code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
import code
from code import softspace
import os
import sys
import wx
import new
def sanitise_text(text):
"""When we process text before saving or executing, we sanitise it
by changing all CR/LF pairs into LF, and then nuking all remaining CRs.
This consistency also ensures that the files we save have the correct
line-endings depending on the operating system we are running on.
It also turns out that things break when after an indentation
level at the very end of the code, there is no empty line. For
example (thanks to Emiel v. IJsseldijk for reproducing!):
def hello():
print "hello" # and this is the last line of the text
Will not completely define method hello.
To remedy this, we add an empty line at the very end if there's
not one already.
"""
text = text.replace('\r\n', '\n')
text = text.replace('\r', '')
lines = text.split('\n')
if lines and len(lines[-1]) != 0:
return text + '\n'
else:
return text
def runcode(self, code):
"""Execute a code object.
Our extra-special verson of the runcode method. We use this when we
want py_shell_mixin._run_source() to generate real exceptions, and
not just output to stdout, for example when CodeRunner is executed
as part of a network. This runcode() is explicitly called by our local
runsource() method.
"""
try:
exec code in self.locals
except SystemExit:
raise
except:
raise
#self.showtraceback()
else:
if softspace(sys.stdout, 0):
print
def runsource(self, source, filename="<input>", symbol="single",
runcode=runcode):
"""Compile and run some source in the interpreter.
Our extra-special verson of the runsource method. We use this when we
want py_shell_mixin._run_source() to generate real exceptions, and
not just output to stdout, for example when CodeRunner is executed
as part of a network. This method calls our special runcode() method
as well.
Arguments are as for compile_command(), but pass in interp instance as
first parameter!
"""
try:
# this could raise OverflowError, SyntaxEror, ValueError
code = self.compile(source, filename, symbol)
except (OverflowError, SyntaxError, ValueError):
# Case 1
raise
#return False
if code is None:
# Case 2
return True
# Case 3
runcode(self, code)
return False
class PythonShellMixin:
def __init__(self, shell_window, module_manager):
# init close handlers
self.close_handlers = []
self.shell_window = shell_window
self.module_manager = module_manager
self._last_fileselector_dir = ''
def close(self, exception_printer):
for ch in self.close_handlers:
try:
ch()
except Exception, e:
exception_printer(
'Exception during PythonShellMixin close_handlers: %s' %
(str(e),))
del self.shell_window
def _open_python_file(self, parent_window):
filename = wx.FileSelector(
'Select file to open into current edit',
self._last_fileselector_dir, "", "py",
"Python files (*.py)|*.py|All files (*.*)|*.*",
wx.OPEN, parent_window)
if filename:
# save directory for future use
self._last_fileselector_dir = \
os.path.dirname(filename)
f = open(filename, 'r')
t = f.read()
t = sanitise_text(t)
f.close()
return filename, t
else:
return (None, None)
def _save_python_file(self, filename, text):
text = sanitise_text(text)
f = open(filename, 'w')
f.write(text)
f.close()
def _saveas_python_file(self, text, parent_window):
filename = wx.FileSelector(
'Select filename to save current edit to',
self._last_fileselector_dir, "", "py",
"Python files (*.py)|*.py|All files (*.*)|*.*",
wx.SAVE, parent_window)
if filename:
# save directory for future use
self._last_fileselector_dir = \
os.path.dirname(filename)
# if the user has NOT specified any fileextension, we
# add .py. (on Win this gets added by the
# FileSelector automatically, on Linux it doesn't)
if os.path.splitext(filename)[1] == '':
filename = '%s.py' % (filename,)
self._save_python_file(filename, text)
return filename
return None
def _run_source(self, text, raise_exceptions=False):
"""Compile and run the source given in text in the shell interpreter's
local namespace.
The idiot pyshell goes through the whole shell.push -> interp.push
-> interp.runsource -> InteractiveInterpreter.runsource hardcoding the
'mode' parameter (effectively) to 'single', thus breaking multi-line
definitions and whatnot.
Here we do some deep magic (ha ha) to externally override the interp
runsource. Python does completely rule.
We do even deeper magic when raise_exceptions is True: we then
raise real exceptions when errors occur instead of just outputting to
stederr.
"""
text = sanitise_text(text)
interp = self.shell_window.interp
if raise_exceptions:
# run our local runsource, don't do any stdout/stderr redirection,
# this is happening as part of a network.
more = runsource(interp, text, '<input>', 'exec')
else:
# our 'traditional' version for normal in-shell introspection and
# execution. Exceptions are turned into nice stdout/stderr
# messages.
stdin, stdout, stderr = sys.stdin, sys.stdout, sys.stderr
sys.stdin, sys.stdout, sys.stderr = \
interp.stdin, interp.stdout, interp.stderr
# look: calling class method with interp instance as first
# parameter comes down to the same as interp calling runsource()
# as its parent method.
more = code.InteractiveInterpreter.runsource(
interp, text, '<input>', 'exec')
# make sure the user can type again
self.shell_window.prompt()
sys.stdin = stdin
sys.stdout = stdout
sys.stderr = stderr
return more
def output_text(self, text):
self.shell_window.write(text + '\n')
self.shell_window.prompt()
def support_vtk(self, interp):
if hasattr(self, 'vtk_renderwindows'):
return
import module_kits
if 'vtk_kit' not in module_kits.module_kit_list:
self.output_text('No VTK support.')
return
from module_kits import vtk_kit
vtk = vtk_kit.vtk
def get_render_info(instance_name):
instance = self.module_manager.get_instance(instance_name)
if instance is None:
return None
class RenderInfo:
pass
render_info = RenderInfo()
render_info.renderer = instance.get_3d_renderer()
render_info.render_window = instance.get_3d_render_window()
render_info.interactor = instance.\
get_3d_render_window_interactor()
return render_info
new_dict = {'vtk' : vtk,
'vtk_get_render_info' : get_render_info}
interp.locals.update(new_dict)
self.__dict__.update(new_dict)
self.output_text('VTK support loaded.')
def support_matplotlib(self, interp):
if hasattr(self, 'mpl_figure_handles'):
return
import module_kits
if 'matplotlib_kit' not in module_kits.module_kit_list:
self.output_text('No matplotlib support.')
return
from module_kits import matplotlib_kit
pylab = matplotlib_kit.pylab
# setup shutdown logic ########################################
self.mpl_figure_handles = []
def mpl_close_handler():
for fh in self.mpl_figure_handles:
pylab.close(fh)
self.close_handlers.append(mpl_close_handler)
# hook our mpl_new_figure method ##############################
# mpl_new_figure hook so that all created figures are registered
# and will be closed when the module is closed
def mpl_new_figure(*args, **kwargs):
handle = pylab.figure(*args, **kwargs)
self.mpl_figure_handles.append(handle)
return handle
def mpl_close_figure(handle):
"""Close matplotlib figure.
"""
pylab.close(handle)
if handle in self.mpl_figure_handles:
idx = self.mpl_figure_handles.index(handle)
del self.mpl_figure_handles[idx]
# replace our hook's documentation with the 'real' documentation
mpl_new_figure.__doc__ = pylab.figure.__doc__
# stuff the required symbols into the module's namespace ######
new_dict = {'matplotlib' : matplotlib_kit.matplotlib,
'pylab' : matplotlib_kit.pylab,
'mpl_new_figure' : mpl_new_figure,
'mpl_close_figure' : mpl_close_figure}
interp.locals.update(new_dict)
self.__dict__.update(new_dict)
self.output_text('matplotlib support loaded.')
| Python |
import wx
from wx import py
class DVShell(py.shell.Shell):
"""DeVIDE shell.
Once again, PyCrust makes some pretty bad calls here and there. With this
override we fix some of them.
1. passing locals=None will result in shell.Shell setting locals to
__main__.__dict__ (!!) in contrast to the default behaviour of the Python
code.InteractiveInterpreter , which is what we do here.
"""
def __init__(self, parent, id=-1, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.CLIP_CHILDREN,
introText='', locals=None, InterpClass=None,
startupScript=None, execStartupScript=False,
*args, **kwds):
# default behaviour for InteractiveInterpreter
if locals is None:
locals = {"__name__": "__console__", "__doc__": None}
py.shell.Shell.__init__(self, parent, id, pos,
size, style,
introText, locals, InterpClass,
startupScript, execStartupScript,
*args, **kwds)
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
import wx
from wx import py
from wx import stc
class DVEditWindow(py.editwindow.EditWindow):
"""DeVIDE EditWindow.
This fixes all of the py screwups by providing a re-usable Python
EditWindow component. The Py components are useful, they've just been put
together in a really unfortunate way. Poor Orbtech.
Note: SaveFile/LoadFile.
@author: Charl P. Botha <http://cpbotha.net/>
"""
def __init__(self, parent, id=-1, pos=wx.DefaultPosition,
size=wx.DefaultSize,
style=wx.CLIP_CHILDREN | wx.SUNKEN_BORDER):
py.editwindow.EditWindow.__init__(self, parent, id, pos, size, style)
self._setup_folding_and_numbers()
self.interp = None
self.observer_modified = None
# we only want insertions and deletions of text to be detected
# by self._handler_modified
self.SetModEventMask(stc.STC_MOD_INSERTTEXT |
stc.STC_MOD_DELETETEXT)
# Assign handlers for keyboard events.
self.Bind(wx.EVT_CHAR, self._handler_char)
self.Bind(stc.EVT_STC_MARGINCLICK, self._handler_marginclick)
self.Bind(stc.EVT_STC_MODIFIED, self._handler_modified)
def _handler_char(self, event):
"""Keypress event handler.
Only receives an event if OnKeyDown calls event.Skip() for the
corresponding event."""
# in wxPython this used to be KeyCode(). In 2.8 it's an ivar.
key = event.KeyCode
if self.interp is None:
event.Skip()
return
if key in self.interp.getAutoCompleteKeys():
# Usually the dot (period) key activates auto completion.
if self.AutoCompActive():
self.AutoCompCancel()
self.ReplaceSelection('')
self.AddText(chr(key))
text, pos = self.GetCurLine()
text = text[:pos]
if self.autoComplete:
self.autoCompleteShow(text)
elif key == ord('('):
# The left paren activates a call tip and cancels an
# active auto completion.
if self.AutoCompActive():
self.AutoCompCancel()
self.ReplaceSelection('')
self.AddText('(')
text, pos = self.GetCurLine()
text = text[:pos]
self.autoCallTipShow(text)
else:
# Allow the normal event handling to take place.
event.Skip()
def _handler_marginclick(self, evt):
# fold and unfold as needed
if evt.GetMargin() == 2:
if evt.GetShift() and evt.GetControl():
self._fold_all()
else:
lineClicked = self.LineFromPosition(evt.GetPosition())
if self.GetFoldLevel(lineClicked) & stc.STC_FOLDLEVELHEADERFLAG:
if evt.GetShift():
self.SetFoldExpanded(lineClicked, True)
self._fold_expand(lineClicked, True, True, 1)
elif evt.GetControl():
if self.GetFoldExpanded(lineClicked):
self.SetFoldExpanded(lineClicked, False)
self._fold_expand(lineClicked, False, True, 0)
else:
self.SetFoldExpanded(lineClicked, True)
self._fold_expand(lineClicked, True, True, 100)
else:
self.ToggleFold(lineClicked)
def _handler_modified(self, evt):
if callable(self.observer_modified):
self.observer_modified(self)
def _fold_all(self):
lineCount = self.GetLineCount()
expanding = True
# find out if we are folding or unfolding
for lineNum in range(lineCount):
if self.GetFoldLevel(lineNum) & stc.STC_FOLDLEVELHEADERFLAG:
expanding = not self.GetFoldExpanded(lineNum)
break
lineNum = 0
while lineNum < lineCount:
level = self.GetFoldLevel(lineNum)
if level & stc.STC_FOLDLEVELHEADERFLAG and \
(level & stc.STC_FOLDLEVELNUMBERMASK) == stc.STC_FOLDLEVELBASE:
if expanding:
self.SetFoldExpanded(lineNum, True)
lineNum = self._fold_expand(lineNum, True)
lineNum = lineNum - 1
else:
lastChild = self.GetLastChild(lineNum, -1)
self.SetFoldExpanded(lineNum, False)
if lastChild > lineNum:
self.HideLines(lineNum+1, lastChild)
lineNum = lineNum + 1
def _fold_expand(self, line, doExpand, force=False, visLevels=0, level=-1):
lastChild = self.GetLastChild(line, level)
line = line + 1
while line <= lastChild:
if force:
if visLevels > 0:
self.ShowLines(line, line)
else:
self.HideLines(line, line)
else:
if doExpand:
self.ShowLines(line, line)
if level == -1:
level = self.GetFoldLevel(line)
if level & stc.STC_FOLDLEVELHEADERFLAG:
if force:
if visLevels > 1:
self.SetFoldExpanded(line, True)
else:
self.SetFoldExpanded(line, False)
line = self._fold_expand(line, doExpand, force, visLevels-1)
else:
if doExpand and self.GetFoldExpanded(line):
line = self._fold_expand(line, True, force, visLevels-1)
else:
line = self._fold_expand(
line, False, force, visLevels-1)
else:
line = line + 1
return line
def _setup_folding_and_numbers(self):
# from our direct ancestor
self.setDisplayLineNumbers(True)
# the rest is from the wxPython StyledControl_2 demo
self.SetProperty("fold", "1")
self.SetMargins(0,0)
self.SetEdgeMode(stc.STC_EDGE_BACKGROUND)
self.SetEdgeColumn(78)
self.SetMarginType(2, stc.STC_MARGIN_SYMBOL)
self.SetMarginMask(2, stc.STC_MASK_FOLDERS)
self.SetMarginSensitive(2, True)
self.SetMarginWidth(2, 12)
# Like a flattened tree control using circular headers and curved joins
self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN,
stc.STC_MARK_CIRCLEMINUS, "white", "#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDER,
stc.STC_MARK_CIRCLEPLUS, "white", "#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB,
stc.STC_MARK_VLINE, "white", "#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL,
stc.STC_MARK_LCORNERCURVE, "white", "#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND,
stc.STC_MARK_CIRCLEPLUSCONNECTED, "white", "#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID,
stc.STC_MARK_CIRCLEMINUSCONNECTED, "white",
"#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL,
stc.STC_MARK_TCORNERCURVE, "white", "#404040")
def set_interp(self, interp):
"""Assign new py.Interpreter instance to this EditWindow.
This instance will be used for autocompletion. This is often a
py.Shell's interp instance.
"""
self.interp = interp
def autoCallTipShow(self, command):
"""Display argument spec and docstring in a popup window."""
if self.interp is None:
return
if self.CallTipActive():
self.CallTipCancel()
(name, argspec, tip) = self.interp.getCallTip(command)
# if tip:
# dispatcher.send(signal='Shell.calltip', sender=self,
# calltip=tip)
if not self.autoCallTip:
return
if argspec:
startpos = self.GetCurrentPos()
self.AddText(argspec + ')')
endpos = self.GetCurrentPos()
self.SetSelection(endpos, startpos)
if tip:
curpos = self.GetCurrentPos()
size = len(name)
tippos = curpos - (size + 1)
fallback = curpos - self.GetColumn(curpos)
# In case there isn't enough room, only go back to the
# fallback.
tippos = max(tippos, fallback)
self.CallTipShow(tippos, tip)
self.CallTipSetHighlight(0, size)
def autoCompleteShow(self, command):
"""Display auto-completion popup list."""
if self.interp is None:
return
list = self.interp.getAutoCompleteList(
command,
includeMagic=self.autoCompleteIncludeMagic,
includeSingle=self.autoCompleteIncludeSingle,
includeDouble=self.autoCompleteIncludeDouble)
if list:
options = ' '.join(list)
offset = 0
self.AutoCompShow(offset, options)
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
# importing this module shouldn't directly cause other large imports
# do large imports in the init() hook so that you can call back to the
# ModuleManager progress handler methods.
"""wxpython_kit package driver file.
Inserts the following modules in sys.modules: wx.
@author: Charl P. Botha <http://cpbotha.net/>
"""
# you have to define this
VERSION = ''
def init(theModuleManager, pre_import=True):
# import the main module itself
global wx
import wx
import dvedit_window
import dvshell
import python_shell_mixin
import python_shell
import utils
# build up VERSION
global VERSION
VERSION = wx.VERSION_STRING
theModuleManager.setProgress(100, 'Initialising wx_kit')
| Python |
# Copyright (c) 1999-2002 Gary Strangman; All Rights Reserved.
#
# This software is distributable under the terms of the GNU
# General Public License (GPL) v2, the text of which can be found at
# http://www.gnu.org/copyleft/gpl.html. Installing, importing or otherwise
# using this module constitutes acceptance of the terms of this License.
#
# Disclaimer
#
# This software is provided "as-is". There are no expressed or implied
# warranties of any kind, including, but not limited to, the warranties
# of merchantability and fittness for a given application. In no event
# shall Gary Strangman be liable for any direct, indirect, incidental,
# special, exemplary or consequential damages (including, but not limited
# to, loss of use, data or profits, or business interruption) however
# caused and on any theory of liability, whether in contract, strict
# liability or tort (including negligence or otherwise) arising in any way
# out of the use of this software, even if advised of the possibility of
# such damage.
#
# Comments and/or additions are welcome (send e-mail to:
# strang@nmr.mgh.harvard.edu).
#
"""
stats.py module
(Requires pstat.py module.)
#################################################
####### Written by: Gary Strangman ###########
####### Last modified: May 10, 2002 ###########
#################################################
A collection of basic statistical functions for python. The function
names appear below.
IMPORTANT: There are really *3* sets of functions. The first set has an 'l'
prefix, which can be used with list or tuple arguments. The second set has
an 'a' prefix, which can accept NumPy array arguments. These latter
functions are defined only when NumPy is available on the system. The third
type has NO prefix (i.e., has the name that appears below). Functions of
this set are members of a "Dispatch" class, c/o David Ascher. This class
allows different functions to be called depending on the type of the passed
arguments. Thus, stats.mean is a member of the Dispatch class and
stats.mean(range(20)) will call stats.lmean(range(20)) while
stats.mean(Numeric.arange(20)) will call stats.amean(Numeric.arange(20)).
This is a handy way to keep consistent function names when different
argument types require different functions to be called. Having
implementated the Dispatch class, however, means that to get info on
a given function, you must use the REAL function name ... that is
"print stats.lmean.__doc__" or "print stats.amean.__doc__" work fine,
while "print stats.mean.__doc__" will print the doc for the Dispatch
class. NUMPY FUNCTIONS ('a' prefix) generally have more argument options
but should otherwise be consistent with the corresponding list functions.
Disclaimers: The function list is obviously incomplete and, worse, the
functions are not optimized. All functions have been tested (some more
so than others), but they are far from bulletproof. Thus, as with any
free software, no warranty or guarantee is expressed or implied. :-) A
few extra functions that don't appear in the list below can be found by
interested treasure-hunters. These functions don't necessarily have
both list and array versions but were deemed useful
CENTRAL TENDENCY: geometricmean
harmonicmean
mean
median
medianscore
mode
MOMENTS: moment
variation
skew
kurtosis
skewtest (for Numpy arrays only)
kurtosistest (for Numpy arrays only)
normaltest (for Numpy arrays only)
ALTERED VERSIONS: tmean (for Numpy arrays only)
tvar (for Numpy arrays only)
tmin (for Numpy arrays only)
tmax (for Numpy arrays only)
tstdev (for Numpy arrays only)
tsem (for Numpy arrays only)
describe
FREQUENCY STATS: itemfreq
scoreatpercentile
percentileofscore
histogram
cumfreq
relfreq
VARIABILITY: obrientransform
samplevar
samplestdev
signaltonoise (for Numpy arrays only)
var
stdev
sterr
sem
z
zs
zmap (for Numpy arrays only)
TRIMMING FCNS: threshold (for Numpy arrays only)
trimboth
trim1
round (round all vals to 'n' decimals; Numpy only)
CORRELATION FCNS: covariance (for Numpy arrays only)
correlation (for Numpy arrays only)
paired
pearsonr
spearmanr
pointbiserialr
kendalltau
linregress
INFERENTIAL STATS: ttest_1samp
ttest_ind
ttest_rel
chisquare
ks_2samp
mannwhitneyu
ranksums
wilcoxont
kruskalwallish
friedmanchisquare
PROBABILITY CALCS: chisqprob
erfcc
zprob
ksprob
fprob
betacf
gammln
betai
ANOVA FUNCTIONS: F_oneway
F_value
SUPPORT FUNCTIONS: writecc
incr
sign (for Numpy arrays only)
sum
cumsum
ss
summult
sumdiffsquared
square_of_sums
shellsort
rankdata
outputpairedstats
findwithin
"""
## CHANGE LOG:
## ===========
## 02-11-19 ... fixed attest_ind and attest_rel for div-by-zero Overflows
## 02-05-10 ... fixed lchisqprob indentation (failed when df=even)
## 00-12-28 ... removed aanova() to separate module, fixed licensing to
## match Python License, fixed doc string & imports
## 00-04-13 ... pulled all "global" statements, except from aanova()
## added/fixed lots of documentation, removed io.py dependency
## changed to version 0.5
## 99-11-13 ... added asign() function
## 99-11-01 ... changed version to 0.4 ... enough incremental changes now
## 99-10-25 ... added acovariance and acorrelation functions
## 99-10-10 ... fixed askew/akurtosis to avoid divide-by-zero errors
## added aglm function (crude, but will be improved)
## 99-10-04 ... upgraded acumsum, ass, asummult, asamplevar, avar, etc. to
## all handle lists of 'dimension's and keepdims
## REMOVED ar0, ar2, ar3, ar4 and replaced them with around
## reinserted fixes for abetai to avoid math overflows
## 99-09-05 ... rewrote achisqprob/aerfcc/aksprob/afprob/abetacf/abetai to
## handle multi-dimensional arrays (whew!)
## 99-08-30 ... fixed l/amoment, l/askew, l/akurtosis per D'Agostino (1990)
## added anormaltest per same reference
## re-wrote azprob to calc arrays of probs all at once
## 99-08-22 ... edited attest_ind printing section so arrays could be rounded
## 99-08-19 ... fixed amean and aharmonicmean for non-error(!) overflow on
## short/byte arrays (mean of #s btw 100-300 = -150??)
## 99-08-09 ... fixed asum so that the None case works for Byte arrays
## 99-08-08 ... fixed 7/3 'improvement' to handle t-calcs on N-D arrays
## 99-07-03 ... improved attest_ind, attest_rel (zero-division errortrap)
## 99-06-24 ... fixed bug(?) in attest_ind (n1=a.shape[0])
## 04/11/99 ... added asignaltonoise, athreshold functions, changed all
## max/min in array section to N.maximum/N.minimum,
## fixed square_of_sums to prevent integer overflow
## 04/10/99 ... !!! Changed function name ... sumsquared ==> square_of_sums
## 03/18/99 ... Added ar0, ar2, ar3 and ar4 rounding functions
## 02/28/99 ... Fixed aobrientransform to return an array rather than a list
## 01/15/99 ... Essentially ceased updating list-versions of functions (!!!)
## 01/13/99 ... CHANGED TO VERSION 0.3
## fixed bug in a/lmannwhitneyu p-value calculation
## 12/31/98 ... fixed variable-name bug in ldescribe
## 12/19/98 ... fixed bug in findwithin (fcns needed pstat. prefix)
## 12/16/98 ... changed amedianscore to return float (not array) for 1 score
## 12/14/98 ... added atmin and atmax functions
## removed umath from import line (not needed)
## l/ageometricmean modified to reduce chance of overflows (take
## nth root first, then multiply)
## 12/07/98 ... added __version__variable (now 0.2)
## removed all 'stats.' from anova() fcn
## 12/06/98 ... changed those functions (except shellsort) that altered
## arguments in-place ... cumsum, ranksort, ...
## updated (and fixed some) doc-strings
## 12/01/98 ... added anova() function (requires NumPy)
## incorporated Dispatch class
## 11/12/98 ... added functionality to amean, aharmonicmean, ageometricmean
## added 'asum' function (added functionality to N.add.reduce)
## fixed both moment and amoment (two errors)
## changed name of skewness and askewness to skew and askew
## fixed (a)histogram (which sometimes counted points <lowerlimit)
import pstat # required 3rd party module
import math, string, copy # required python modules
from types import *
__version__ = 0.6
############# DISPATCH CODE ##############
class Dispatch:
"""
The Dispatch class, care of David Ascher, allows different functions to
be called depending on the argument types. This way, there can be one
function name regardless of the argument type. To access function doc
in stats.py module, prefix the function with an 'l' or 'a' for list or
array arguments, respectively. That is, print stats.lmean.__doc__ or
print stats.amean.__doc__ or whatever.
"""
def __init__(self, *tuples):
self._dispatch = {}
for func, types in tuples:
for t in types:
if t in self._dispatch.keys():
raise ValueError, "can't have two dispatches on "+str(t)
self._dispatch[t] = func
self._types = self._dispatch.keys()
def __call__(self, arg1, *args, **kw):
if type(arg1) not in self._types:
raise TypeError, "don't know how to dispatch %s arguments" % type(arg1)
return apply(self._dispatch[type(arg1)], (arg1,) + args, kw)
##########################################################################
######################## LIST-BASED FUNCTIONS ########################
##########################################################################
### Define these regardless
####################################
####### CENTRAL TENDENCY #########
####################################
def lgeometricmean (inlist):
"""
Calculates the geometric mean of the values in the passed list.
That is: n-th root of (x1 * x2 * ... * xn). Assumes a '1D' list.
Usage: lgeometricmean(inlist)
"""
mult = 1.0
one_over_n = 1.0/len(inlist)
for item in inlist:
mult = mult * pow(item,one_over_n)
return mult
def lharmonicmean (inlist):
"""
Calculates the harmonic mean of the values in the passed list.
That is: n / (1/x1 + 1/x2 + ... + 1/xn). Assumes a '1D' list.
Usage: lharmonicmean(inlist)
"""
sum = 0
for item in inlist:
sum = sum + 1.0/item
return len(inlist) / sum
def lmean (inlist):
"""
Returns the arithematic mean of the values in the passed list.
Assumes a '1D' list, but will function on the 1st dim of an array(!).
Usage: lmean(inlist)
"""
sum = 0
for item in inlist:
sum = sum + item
return sum/float(len(inlist))
def lmedian (inlist,numbins=1000):
"""
Returns the computed median value of a list of numbers, given the
number of bins to use for the histogram (more bins brings the computed value
closer to the median score, default number of bins = 1000). See G.W.
Heiman's Basic Stats (1st Edition), or CRC Probability & Statistics.
Usage: lmedian (inlist, numbins=1000)
"""
(hist, smallest, binsize, extras) = histogram(inlist,numbins) # make histog
cumhist = cumsum(hist) # make cumulative histogram
for i in range(len(cumhist)): # get 1st(!) index holding 50%ile score
if cumhist[i]>=len(inlist)/2.0:
cfbin = i
break
LRL = smallest + binsize*cfbin # get lower read limit of that bin
cfbelow = cumhist[cfbin-1]
freq = float(hist[cfbin]) # frequency IN the 50%ile bin
median = LRL + ((len(inlist)/2.0 - cfbelow)/float(freq))*binsize # median formula
return median
def lmedianscore (inlist):
"""
Returns the 'middle' score of the passed list. If there is an even
number of scores, the mean of the 2 middle scores is returned.
Usage: lmedianscore(inlist)
"""
newlist = copy.deepcopy(inlist)
newlist.sort()
if len(newlist) % 2 == 0: # if even number of scores, average middle 2
index = len(newlist)/2 # integer division correct
median = float(newlist[index] + newlist[index-1]) /2
else:
index = len(newlist)/2 # int divsion gives mid value when count from 0
median = newlist[index]
return median
def lmode(inlist):
"""
Returns a list of the modal (most common) score(s) in the passed
list. If there is more than one such score, all are returned. The
bin-count for the mode(s) is also returned.
Usage: lmode(inlist)
Returns: bin-count for mode(s), a list of modal value(s)
"""
scores = pstat.unique(inlist)
scores.sort()
freq = []
for item in scores:
freq.append(inlist.count(item))
maxfreq = max(freq)
mode = []
stillmore = 1
while stillmore:
try:
indx = freq.index(maxfreq)
mode.append(scores[indx])
del freq[indx]
del scores[indx]
except ValueError:
stillmore=0
return maxfreq, mode
####################################
############ MOMENTS #############
####################################
def lmoment(inlist,moment=1):
"""
Calculates the nth moment about the mean for a sample (defaults to
the 1st moment). Used to calculate coefficients of skewness and kurtosis.
Usage: lmoment(inlist,moment=1)
Returns: appropriate moment (r) from ... 1/n * SUM((inlist(i)-mean)**r)
"""
if moment == 1:
return 0.0
else:
mn = mean(inlist)
n = len(inlist)
s = 0
for x in inlist:
s = s + (x-mn)**moment
return s/float(n)
def lvariation(inlist):
"""
Returns the coefficient of variation, as defined in CRC Standard
Probability and Statistics, p.6.
Usage: lvariation(inlist)
"""
return 100.0*samplestdev(inlist)/float(mean(inlist))
def lskew(inlist):
"""
Returns the skewness of a distribution, as defined in Numerical
Recipies (alternate defn in CRC Standard Probability and Statistics, p.6.)
Usage: lskew(inlist)
"""
return moment(inlist,3)/pow(moment(inlist,2),1.5)
def lkurtosis(inlist):
"""
Returns the kurtosis of a distribution, as defined in Numerical
Recipies (alternate defn in CRC Standard Probability and Statistics, p.6.)
Usage: lkurtosis(inlist)
"""
return moment(inlist,4)/pow(moment(inlist,2),2.0)
def ldescribe(inlist):
"""
Returns some descriptive statistics of the passed list (assumed to be 1D).
Usage: ldescribe(inlist)
Returns: n, mean, standard deviation, skew, kurtosis
"""
n = len(inlist)
mm = (min(inlist),max(inlist))
m = mean(inlist)
sd = stdev(inlist)
sk = skew(inlist)
kurt = kurtosis(inlist)
return n, mm, m, sd, sk, kurt
####################################
####### FREQUENCY STATS ##########
####################################
def litemfreq(inlist):
"""
Returns a list of pairs. Each pair consists of one of the scores in inlist
and it's frequency count. Assumes a 1D list is passed.
Usage: litemfreq(inlist)
Returns: a 2D frequency table (col [0:n-1]=scores, col n=frequencies)
"""
scores = pstat.unique(inlist)
scores.sort()
freq = []
for item in scores:
freq.append(inlist.count(item))
return pstat.abut(scores, freq)
def lscoreatpercentile (inlist, percent):
"""
Returns the score at a given percentile relative to the distribution
given by inlist.
Usage: lscoreatpercentile(inlist,percent)
"""
if percent > 1:
print "\nDividing percent>1 by 100 in lscoreatpercentile().\n"
percent = percent / 100.0
targetcf = percent*len(inlist)
h, lrl, binsize, extras = histogram(inlist)
cumhist = cumsum(copy.deepcopy(h))
for i in range(len(cumhist)):
if cumhist[i] >= targetcf:
break
score = binsize * ((targetcf - cumhist[i-1]) / float(h[i])) + (lrl+binsize*i)
return score
def lpercentileofscore (inlist, score,histbins=10,defaultlimits=None):
"""
Returns the percentile value of a score relative to the distribution
given by inlist. Formula depends on the values used to histogram the data(!).
Usage: lpercentileofscore(inlist,score,histbins=10,defaultlimits=None)
"""
h, lrl, binsize, extras = histogram(inlist,histbins,defaultlimits)
cumhist = cumsum(copy.deepcopy(h))
i = int((score - lrl)/float(binsize))
pct = (cumhist[i-1]+((score-(lrl+binsize*i))/float(binsize))*h[i])/float(len(inlist)) * 100
return pct
def lhistogram (inlist,numbins=10,defaultreallimits=None,printextras=0):
"""
Returns (i) a list of histogram bin counts, (ii) the smallest value
of the histogram binning, and (iii) the bin width (the last 2 are not
necessarily integers). Default number of bins is 10. If no sequence object
is given for defaultreallimits, the routine picks (usually non-pretty) bins
spanning all the numbers in the inlist.
Usage: lhistogram (inlist, numbins=10, defaultreallimits=None,suppressoutput=0)
Returns: list of bin values, lowerreallimit, binsize, extrapoints
"""
if (defaultreallimits <> None):
if type(defaultreallimits) not in [ListType,TupleType] or len(defaultreallimits)==1: # only one limit given, assumed to be lower one & upper is calc'd
lowerreallimit = defaultreallimits
upperreallimit = 1.0001 * max(inlist)
else: # assume both limits given
lowerreallimit = defaultreallimits[0]
upperreallimit = defaultreallimits[1]
binsize = (upperreallimit-lowerreallimit)/float(numbins)
else: # no limits given for histogram, both must be calc'd
estbinwidth=(max(inlist)-min(inlist))/float(numbins) + 1 # 1=>cover all
binsize = ((max(inlist)-min(inlist)+estbinwidth))/float(numbins)
lowerreallimit = min(inlist) - binsize/2 #lower real limit,1st bin
bins = [0]*(numbins)
extrapoints = 0
for num in inlist:
try:
if (num-lowerreallimit) < 0:
extrapoints = extrapoints + 1
else:
bintoincrement = int((num-lowerreallimit)/float(binsize))
bins[bintoincrement] = bins[bintoincrement] + 1
except:
extrapoints = extrapoints + 1
if (extrapoints > 0 and printextras == 1):
print '\nPoints outside given histogram range =',extrapoints
return (bins, lowerreallimit, binsize, extrapoints)
def lcumfreq(inlist,numbins=10,defaultreallimits=None):
"""
Returns a cumulative frequency histogram, using the histogram function.
Usage: lcumfreq(inlist,numbins=10,defaultreallimits=None)
Returns: list of cumfreq bin values, lowerreallimit, binsize, extrapoints
"""
h,l,b,e = histogram(inlist,numbins,defaultreallimits)
cumhist = cumsum(copy.deepcopy(h))
return cumhist,l,b,e
def lrelfreq(inlist,numbins=10,defaultreallimits=None):
"""
Returns a relative frequency histogram, using the histogram function.
Usage: lrelfreq(inlist,numbins=10,defaultreallimits=None)
Returns: list of cumfreq bin values, lowerreallimit, binsize, extrapoints
"""
h,l,b,e = histogram(inlist,numbins,defaultreallimits)
for i in range(len(h)):
h[i] = h[i]/float(len(inlist))
return h,l,b,e
####################################
##### VARIABILITY FUNCTIONS ######
####################################
def lobrientransform(*args):
"""
Computes a transform on input data (any number of columns). Used to
test for homogeneity of variance prior to running one-way stats. From
Maxwell and Delaney, p.112.
Usage: lobrientransform(*args)
Returns: transformed data for use in an ANOVA
"""
TINY = 1e-10
k = len(args)
n = [0.0]*k
v = [0.0]*k
m = [0.0]*k
nargs = []
for i in range(k):
nargs.append(copy.deepcopy(args[i]))
n[i] = float(len(nargs[i]))
v[i] = var(nargs[i])
m[i] = mean(nargs[i])
for j in range(k):
for i in range(n[j]):
t1 = (n[j]-1.5)*n[j]*(nargs[j][i]-m[j])**2
t2 = 0.5*v[j]*(n[j]-1.0)
t3 = (n[j]-1.0)*(n[j]-2.0)
nargs[j][i] = (t1-t2) / float(t3)
check = 1
for j in range(k):
if v[j] - mean(nargs[j]) > TINY:
check = 0
if check <> 1:
raise ValueError, 'Problem in obrientransform.'
else:
return nargs
def lsamplevar (inlist):
"""
Returns the variance of the values in the passed list using
N for the denominator (i.e., DESCRIBES the sample variance only).
Usage: lsamplevar(inlist)
"""
n = len(inlist)
mn = mean(inlist)
deviations = []
for item in inlist:
deviations.append(item-mn)
return ss(deviations)/float(n)
def lsamplestdev (inlist):
"""
Returns the standard deviation of the values in the passed list using
N for the denominator (i.e., DESCRIBES the sample stdev only).
Usage: lsamplestdev(inlist)
"""
return math.sqrt(samplevar(inlist))
def lvar (inlist):
"""
Returns the variance of the values in the passed list using N-1
for the denominator (i.e., for estimating population variance).
Usage: lvar(inlist)
"""
n = len(inlist)
mn = mean(inlist)
deviations = [0]*len(inlist)
for i in range(len(inlist)):
deviations[i] = inlist[i] - mn
return ss(deviations)/float(n-1)
def lstdev (inlist):
"""
Returns the standard deviation of the values in the passed list
using N-1 in the denominator (i.e., to estimate population stdev).
Usage: lstdev(inlist)
"""
return math.sqrt(var(inlist))
def lsterr(inlist):
"""
Returns the standard error of the values in the passed list using N-1
in the denominator (i.e., to estimate population standard error).
Usage: lsterr(inlist)
"""
return stdev(inlist) / float(math.sqrt(len(inlist)))
def lsem (inlist):
"""
Returns the estimated standard error of the mean (sx-bar) of the
values in the passed list. sem = stdev / sqrt(n)
Usage: lsem(inlist)
"""
sd = stdev(inlist)
n = len(inlist)
return sd/math.sqrt(n)
def lz (inlist, score):
"""
Returns the z-score for a given input score, given that score and the
list from which that score came. Not appropriate for population calculations.
Usage: lz(inlist, score)
"""
z = (score-mean(inlist))/samplestdev(inlist)
return z
def lzs (inlist):
"""
Returns a list of z-scores, one for each score in the passed list.
Usage: lzs(inlist)
"""
zscores = []
for item in inlist:
zscores.append(z(inlist,item))
return zscores
####################################
####### TRIMMING FUNCTIONS #######
####################################
def ltrimboth (l,proportiontocut):
"""
Slices off the passed proportion of items from BOTH ends of the passed
list (i.e., with proportiontocut=0.1, slices 'leftmost' 10% AND 'rightmost'
10% of scores. Assumes list is sorted by magnitude. Slices off LESS if
proportion results in a non-integer slice index (i.e., conservatively
slices off proportiontocut).
Usage: ltrimboth (l,proportiontocut)
Returns: trimmed version of list l
"""
lowercut = int(proportiontocut*len(l))
uppercut = len(l) - lowercut
return l[lowercut:uppercut]
def ltrim1 (l,proportiontocut,tail='right'):
"""
Slices off the passed proportion of items from ONE end of the passed
list (i.e., if proportiontocut=0.1, slices off 'leftmost' or 'rightmost'
10% of scores). Slices off LESS if proportion results in a non-integer
slice index (i.e., conservatively slices off proportiontocut).
Usage: ltrim1 (l,proportiontocut,tail='right') or set tail='left'
Returns: trimmed version of list l
"""
if tail == 'right':
lowercut = 0
uppercut = len(l) - int(proportiontocut*len(l))
elif tail == 'left':
lowercut = int(proportiontocut*len(l))
uppercut = len(l)
return l[lowercut:uppercut]
####################################
##### CORRELATION FUNCTIONS ######
####################################
def lpaired(x,y):
"""
Interactively determines the type of data and then runs the
appropriated statistic for paired group data.
Usage: lpaired(x,y)
Returns: appropriate statistic name, value, and probability
"""
samples = ''
while samples not in ['i','r','I','R','c','C']:
print '\nIndependent or related samples, or correlation (i,r,c): ',
samples = raw_input()
if samples in ['i','I','r','R']:
print '\nComparing variances ...',
# USE O'BRIEN'S TEST FOR HOMOGENEITY OF VARIANCE, Maxwell & delaney, p.112
r = obrientransform(x,y)
f,p = F_oneway(pstat.colex(r,0),pstat.colex(r,1))
if p<0.05:
vartype='unequal, p='+str(round(p,4))
else:
vartype='equal'
print vartype
if samples in ['i','I']:
if vartype[0]=='e':
t,p = ttest_ind(x,y,0)
print '\nIndependent samples t-test: ', round(t,4),round(p,4)
else:
if len(x)>20 or len(y)>20:
z,p = ranksums(x,y)
print '\nRank Sums test (NONparametric, n>20): ', round(z,4),round(p,4)
else:
u,p = mannwhitneyu(x,y)
print '\nMann-Whitney U-test (NONparametric, ns<20): ', round(u,4),round(p,4)
else: # RELATED SAMPLES
if vartype[0]=='e':
t,p = ttest_rel(x,y,0)
print '\nRelated samples t-test: ', round(t,4),round(p,4)
else:
t,p = ranksums(x,y)
print '\nWilcoxon T-test (NONparametric): ', round(t,4),round(p,4)
else: # CORRELATION ANALYSIS
corrtype = ''
while corrtype not in ['c','C','r','R','d','D']:
print '\nIs the data Continuous, Ranked, or Dichotomous (c,r,d): ',
corrtype = raw_input()
if corrtype in ['c','C']:
m,b,r,p,see = linregress(x,y)
print '\nLinear regression for continuous variables ...'
lol = [['Slope','Intercept','r','Prob','SEestimate'],[round(m,4),round(b,4),round(r,4),round(p,4),round(see,4)]]
pstat.printcc(lol)
elif corrtype in ['r','R']:
r,p = spearmanr(x,y)
print '\nCorrelation for ranked variables ...'
print "Spearman's r: ",round(r,4),round(p,4)
else: # DICHOTOMOUS
r,p = pointbiserialr(x,y)
print '\nAssuming x contains a dichotomous variable ...'
print 'Point Biserial r: ',round(r,4),round(p,4)
print '\n\n'
return None
def lpearsonr(x,y):
"""
Calculates a Pearson correlation coefficient and the associated
probability value. Taken from Heiman's Basic Statistics for the Behav.
Sci (2nd), p.195.
Usage: lpearsonr(x,y) where x and y are equal-length lists
Returns: Pearson's r value, two-tailed p-value
"""
TINY = 1.0e-30
if len(x) <> len(y):
raise ValueError, 'Input values not paired in pearsonr. Aborting.'
n = len(x)
x = map(float,x)
y = map(float,y)
xmean = mean(x)
ymean = mean(y)
r_num = n*(summult(x,y)) - sum(x)*sum(y)
r_den = math.sqrt((n*ss(x) - square_of_sums(x))*(n*ss(y)-square_of_sums(y)))
r = (r_num / r_den) # denominator already a float
df = n-2
t = r*math.sqrt(df/((1.0-r+TINY)*(1.0+r+TINY)))
prob = betai(0.5*df,0.5,df/float(df+t*t))
return r, prob
def lspearmanr(x,y):
"""
Calculates a Spearman rank-order correlation coefficient. Taken
from Heiman's Basic Statistics for the Behav. Sci (1st), p.192.
Usage: lspearmanr(x,y) where x and y are equal-length lists
Returns: Spearman's r, two-tailed p-value
"""
TINY = 1e-30
if len(x) <> len(y):
raise ValueError, 'Input values not paired in spearmanr. Aborting.'
n = len(x)
rankx = rankdata(x)
ranky = rankdata(y)
dsq = sumdiffsquared(rankx,ranky)
rs = 1 - 6*dsq / float(n*(n**2-1))
t = rs * math.sqrt((n-2) / ((rs+1.0)*(1.0-rs)))
df = n-2
probrs = betai(0.5*df,0.5,df/(df+t*t)) # t already a float
# probability values for rs are from part 2 of the spearman function in
# Numerical Recipies, p.510. They are close to tables, but not exact. (?)
return rs, probrs
def lpointbiserialr(x,y):
"""
Calculates a point-biserial correlation coefficient and the associated
probability value. Taken from Heiman's Basic Statistics for the Behav.
Sci (1st), p.194.
Usage: lpointbiserialr(x,y) where x,y are equal-length lists
Returns: Point-biserial r, two-tailed p-value
"""
TINY = 1e-30
if len(x) <> len(y):
raise ValueError, 'INPUT VALUES NOT PAIRED IN pointbiserialr. ABORTING.'
data = pstat.abut(x,y)
categories = pstat.unique(x)
if len(categories) <> 2:
raise ValueError, "Exactly 2 categories required for pointbiserialr()."
else: # there are 2 categories, continue
codemap = pstat.abut(categories,range(2))
recoded = pstat.recode(data,codemap,0)
x = pstat.linexand(data,0,categories[0])
y = pstat.linexand(data,0,categories[1])
xmean = mean(pstat.colex(x,1))
ymean = mean(pstat.colex(y,1))
n = len(data)
adjust = math.sqrt((len(x)/float(n))*(len(y)/float(n)))
rpb = (ymean - xmean)/samplestdev(pstat.colex(data,1))*adjust
df = n-2
t = rpb*math.sqrt(df/((1.0-rpb+TINY)*(1.0+rpb+TINY)))
prob = betai(0.5*df,0.5,df/(df+t*t)) # t already a float
return rpb, prob
def lkendalltau(x,y):
"""
Calculates Kendall's tau ... correlation of ordinal data. Adapted
from function kendl1 in Numerical Recipies. Needs good test-routine.@@@
Usage: lkendalltau(x,y)
Returns: Kendall's tau, two-tailed p-value
"""
n1 = 0
n2 = 0
iss = 0
for j in range(len(x)-1):
for k in range(j,len(y)):
a1 = x[j] - x[k]
a2 = y[j] - y[k]
aa = a1 * a2
if (aa): # neither list has a tie
n1 = n1 + 1
n2 = n2 + 1
if aa > 0:
iss = iss + 1
else:
iss = iss -1
else:
if (a1):
n1 = n1 + 1
else:
n2 = n2 + 1
tau = iss / math.sqrt(n1*n2)
svar = (4.0*len(x)+10.0) / (9.0*len(x)*(len(x)-1))
z = tau / math.sqrt(svar)
prob = erfcc(abs(z)/1.4142136)
return tau, prob
def llinregress(x,y):
"""
Calculates a regression line on x,y pairs.
Usage: llinregress(x,y) x,y are equal-length lists of x-y coordinates
Returns: slope, intercept, r, two-tailed prob, sterr-of-estimate
"""
TINY = 1.0e-20
if len(x) <> len(y):
raise ValueError, 'Input values not paired in linregress. Aborting.'
n = len(x)
x = map(float,x)
y = map(float,y)
xmean = mean(x)
ymean = mean(y)
r_num = float(n*(summult(x,y)) - sum(x)*sum(y))
r_den = math.sqrt((n*ss(x) - square_of_sums(x))*(n*ss(y)-square_of_sums(y)))
r = r_num / r_den
z = 0.5*math.log((1.0+r+TINY)/(1.0-r+TINY))
df = n-2
t = r*math.sqrt(df/((1.0-r+TINY)*(1.0+r+TINY)))
prob = betai(0.5*df,0.5,df/(df+t*t))
slope = r_num / float(n*ss(x) - square_of_sums(x))
intercept = ymean - slope*xmean
sterrest = math.sqrt(1-r*r)*samplestdev(y)
return slope, intercept, r, prob, sterrest
####################################
##### INFERENTIAL STATISTICS #####
####################################
def lttest_1samp(a,popmean,printit=0,name='Sample',writemode='a'):
"""
Calculates the t-obtained for the independent samples T-test on ONE group
of scores a, given a population mean. If printit=1, results are printed
to the screen. If printit='filename', the results are output to 'filename'
using the given writemode (default=append). Returns t-value, and prob.
Usage: lttest_1samp(a,popmean,Name='Sample',printit=0,writemode='a')
Returns: t-value, two-tailed prob
"""
x = mean(a)
v = var(a)
n = len(a)
df = n-1
svar = ((n-1)*v)/float(df)
t = (x-popmean)/math.sqrt(svar*(1.0/n))
prob = betai(0.5*df,0.5,float(df)/(df+t*t))
if printit <> 0:
statname = 'Single-sample T-test.'
outputpairedstats(printit,writemode,
'Population','--',popmean,0,0,0,
name,n,x,v,min(a),max(a),
statname,t,prob)
return t,prob
def lttest_ind (a, b, printit=0, name1='Samp1', name2='Samp2', writemode='a'):
"""
Calculates the t-obtained T-test on TWO INDEPENDENT samples of
scores a, and b. From Numerical Recipies, p.483. If printit=1, results
are printed to the screen. If printit='filename', the results are output
to 'filename' using the given writemode (default=append). Returns t-value,
and prob.
Usage: lttest_ind(a,b,printit=0,name1='Samp1',name2='Samp2',writemode='a')
Returns: t-value, two-tailed prob
"""
x1 = mean(a)
x2 = mean(b)
v1 = stdev(a)**2
v2 = stdev(b)**2
n1 = len(a)
n2 = len(b)
df = n1+n2-2
svar = ((n1-1)*v1+(n2-1)*v2)/float(df)
t = (x1-x2)/math.sqrt(svar*(1.0/n1 + 1.0/n2))
prob = betai(0.5*df,0.5,df/(df+t*t))
if printit <> 0:
statname = 'Independent samples T-test.'
outputpairedstats(printit,writemode,
name1,n1,x1,v1,min(a),max(a),
name2,n2,x2,v2,min(b),max(b),
statname,t,prob)
return t,prob
def lttest_rel (a,b,printit=0,name1='Sample1',name2='Sample2',writemode='a'):
"""
Calculates the t-obtained T-test on TWO RELATED samples of scores,
a and b. From Numerical Recipies, p.483. If printit=1, results are
printed to the screen. If printit='filename', the results are output to
'filename' using the given writemode (default=append). Returns t-value,
and prob.
Usage: lttest_rel(a,b,printit=0,name1='Sample1',name2='Sample2',writemode='a')
Returns: t-value, two-tailed prob
"""
if len(a)<>len(b):
raise ValueError, 'Unequal length lists in ttest_rel.'
x1 = mean(a)
x2 = mean(b)
v1 = var(a)
v2 = var(b)
n = len(a)
cov = 0
for i in range(len(a)):
cov = cov + (a[i]-x1) * (b[i]-x2)
df = n-1
cov = cov / float(df)
sd = math.sqrt((v1+v2 - 2.0*cov)/float(n))
t = (x1-x2)/sd
prob = betai(0.5*df,0.5,df/(df+t*t))
if printit <> 0:
statname = 'Related samples T-test.'
outputpairedstats(printit,writemode,
name1,n,x1,v1,min(a),max(a),
name2,n,x2,v2,min(b),max(b),
statname,t,prob)
return t, prob
def lchisquare(f_obs,f_exp=None):
"""
Calculates a one-way chi square for list of observed frequencies and returns
the result. If no expected frequencies are given, the total N is assumed to
be equally distributed across all groups.
Usage: lchisquare(f_obs, f_exp=None) f_obs = list of observed cell freq.
Returns: chisquare-statistic, associated p-value
"""
k = len(f_obs) # number of groups
if f_exp == None:
f_exp = [sum(f_obs)/float(k)] * len(f_obs) # create k bins with = freq.
chisq = 0
for i in range(len(f_obs)):
chisq = chisq + (f_obs[i]-f_exp[i])**2 / float(f_exp[i])
return chisq, chisqprob(chisq, k-1)
def lks_2samp (data1,data2):
"""
Computes the Kolmogorov-Smirnof statistic on 2 samples. From
Numerical Recipies in C, page 493.
Usage: lks_2samp(data1,data2) data1&2 are lists of values for 2 conditions
Returns: KS D-value, associated p-value
"""
j1 = 0
j2 = 0
fn1 = 0.0
fn2 = 0.0
n1 = len(data1)
n2 = len(data2)
en1 = n1
en2 = n2
d = 0.0
data1.sort()
data2.sort()
while j1 < n1 and j2 < n2:
d1=data1[j1]
d2=data2[j2]
if d1 <= d2:
fn1 = (j1)/float(en1)
j1 = j1 + 1
if d2 <= d1:
fn2 = (j2)/float(en2)
j2 = j2 + 1
dt = (fn2-fn1)
if math.fabs(dt) > math.fabs(d):
d = dt
try:
en = math.sqrt(en1*en2/float(en1+en2))
prob = ksprob((en+0.12+0.11/en)*abs(d))
except:
prob = 1.0
return d, prob
def lmannwhitneyu(x,y):
"""
Calculates a Mann-Whitney U statistic on the provided scores and
returns the result. Use only when the n in each condition is < 20 and
you have 2 independent samples of ranks. NOTE: Mann-Whitney U is
significant if the u-obtained is LESS THAN or equal to the critical
value of U found in the tables. Equivalent to Kruskal-Wallis H with
just 2 groups.
Usage: lmannwhitneyu(data)
Returns: u-statistic, one-tailed p-value (i.e., p(z(U)))
"""
n1 = len(x)
n2 = len(y)
ranked = rankdata(x+y)
rankx = ranked[0:n1] # get the x-ranks
ranky = ranked[n1:] # the rest are y-ranks
u1 = n1*n2 + (n1*(n1+1))/2.0 - sum(rankx) # calc U for x
u2 = n1*n2 - u1 # remainder is U for y
bigu = max(u1,u2)
smallu = min(u1,u2)
T = math.sqrt(tiecorrect(ranked)) # correction factor for tied scores
if T == 0:
raise ValueError, 'All numbers are identical in lmannwhitneyu'
sd = math.sqrt(T*n1*n2*(n1+n2+1)/12.0)
z = abs((bigu-n1*n2/2.0) / sd) # normal approximation for prob calc
return smallu, 1.0 - zprob(z)
def ltiecorrect(rankvals):
"""
Corrects for ties in Mann Whitney U and Kruskal Wallis H tests. See
Siegel, S. (1956) Nonparametric Statistics for the Behavioral Sciences.
New York: McGraw-Hill. Code adapted from |Stat rankind.c code.
Usage: ltiecorrect(rankvals)
Returns: T correction factor for U or H
"""
sorted,posn = shellsort(rankvals)
n = len(sorted)
T = 0.0
i = 0
while (i<n-1):
if sorted[i] == sorted[i+1]:
nties = 1
while (i<n-1) and (sorted[i] == sorted[i+1]):
nties = nties +1
i = i +1
T = T + nties**3 - nties
i = i+1
T = T / float(n**3-n)
return 1.0 - T
def lranksums(x,y):
"""
Calculates the rank sums statistic on the provided scores and
returns the result. Use only when the n in each condition is > 20 and you
have 2 independent samples of ranks.
Usage: lranksums(x,y)
Returns: a z-statistic, two-tailed p-value
"""
n1 = len(x)
n2 = len(y)
alldata = x+y
ranked = rankdata(alldata)
x = ranked[:n1]
y = ranked[n1:]
s = sum(x)
expected = n1*(n1+n2+1) / 2.0
z = (s - expected) / math.sqrt(n1*n2*(n1+n2+1)/12.0)
prob = 2*(1.0 -zprob(abs(z)))
return z, prob
def lwilcoxont(x,y):
"""
Calculates the Wilcoxon T-test for related samples and returns the
result. A non-parametric T-test.
Usage: lwilcoxont(x,y)
Returns: a t-statistic, two-tail probability estimate
"""
if len(x) <> len(y):
raise ValueError, 'Unequal N in wilcoxont. Aborting.'
d=[]
for i in range(len(x)):
diff = x[i] - y[i]
if diff <> 0:
d.append(diff)
count = len(d)
absd = map(abs,d)
absranked = rankdata(absd)
r_plus = 0.0
r_minus = 0.0
for i in range(len(absd)):
if d[i] < 0:
r_minus = r_minus + absranked[i]
else:
r_plus = r_plus + absranked[i]
wt = min(r_plus, r_minus)
mn = count * (count+1) * 0.25
se = math.sqrt(count*(count+1)*(2.0*count+1.0)/24.0)
z = math.fabs(wt-mn) / se
prob = 2*(1.0 -zprob(abs(z)))
return wt, prob
def lkruskalwallish(*args):
"""
The Kruskal-Wallis H-test is a non-parametric ANOVA for 3 or more
groups, requiring at least 5 subjects in each group. This function
calculates the Kruskal-Wallis H-test for 3 or more independent samples
and returns the result.
Usage: lkruskalwallish(*args)
Returns: H-statistic (corrected for ties), associated p-value
"""
args = list(args)
n = [0]*len(args)
all = []
n = map(len,args)
for i in range(len(args)):
all = all + args[i]
ranked = rankdata(all)
T = tiecorrect(ranked)
for i in range(len(args)):
args[i] = ranked[0:n[i]]
del ranked[0:n[i]]
rsums = []
for i in range(len(args)):
rsums.append(sum(args[i])**2)
rsums[i] = rsums[i] / float(n[i])
ssbn = sum(rsums)
totaln = sum(n)
h = 12.0 / (totaln*(totaln+1)) * ssbn - 3*(totaln+1)
df = len(args) - 1
if T == 0:
raise ValueError, 'All numbers are identical in lkruskalwallish'
h = h / float(T)
return h, chisqprob(h,df)
def lfriedmanchisquare(*args):
"""
Friedman Chi-Square is a non-parametric, one-way within-subjects
ANOVA. This function calculates the Friedman Chi-square test for repeated
measures and returns the result, along with the associated probability
value. It assumes 3 or more repeated measures. Only 3 levels requires a
minimum of 10 subjects in the study. Four levels requires 5 subjects per
level(??).
Usage: lfriedmanchisquare(*args)
Returns: chi-square statistic, associated p-value
"""
k = len(args)
if k < 3:
raise ValueError, 'Less than 3 levels. Friedman test not appropriate.'
n = len(args[0])
data = apply(pstat.abut,tuple(args))
for i in range(len(data)):
data[i] = rankdata(data[i])
ssbn = 0
for i in range(k):
ssbn = ssbn + sum(args[i])**2
chisq = 12.0 / (k*n*(k+1)) * ssbn - 3*n*(k+1)
return chisq, chisqprob(chisq,k-1)
####################################
#### PROBABILITY CALCULATIONS ####
####################################
def lchisqprob(chisq,df):
"""
Returns the (1-tailed) probability value associated with the provided
chi-square value and df. Adapted from chisq.c in Gary Perlman's |Stat.
Usage: lchisqprob(chisq,df)
"""
BIG = 20.0
def ex(x):
BIG = 20.0
if x < -BIG:
return 0.0
else:
return math.exp(x)
if chisq <=0 or df < 1:
return 1.0
a = 0.5 * chisq
if df%2 == 0:
even = 1
else:
even = 0
if df > 1:
y = ex(-a)
if even:
s = y
else:
s = 2.0 * zprob(-math.sqrt(chisq))
if (df > 2):
chisq = 0.5 * (df - 1.0)
if even:
z = 1.0
else:
z = 0.5
if a > BIG:
if even:
e = 0.0
else:
e = math.log(math.sqrt(math.pi))
c = math.log(a)
while (z <= chisq):
e = math.log(z) + e
s = s + ex(c*z-a-e)
z = z + 1.0
return s
else:
if even:
e = 1.0
else:
e = 1.0 / math.sqrt(math.pi) / math.sqrt(a)
c = 0.0
while (z <= chisq):
e = e * (a/float(z))
c = c + e
z = z + 1.0
return (c*y+s)
else:
return s
def lerfcc(x):
"""
Returns the complementary error function erfc(x) with fractional
error everywhere less than 1.2e-7. Adapted from Numerical Recipies.
Usage: lerfcc(x)
"""
z = abs(x)
t = 1.0 / (1.0+0.5*z)
ans = t * math.exp(-z*z-1.26551223 + t*(1.00002368+t*(0.37409196+t*(0.09678418+t*(-0.18628806+t*(0.27886807+t*(-1.13520398+t*(1.48851587+t*(-0.82215223+t*0.17087277)))))))))
if x >= 0:
return ans
else:
return 2.0 - ans
def lzprob(z):
"""
Returns the area under the normal curve 'to the left of' the given z value.
Thus,
for z<0, zprob(z) = 1-tail probability
for z>0, 1.0-zprob(z) = 1-tail probability
for any z, 2.0*(1.0-zprob(abs(z))) = 2-tail probability
Adapted from z.c in Gary Perlman's |Stat.
Usage: lzprob(z)
"""
Z_MAX = 6.0 # maximum meaningful z-value
if z == 0.0:
x = 0.0
else:
y = 0.5 * math.fabs(z)
if y >= (Z_MAX*0.5):
x = 1.0
elif (y < 1.0):
w = y*y
x = ((((((((0.000124818987 * w
-0.001075204047) * w +0.005198775019) * w
-0.019198292004) * w +0.059054035642) * w
-0.151968751364) * w +0.319152932694) * w
-0.531923007300) * w +0.797884560593) * y * 2.0
else:
y = y - 2.0
x = (((((((((((((-0.000045255659 * y
+0.000152529290) * y -0.000019538132) * y
-0.000676904986) * y +0.001390604284) * y
-0.000794620820) * y -0.002034254874) * y
+0.006549791214) * y -0.010557625006) * y
+0.011630447319) * y -0.009279453341) * y
+0.005353579108) * y -0.002141268741) * y
+0.000535310849) * y +0.999936657524
if z > 0.0:
prob = ((x+1.0)*0.5)
else:
prob = ((1.0-x)*0.5)
return prob
def lksprob(alam):
"""
Computes a Kolmolgorov-Smirnov t-test significance level. Adapted from
Numerical Recipies.
Usage: lksprob(alam)
"""
fac = 2.0
sum = 0.0
termbf = 0.0
a2 = -2.0*alam*alam
for j in range(1,201):
term = fac*math.exp(a2*j*j)
sum = sum + term
if math.fabs(term) <= (0.001*termbf) or math.fabs(term) < (1.0e-8*sum):
return sum
fac = -fac
termbf = math.fabs(term)
return 1.0 # Get here only if fails to converge; was 0.0!!
def lfprob (dfnum, dfden, F):
"""
Returns the (1-tailed) significance level (p-value) of an F
statistic given the degrees of freedom for the numerator (dfR-dfF) and
the degrees of freedom for the denominator (dfF).
Usage: lfprob(dfnum, dfden, F) where usually dfnum=dfbn, dfden=dfwn
"""
p = betai(0.5*dfden, 0.5*dfnum, dfden/float(dfden+dfnum*F))
return p
def lbetacf(a,b,x):
"""
This function evaluates the continued fraction form of the incomplete
Beta function, betai. (Adapted from: Numerical Recipies in C.)
Usage: lbetacf(a,b,x)
"""
ITMAX = 200
EPS = 3.0e-7
bm = az = am = 1.0
qab = a+b
qap = a+1.0
qam = a-1.0
bz = 1.0-qab*x/qap
for i in range(ITMAX+1):
em = float(i+1)
tem = em + em
d = em*(b-em)*x/((qam+tem)*(a+tem))
ap = az + d*am
bp = bz+d*bm
d = -(a+em)*(qab+em)*x/((qap+tem)*(a+tem))
app = ap+d*az
bpp = bp+d*bz
aold = az
am = ap/bpp
bm = bp/bpp
az = app/bpp
bz = 1.0
if (abs(az-aold)<(EPS*abs(az))):
return az
print 'a or b too big, or ITMAX too small in Betacf.'
def lgammln(xx):
"""
Returns the gamma function of xx.
Gamma(z) = Integral(0,infinity) of t^(z-1)exp(-t) dt.
(Adapted from: Numerical Recipies in C.)
Usage: lgammln(xx)
"""
coeff = [76.18009173, -86.50532033, 24.01409822, -1.231739516,
0.120858003e-2, -0.536382e-5]
x = xx - 1.0
tmp = x + 5.5
tmp = tmp - (x+0.5)*math.log(tmp)
ser = 1.0
for j in range(len(coeff)):
x = x + 1
ser = ser + coeff[j]/x
return -tmp + math.log(2.50662827465*ser)
def lbetai(a,b,x):
"""
Returns the incomplete beta function:
I-sub-x(a,b) = 1/B(a,b)*(Integral(0,x) of t^(a-1)(1-t)^(b-1) dt)
where a,b>0 and B(a,b) = G(a)*G(b)/(G(a+b)) where G(a) is the gamma
function of a. The continued fraction formulation is implemented here,
using the betacf function. (Adapted from: Numerical Recipies in C.)
Usage: lbetai(a,b,x)
"""
if (x<0.0 or x>1.0):
raise ValueError, 'Bad x in lbetai'
if (x==0.0 or x==1.0):
bt = 0.0
else:
bt = math.exp(gammln(a+b)-gammln(a)-gammln(b)+a*math.log(x)+b*
math.log(1.0-x))
if (x<(a+1.0)/(a+b+2.0)):
return bt*betacf(a,b,x)/float(a)
else:
return 1.0-bt*betacf(b,a,1.0-x)/float(b)
####################################
####### ANOVA CALCULATIONS #######
####################################
def lF_oneway(*lists):
"""
Performs a 1-way ANOVA, returning an F-value and probability given
any number of groups. From Heiman, pp.394-7.
Usage: F_oneway(*lists) where *lists is any number of lists, one per
treatment group
Returns: F value, one-tailed p-value
"""
a = len(lists) # ANOVA on 'a' groups, each in it's own list
means = [0]*a
vars = [0]*a
ns = [0]*a
alldata = []
tmp = map(N.array,lists)
means = map(amean,tmp)
vars = map(avar,tmp)
ns = map(len,lists)
for i in range(len(lists)):
alldata = alldata + lists[i]
alldata = N.array(alldata)
bign = len(alldata)
sstot = ass(alldata)-(asquare_of_sums(alldata)/float(bign))
ssbn = 0
for list in lists:
ssbn = ssbn + asquare_of_sums(N.array(list))/float(len(list))
ssbn = ssbn - (asquare_of_sums(alldata)/float(bign))
sswn = sstot-ssbn
dfbn = a-1
dfwn = bign - a
msb = ssbn/float(dfbn)
msw = sswn/float(dfwn)
f = msb/msw
prob = fprob(dfbn,dfwn,f)
return f, prob
def lF_value (ER,EF,dfnum,dfden):
"""
Returns an F-statistic given the following:
ER = error associated with the null hypothesis (the Restricted model)
EF = error associated with the alternate hypothesis (the Full model)
dfR-dfF = degrees of freedom of the numerator
dfF = degrees of freedom associated with the denominator/Full model
Usage: lF_value(ER,EF,dfnum,dfden)
"""
return ((ER-EF)/float(dfnum) / (EF/float(dfden)))
####################################
######## SUPPORT FUNCTIONS #######
####################################
def writecc (listoflists,file,writetype='w',extra=2):
"""
Writes a list of lists to a file in columns, customized by the max
size of items within the columns (max size of items in col, +2 characters)
to specified file. File-overwrite is the default.
Usage: writecc (listoflists,file,writetype='w',extra=2)
Returns: None
"""
if type(listoflists[0]) not in [ListType,TupleType]:
listoflists = [listoflists]
outfile = open(file,writetype)
rowstokill = []
list2print = copy.deepcopy(listoflists)
for i in range(len(listoflists)):
if listoflists[i] == ['\n'] or listoflists[i]=='\n' or listoflists[i]=='dashes':
rowstokill = rowstokill + [i]
rowstokill.reverse()
for row in rowstokill:
del list2print[row]
maxsize = [0]*len(list2print[0])
for col in range(len(list2print[0])):
items = pstat.colex(list2print,col)
items = map(pstat.makestr,items)
maxsize[col] = max(map(len,items)) + extra
for row in listoflists:
if row == ['\n'] or row == '\n':
outfile.write('\n')
elif row == ['dashes'] or row == 'dashes':
dashes = [0]*len(maxsize)
for j in range(len(maxsize)):
dashes[j] = '-'*(maxsize[j]-2)
outfile.write(pstat.lineincustcols(dashes,maxsize))
else:
outfile.write(pstat.lineincustcols(row,maxsize))
outfile.write('\n')
outfile.close()
return None
def lincr(l,cap): # to increment a list up to a max-list of 'cap'
"""
Simulate a counting system from an n-dimensional list.
Usage: lincr(l,cap) l=list to increment, cap=max values for each list pos'n
Returns: next set of values for list l, OR -1 (if overflow)
"""
l[0] = l[0] + 1 # e.g., [0,0,0] --> [2,4,3] (=cap)
for i in range(len(l)):
if l[i] > cap[i] and i < len(l)-1: # if carryover AND not done
l[i] = 0
l[i+1] = l[i+1] + 1
elif l[i] > cap[i] and i == len(l)-1: # overflow past last column, must be finished
l = -1
return l
def lsum (inlist):
"""
Returns the sum of the items in the passed list.
Usage: lsum(inlist)
"""
s = 0
for item in inlist:
s = s + item
return s
def lcumsum (inlist):
"""
Returns a list consisting of the cumulative sum of the items in the
passed list.
Usage: lcumsum(inlist)
"""
newlist = copy.deepcopy(inlist)
for i in range(1,len(newlist)):
newlist[i] = newlist[i] + newlist[i-1]
return newlist
def lss(inlist):
"""
Squares each value in the passed list, adds up these squares and
returns the result.
Usage: lss(inlist)
"""
ss = 0
for item in inlist:
ss = ss + item*item
return ss
def lsummult (list1,list2):
"""
Multiplies elements in list1 and list2, element by element, and
returns the sum of all resulting multiplications. Must provide equal
length lists.
Usage: lsummult(list1,list2)
"""
if len(list1) <> len(list2):
raise ValueError, "Lists not equal length in summult."
s = 0
for item1,item2 in pstat.abut(list1,list2):
s = s + item1*item2
return s
def lsumdiffsquared(x,y):
"""
Takes pairwise differences of the values in lists x and y, squares
these differences, and returns the sum of these squares.
Usage: lsumdiffsquared(x,y)
Returns: sum[(x[i]-y[i])**2]
"""
sds = 0
for i in range(len(x)):
sds = sds + (x[i]-y[i])**2
return sds
def lsquare_of_sums(inlist):
"""
Adds the values in the passed list, squares the sum, and returns
the result.
Usage: lsquare_of_sums(inlist)
Returns: sum(inlist[i])**2
"""
s = sum(inlist)
return float(s)*s
def lshellsort(inlist):
"""
Shellsort algorithm. Sorts a 1D-list.
Usage: lshellsort(inlist)
Returns: sorted-inlist, sorting-index-vector (for original list)
"""
n = len(inlist)
svec = copy.deepcopy(inlist)
ivec = range(n)
gap = n/2 # integer division needed
while gap >0:
for i in range(gap,n):
for j in range(i-gap,-1,-gap):
while j>=0 and svec[j]>svec[j+gap]:
temp = svec[j]
svec[j] = svec[j+gap]
svec[j+gap] = temp
itemp = ivec[j]
ivec[j] = ivec[j+gap]
ivec[j+gap] = itemp
gap = gap / 2 # integer division needed
# svec is now sorted inlist, and ivec has the order svec[i] = vec[ivec[i]]
return svec, ivec
def lrankdata(inlist):
"""
Ranks the data in inlist, dealing with ties appropritely. Assumes
a 1D inlist. Adapted from Gary Perlman's |Stat ranksort.
Usage: lrankdata(inlist)
Returns: a list of length equal to inlist, containing rank scores
"""
n = len(inlist)
svec, ivec = shellsort(inlist)
sumranks = 0
dupcount = 0
newlist = [0]*n
for i in range(n):
sumranks = sumranks + i
dupcount = dupcount + 1
if i==n-1 or svec[i] <> svec[i+1]:
averank = sumranks / float(dupcount) + 1
for j in range(i-dupcount+1,i+1):
newlist[ivec[j]] = averank
sumranks = 0
dupcount = 0
return newlist
def outputpairedstats(fname,writemode,name1,n1,m1,se1,min1,max1,name2,n2,m2,se2,min2,max2,statname,stat,prob):
"""
Prints or write to a file stats for two groups, using the name, n,
mean, sterr, min and max for each group, as well as the statistic name,
its value, and the associated p-value.
Usage: outputpairedstats(fname,writemode,
name1,n1,mean1,stderr1,min1,max1,
name2,n2,mean2,stderr2,min2,max2,
statname,stat,prob)
Returns: None
"""
suffix = '' # for *s after the p-value
try:
x = prob.shape
prob = prob[0]
except:
pass
if prob < 0.001: suffix = ' ***'
elif prob < 0.01: suffix = ' **'
elif prob < 0.05: suffix = ' *'
title = [['Name','N','Mean','SD','Min','Max']]
lofl = title+[[name1,n1,round(m1,3),round(math.sqrt(se1),3),min1,max1],
[name2,n2,round(m2,3),round(math.sqrt(se2),3),min2,max2]]
if type(fname)<>StringType or len(fname)==0:
print
print statname
print
pstat.printcc(lofl)
print
try:
if stat.shape == ():
stat = stat[0]
if prob.shape == ():
prob = prob[0]
except:
pass
print 'Test statistic = ',round(stat,3),' p = ',round(prob,3),suffix
print
else:
file = open(fname,writemode)
file.write('\n'+statname+'\n\n')
file.close()
writecc(lofl,fname,'a')
file = open(fname,'a')
try:
if stat.shape == ():
stat = stat[0]
if prob.shape == ():
prob = prob[0]
except:
pass
file.write(pstat.list2string(['\nTest statistic = ',round(stat,4),' p = ',round(prob,4),suffix,'\n\n']))
file.close()
return None
def lfindwithin (data):
"""
Returns an integer representing a binary vector, where 1=within-
subject factor, 0=between. Input equals the entire data 2D list (i.e.,
column 0=random factor, column -1=measured values (those two are skipped).
Note: input data is in |Stat format ... a list of lists ("2D list") with
one row per measured value, first column=subject identifier, last column=
score, one in-between column per factor (these columns contain level
designations on each factor). See also stats.anova.__doc__.
Usage: lfindwithin(data) data in |Stat format
"""
numfact = len(data[0])-1
withinvec = 0
for col in range(1,numfact):
examplelevel = pstat.unique(pstat.colex(data,col))[0]
rows = pstat.linexand(data,col,examplelevel) # get 1 level of this factor
factsubjs = pstat.unique(pstat.colex(rows,0))
allsubjs = pstat.unique(pstat.colex(data,0))
if len(factsubjs) == len(allsubjs): # fewer Ss than scores on this factor?
withinvec = withinvec + (1 << col)
return withinvec
#########################################################
#########################################################
####### DISPATCH LISTS AND TUPLES TO ABOVE FCNS #########
#########################################################
#########################################################
## CENTRAL TENDENCY:
geometricmean = Dispatch ( (lgeometricmean, (ListType, TupleType)), )
harmonicmean = Dispatch ( (lharmonicmean, (ListType, TupleType)), )
mean = Dispatch ( (lmean, (ListType, TupleType)), )
median = Dispatch ( (lmedian, (ListType, TupleType)), )
medianscore = Dispatch ( (lmedianscore, (ListType, TupleType)), )
mode = Dispatch ( (lmode, (ListType, TupleType)), )
## MOMENTS:
moment = Dispatch ( (lmoment, (ListType, TupleType)), )
variation = Dispatch ( (lvariation, (ListType, TupleType)), )
skew = Dispatch ( (lskew, (ListType, TupleType)), )
kurtosis = Dispatch ( (lkurtosis, (ListType, TupleType)), )
describe = Dispatch ( (ldescribe, (ListType, TupleType)), )
## FREQUENCY STATISTICS:
itemfreq = Dispatch ( (litemfreq, (ListType, TupleType)), )
scoreatpercentile = Dispatch ( (lscoreatpercentile, (ListType, TupleType)), )
percentileofscore = Dispatch ( (lpercentileofscore, (ListType, TupleType)), )
histogram = Dispatch ( (lhistogram, (ListType, TupleType)), )
cumfreq = Dispatch ( (lcumfreq, (ListType, TupleType)), )
relfreq = Dispatch ( (lrelfreq, (ListType, TupleType)), )
## VARIABILITY:
obrientransform = Dispatch ( (lobrientransform, (ListType, TupleType)), )
samplevar = Dispatch ( (lsamplevar, (ListType, TupleType)), )
samplestdev = Dispatch ( (lsamplestdev, (ListType, TupleType)), )
var = Dispatch ( (lvar, (ListType, TupleType)), )
stdev = Dispatch ( (lstdev, (ListType, TupleType)), )
sterr = Dispatch ( (lsterr, (ListType, TupleType)), )
sem = Dispatch ( (lsem, (ListType, TupleType)), )
z = Dispatch ( (lz, (ListType, TupleType)), )
zs = Dispatch ( (lzs, (ListType, TupleType)), )
## TRIMMING FCNS:
trimboth = Dispatch ( (ltrimboth, (ListType, TupleType)), )
trim1 = Dispatch ( (ltrim1, (ListType, TupleType)), )
## CORRELATION FCNS:
paired = Dispatch ( (lpaired, (ListType, TupleType)), )
pearsonr = Dispatch ( (lpearsonr, (ListType, TupleType)), )
spearmanr = Dispatch ( (lspearmanr, (ListType, TupleType)), )
pointbiserialr = Dispatch ( (lpointbiserialr, (ListType, TupleType)), )
kendalltau = Dispatch ( (lkendalltau, (ListType, TupleType)), )
linregress = Dispatch ( (llinregress, (ListType, TupleType)), )
## INFERENTIAL STATS:
ttest_1samp = Dispatch ( (lttest_1samp, (ListType, TupleType)), )
ttest_ind = Dispatch ( (lttest_ind, (ListType, TupleType)), )
ttest_rel = Dispatch ( (lttest_rel, (ListType, TupleType)), )
chisquare = Dispatch ( (lchisquare, (ListType, TupleType)), )
ks_2samp = Dispatch ( (lks_2samp, (ListType, TupleType)), )
mannwhitneyu = Dispatch ( (lmannwhitneyu, (ListType, TupleType)), )
ranksums = Dispatch ( (lranksums, (ListType, TupleType)), )
tiecorrect = Dispatch ( (ltiecorrect, (ListType, TupleType)), )
wilcoxont = Dispatch ( (lwilcoxont, (ListType, TupleType)), )
kruskalwallish = Dispatch ( (lkruskalwallish, (ListType, TupleType)), )
friedmanchisquare = Dispatch ( (lfriedmanchisquare, (ListType, TupleType)), )
## PROBABILITY CALCS:
chisqprob = Dispatch ( (lchisqprob, (IntType, FloatType)), )
zprob = Dispatch ( (lzprob, (IntType, FloatType)), )
ksprob = Dispatch ( (lksprob, (IntType, FloatType)), )
fprob = Dispatch ( (lfprob, (IntType, FloatType)), )
betacf = Dispatch ( (lbetacf, (IntType, FloatType)), )
betai = Dispatch ( (lbetai, (IntType, FloatType)), )
erfcc = Dispatch ( (lerfcc, (IntType, FloatType)), )
gammln = Dispatch ( (lgammln, (IntType, FloatType)), )
## ANOVA FUNCTIONS:
F_oneway = Dispatch ( (lF_oneway, (ListType, TupleType)), )
F_value = Dispatch ( (lF_value, (ListType, TupleType)), )
## SUPPORT FUNCTIONS:
incr = Dispatch ( (lincr, (ListType, TupleType)), )
sum = Dispatch ( (lsum, (ListType, TupleType)), )
cumsum = Dispatch ( (lcumsum, (ListType, TupleType)), )
ss = Dispatch ( (lss, (ListType, TupleType)), )
summult = Dispatch ( (lsummult, (ListType, TupleType)), )
square_of_sums = Dispatch ( (lsquare_of_sums, (ListType, TupleType)), )
sumdiffsquared = Dispatch ( (lsumdiffsquared, (ListType, TupleType)), )
shellsort = Dispatch ( (lshellsort, (ListType, TupleType)), )
rankdata = Dispatch ( (lrankdata, (ListType, TupleType)), )
findwithin = Dispatch ( (lfindwithin, (ListType, TupleType)), )
#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS ===============
#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS ===============
#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS ===============
#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS ===============
#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS ===============
#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS ===============
#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS ===============
#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS ===============
#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS ===============
#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS ===============
#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS ===============
#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS ===============
#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS ===============
#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS ===============
#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS ===============
#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS ===============
#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS ===============
#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS ===============
#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS ===============
try: # DEFINE THESE *ONLY* IF NUMERIC IS AVAILABLE
import Numeric
N = Numeric
import LinearAlgebra
LA = LinearAlgebra
#####################################
######## ACENTRAL TENDENCY ########
#####################################
def ageometricmean (inarray,dimension=None,keepdims=0):
"""
Calculates the geometric mean of the values in the passed array.
That is: n-th root of (x1 * x2 * ... * xn). Defaults to ALL values in
the passed array. Use dimension=None to flatten array first. REMEMBER: if
dimension=0, it collapses over dimension 0 ('rows' in a 2D array) only, and
if dimension is a sequence, it collapses over all specified dimensions. If
keepdims is set to 1, the resulting array will have as many dimensions as
inarray, with only 1 'level' per dim that was collapsed over.
Usage: ageometricmean(inarray,dimension=None,keepdims=0)
Returns: geometric mean computed over dim(s) listed in dimension
"""
inarray = N.array(inarray,N.Float)
if dimension == None:
inarray = N.ravel(inarray)
size = len(inarray)
mult = N.power(inarray,1.0/size)
mult = N.multiply.reduce(mult)
elif type(dimension) in [IntType,FloatType]:
size = inarray.shape[dimension]
mult = N.power(inarray,1.0/size)
mult = N.multiply.reduce(mult,dimension)
if keepdims == 1:
shp = list(inarray.shape)
shp[dimension] = 1
sum = N.reshape(sum,shp)
else: # must be a SEQUENCE of dims to average over
dims = list(dimension)
dims.sort()
dims.reverse()
size = N.array(N.multiply.reduce(N.take(inarray.shape,dims)),N.Float)
mult = N.power(inarray,1.0/size)
for dim in dims:
mult = N.multiply.reduce(mult,dim)
if keepdims == 1:
shp = list(inarray.shape)
for dim in dims:
shp[dim] = 1
mult = N.reshape(mult,shp)
return mult
def aharmonicmean (inarray,dimension=None,keepdims=0):
"""
Calculates the harmonic mean of the values in the passed array.
That is: n / (1/x1 + 1/x2 + ... + 1/xn). Defaults to ALL values in
the passed array. Use dimension=None to flatten array first. REMEMBER: if
dimension=0, it collapses over dimension 0 ('rows' in a 2D array) only, and
if dimension is a sequence, it collapses over all specified dimensions. If
keepdims is set to 1, the resulting array will have as many dimensions as
inarray, with only 1 'level' per dim that was collapsed over.
Usage: aharmonicmean(inarray,dimension=None,keepdims=0)
Returns: harmonic mean computed over dim(s) in dimension
"""
inarray = inarray.astype(N.Float)
if dimension == None:
inarray = N.ravel(inarray)
size = len(inarray)
s = N.add.reduce(1.0 / inarray)
elif type(dimension) in [IntType,FloatType]:
size = float(inarray.shape[dimension])
s = N.add.reduce(1.0/inarray, dimension)
if keepdims == 1:
shp = list(inarray.shape)
shp[dimension] = 1
s = N.reshape(s,shp)
else: # must be a SEQUENCE of dims to average over
dims = list(dimension)
dims.sort()
nondims = []
for i in range(len(inarray.shape)):
if i not in dims:
nondims.append(i)
tinarray = N.transpose(inarray,nondims+dims) # put keep-dims first
idx = [0] *len(nondims)
if idx == []:
size = len(N.ravel(inarray))
s = asum(1.0 / inarray)
if keepdims == 1:
s = N.reshape([s],N.ones(len(inarray.shape)))
else:
idx[0] = -1
loopcap = N.array(tinarray.shape[0:len(nondims)]) -1
s = N.zeros(loopcap+1,N.Float)
while incr(idx,loopcap) <> -1:
s[idx] = asum(1.0/tinarray[idx])
size = N.multiply.reduce(N.take(inarray.shape,dims))
if keepdims == 1:
shp = list(inarray.shape)
for dim in dims:
shp[dim] = 1
s = N.reshape(s,shp)
return size / s
def amean (inarray,dimension=None,keepdims=0):
"""
Calculates the arithmatic mean of the values in the passed array.
That is: 1/n * (x1 + x2 + ... + xn). Defaults to ALL values in the
passed array. Use dimension=None to flatten array first. REMEMBER: if
dimension=0, it collapses over dimension 0 ('rows' in a 2D array) only, and
if dimension is a sequence, it collapses over all specified dimensions. If
keepdims is set to 1, the resulting array will have as many dimensions as
inarray, with only 1 'level' per dim that was collapsed over.
Usage: amean(inarray,dimension=None,keepdims=0)
Returns: arithematic mean calculated over dim(s) in dimension
"""
if inarray.typecode() in ['l','s','b']:
inarray = inarray.astype(N.Float)
if dimension == None:
inarray = N.ravel(inarray)
sum = N.add.reduce(inarray)
denom = float(len(inarray))
elif type(dimension) in [IntType,FloatType]:
sum = asum(inarray,dimension)
denom = float(inarray.shape[dimension])
if keepdims == 1:
shp = list(inarray.shape)
shp[dimension] = 1
sum = N.reshape(sum,shp)
else: # must be a TUPLE of dims to average over
dims = list(dimension)
dims.sort()
dims.reverse()
sum = inarray *1.0
for dim in dims:
sum = N.add.reduce(sum,dim)
denom = N.array(N.multiply.reduce(N.take(inarray.shape,dims)),N.Float)
if keepdims == 1:
shp = list(inarray.shape)
for dim in dims:
shp[dim] = 1
sum = N.reshape(sum,shp)
return sum/denom
def amedian (inarray,numbins=1000):
"""
Calculates the COMPUTED median value of an array of numbers, given the
number of bins to use for the histogram (more bins approaches finding the
precise median value of the array; default number of bins = 1000). From
G.W. Heiman's Basic Stats, or CRC Probability & Statistics.
NOTE: THIS ROUTINE ALWAYS uses the entire passed array (flattens it first).
Usage: amedian(inarray,numbins=1000)
Returns: median calculated over ALL values in inarray
"""
inarray = N.ravel(inarray)
(hist, smallest, binsize, extras) = ahistogram(inarray,numbins)
cumhist = N.cumsum(hist) # make cumulative histogram
otherbins = N.greater_equal(cumhist,len(inarray)/2.0)
otherbins = list(otherbins) # list of 0/1s, 1s start at median bin
cfbin = otherbins.index(1) # get 1st(!) index holding 50%ile score
LRL = smallest + binsize*cfbin # get lower read limit of that bin
cfbelow = N.add.reduce(hist[0:cfbin]) # cum. freq. below bin
freq = hist[cfbin] # frequency IN the 50%ile bin
median = LRL + ((len(inarray)/2.0-cfbelow)/float(freq))*binsize # MEDIAN
return median
def amedianscore (inarray,dimension=None):
"""
Returns the 'middle' score of the passed array. If there is an even
number of scores, the mean of the 2 middle scores is returned. Can function
with 1D arrays, or on the FIRST dimension of 2D arrays (i.e., dimension can
be None, to pre-flatten the array, or else dimension must equal 0).
Usage: amedianscore(inarray,dimension=None)
Returns: 'middle' score of the array, or the mean of the 2 middle scores
"""
if dimension == None:
inarray = N.ravel(inarray)
dimension = 0
inarray = N.sort(inarray,dimension)
if inarray.shape[dimension] % 2 == 0: # if even number of elements
indx = inarray.shape[dimension]/2 # integer division correct
median = N.asarray(inarray[indx]+inarray[indx-1]) / 2.0
else:
indx = inarray.shape[dimension] / 2 # integer division correct
median = N.take(inarray,[indx],dimension)
if median.shape == (1,):
median = median[0]
return median
def amode(a, dimension=None):
"""
Returns an array of the modal (most common) score in the passed array.
If there is more than one such score, ONLY THE FIRST is returned.
The bin-count for the modal values is also returned. Operates on whole
array (dimension=None), or on a given dimension.
Usage: amode(a, dimension=None)
Returns: array of bin-counts for mode(s), array of corresponding modal values
"""
if dimension == None:
a = N.ravel(a)
dimension = 0
scores = pstat.aunique(N.ravel(a)) # get ALL unique values
testshape = list(a.shape)
testshape[dimension] = 1
oldmostfreq = N.zeros(testshape)
oldcounts = N.zeros(testshape)
for score in scores:
template = N.equal(a,score)
counts = asum(template,dimension,1)
mostfrequent = N.where(N.greater(counts,oldcounts),score,oldmostfreq)
oldcounts = N.where(N.greater(counts,oldcounts),counts,oldcounts)
oldmostfreq = mostfrequent
return oldcounts, mostfrequent
def atmean(a,limits=None,inclusive=(1,1)):
"""
Returns the arithmetic mean of all values in an array, ignoring values
strictly outside the sequence passed to 'limits'. Note: either limit
in the sequence, or the value of limits itself, can be set to None. The
inclusive list/tuple determines whether the lower and upper limiting bounds
(respectively) are open/exclusive (0) or closed/inclusive (1).
Usage: atmean(a,limits=None,inclusive=(1,1))
"""
if a.typecode() in ['l','s','b']:
a = a.astype(N.Float)
if limits == None:
return mean(a)
assert type(limits) in [ListType,TupleType,N.ArrayType], "Wrong type for limits in atmean"
if inclusive[0]: lowerfcn = N.greater_equal
else: lowerfcn = N.greater
if inclusive[1]: upperfcn = N.less_equal
else: upperfcn = N.less
if limits[0] > N.maximum.reduce(N.ravel(a)) or limits[1] < N.minimum.reduce(N.ravel(a)):
raise ValueError, "No array values within given limits (atmean)."
elif limits[0]==None and limits[1]<>None:
mask = upperfcn(a,limits[1])
elif limits[0]<>None and limits[1]==None:
mask = lowerfcn(a,limits[0])
elif limits[0]<>None and limits[1]<>None:
mask = lowerfcn(a,limits[0])*upperfcn(a,limits[1])
s = float(N.add.reduce(N.ravel(a*mask)))
n = float(N.add.reduce(N.ravel(mask)))
return s/n
def atvar(a,limits=None,inclusive=(1,1)):
"""
Returns the sample variance of values in an array, (i.e., using N-1),
ignoring values strictly outside the sequence passed to 'limits'.
Note: either limit in the sequence, or the value of limits itself,
can be set to None. The inclusive list/tuple determines whether the lower
and upper limiting bounds (respectively) are open/exclusive (0) or
closed/inclusive (1).
Usage: atvar(a,limits=None,inclusive=(1,1))
"""
a = a.astype(N.Float)
if limits == None or limits == [None,None]:
term1 = N.add.reduce(N.ravel(a*a))
n = float(len(N.ravel(a))) - 1
term2 = N.add.reduce(N.ravel(a))**2 / n
print term1, term2, n
return (term1 - term2) / n
assert type(limits) in [ListType,TupleType,N.ArrayType], "Wrong type for limits in atvar"
if inclusive[0]: lowerfcn = N.greater_equal
else: lowerfcn = N.greater
if inclusive[1]: upperfcn = N.less_equal
else: upperfcn = N.less
if limits[0] > N.maximum.reduce(N.ravel(a)) or limits[1] < N.minimum.reduce(N.ravel(a)):
raise ValueError, "No array values within given limits (atvar)."
elif limits[0]==None and limits[1]<>None:
mask = upperfcn(a,limits[1])
elif limits[0]<>None and limits[1]==None:
mask = lowerfcn(a,limits[0])
elif limits[0]<>None and limits[1]<>None:
mask = lowerfcn(a,limits[0])*upperfcn(a,limits[1])
term1 = N.add.reduce(N.ravel(a*a*mask))
n = float(N.add.reduce(N.ravel(mask))) - 1
term2 = N.add.reduce(N.ravel(a*mask))**2 / n
print term1, term2, n
return (term1 - term2) / n
def atmin(a,lowerlimit=None,dimension=None,inclusive=1):
"""
Returns the minimum value of a, along dimension, including only values less
than (or equal to, if inclusive=1) lowerlimit. If the limit is set to None,
all values in the array are used.
Usage: atmin(a,lowerlimit=None,dimension=None,inclusive=1)
"""
if inclusive: lowerfcn = N.greater
else: lowerfcn = N.greater_equal
if dimension == None:
a = N.ravel(a)
dimension = 0
if lowerlimit == None:
lowerlimit = N.minimum.reduce(N.ravel(a))-11
biggest = N.maximum.reduce(N.ravel(a))
ta = N.where(lowerfcn(a,lowerlimit),a,biggest)
return N.minimum.reduce(ta,dimension)
def atmax(a,upperlimit,dimension=None,inclusive=1):
"""
Returns the maximum value of a, along dimension, including only values greater
than (or equal to, if inclusive=1) upperlimit. If the limit is set to None,
a limit larger than the max value in the array is used.
Usage: atmax(a,upperlimit,dimension=None,inclusive=1)
"""
if inclusive: upperfcn = N.less
else: upperfcn = N.less_equal
if dimension == None:
a = N.ravel(a)
dimension = 0
if upperlimit == None:
upperlimit = N.maximum.reduce(N.ravel(a))+1
smallest = N.minimum.reduce(N.ravel(a))
ta = N.where(upperfcn(a,upperlimit),a,smallest)
return N.maximum.reduce(ta,dimension)
def atstdev(a,limits=None,inclusive=(1,1)):
"""
Returns the standard deviation of all values in an array, ignoring values
strictly outside the sequence passed to 'limits'. Note: either limit
in the sequence, or the value of limits itself, can be set to None. The
inclusive list/tuple determines whether the lower and upper limiting bounds
(respectively) are open/exclusive (0) or closed/inclusive (1).
Usage: atstdev(a,limits=None,inclusive=(1,1))
"""
return N.sqrt(tvar(a,limits,inclusive))
def atsem(a,limits=None,inclusive=(1,1)):
"""
Returns the standard error of the mean for the values in an array,
(i.e., using N for the denominator), ignoring values strictly outside
the sequence passed to 'limits'. Note: either limit in the sequence,
or the value of limits itself, can be set to None. The inclusive list/tuple
determines whether the lower and upper limiting bounds (respectively) are
open/exclusive (0) or closed/inclusive (1).
Usage: atsem(a,limits=None,inclusive=(1,1))
"""
sd = tstdev(a,limits,inclusive)
if limits == None or limits == [None,None]:
n = float(len(N.ravel(a)))
assert type(limits) in [ListType,TupleType,N.ArrayType], "Wrong type for limits in atsem"
if inclusive[0]: lowerfcn = N.greater_equal
else: lowerfcn = N.greater
if inclusive[1]: upperfcn = N.less_equal
else: upperfcn = N.less
if limits[0] > N.maximum.reduce(N.ravel(a)) or limits[1] < N.minimum.reduce(N.ravel(a)):
raise ValueError, "No array values within given limits (atsem)."
elif limits[0]==None and limits[1]<>None:
mask = upperfcn(a,limits[1])
elif limits[0]<>None and limits[1]==None:
mask = lowerfcn(a,limits[0])
elif limits[0]<>None and limits[1]<>None:
mask = lowerfcn(a,limits[0])*upperfcn(a,limits[1])
term1 = N.add.reduce(N.ravel(a*a*mask))
n = float(N.add.reduce(N.ravel(mask)))
return sd/math.sqrt(n)
#####################################
############ AMOMENTS #############
#####################################
def amoment(a,moment=1,dimension=None):
"""
Calculates the nth moment about the mean for a sample (defaults to the
1st moment). Generally used to calculate coefficients of skewness and
kurtosis. Dimension can equal None (ravel array first), an integer
(the dimension over which to operate), or a sequence (operate over
multiple dimensions).
Usage: amoment(a,moment=1,dimension=None)
Returns: appropriate moment along given dimension
"""
if dimension == None:
a = N.ravel(a)
dimension = 0
if moment == 1:
return 0.0
else:
mn = amean(a,dimension,1) # 1=keepdims
s = N.power((a-mn),moment)
return amean(s,dimension)
def avariation(a,dimension=None):
"""
Returns the coefficient of variation, as defined in CRC Standard
Probability and Statistics, p.6. Dimension can equal None (ravel array
first), an integer (the dimension over which to operate), or a
sequence (operate over multiple dimensions).
Usage: avariation(a,dimension=None)
"""
return 100.0*asamplestdev(a,dimension)/amean(a,dimension)
def askew(a,dimension=None):
"""
Returns the skewness of a distribution (normal ==> 0.0; >0 means extra
weight in left tail). Use askewtest() to see if it's close enough.
Dimension can equal None (ravel array first), an integer (the
dimension over which to operate), or a sequence (operate over multiple
dimensions).
Usage: askew(a, dimension=None)
Returns: skew of vals in a along dimension, returning ZERO where all vals equal
"""
denom = N.power(amoment(a,2,dimension),1.5)
zero = N.equal(denom,0)
if type(denom) == N.ArrayType and asum(zero) <> 0:
print "Number of zeros in askew: ",asum(zero)
denom = denom + zero # prevent divide-by-zero
return N.where(zero, 0, amoment(a,3,dimension)/denom)
def akurtosis(a,dimension=None):
"""
Returns the kurtosis of a distribution (normal ==> 3.0; >3 means
heavier in the tails, and usually more peaked). Use akurtosistest()
to see if it's close enough. Dimension can equal None (ravel array
first), an integer (the dimension over which to operate), or a
sequence (operate over multiple dimensions).
Usage: akurtosis(a,dimension=None)
Returns: kurtosis of values in a along dimension, and ZERO where all vals equal
"""
denom = N.power(amoment(a,2,dimension),2)
zero = N.equal(denom,0)
if type(denom) == N.ArrayType and asum(zero) <> 0:
print "Number of zeros in akurtosis: ",asum(zero)
denom = denom + zero # prevent divide-by-zero
return N.where(zero,0,amoment(a,4,dimension)/denom)
def adescribe(inarray,dimension=None):
"""
Returns several descriptive statistics of the passed array. Dimension
can equal None (ravel array first), an integer (the dimension over
which to operate), or a sequence (operate over multiple dimensions).
Usage: adescribe(inarray,dimension=None)
Returns: n, (min,max), mean, standard deviation, skew, kurtosis
"""
if dimension == None:
inarray = N.ravel(inarray)
dimension = 0
n = inarray.shape[dimension]
mm = (N.minimum.reduce(inarray),N.maximum.reduce(inarray))
m = amean(inarray,dimension)
sd = astdev(inarray,dimension)
skew = askew(inarray,dimension)
kurt = akurtosis(inarray,dimension)
return n, mm, m, sd, skew, kurt
#####################################
######## NORMALITY TESTS ##########
#####################################
def askewtest(a,dimension=None):
"""
Tests whether the skew is significantly different from a normal
distribution. Dimension can equal None (ravel array first), an
integer (the dimension over which to operate), or a sequence (operate
over multiple dimensions).
Usage: askewtest(a,dimension=None)
Returns: z-score and 2-tail z-probability
"""
if dimension == None:
a = N.ravel(a)
dimension = 0
b2 = askew(a,dimension)
n = float(a.shape[dimension])
y = b2 * N.sqrt(((n+1)*(n+3)) / (6.0*(n-2)) )
beta2 = ( 3.0*(n*n+27*n-70)*(n+1)*(n+3) ) / ( (n-2.0)*(n+5)*(n+7)*(n+9) )
W2 = -1 + N.sqrt(2*(beta2-1))
delta = 1/N.sqrt(N.log(N.sqrt(W2)))
alpha = N.sqrt(2/(W2-1))
y = N.where(N.equal(y,0),1,y)
Z = delta*N.log(y/alpha + N.sqrt((y/alpha)**2+1))
return Z, (1.0-zprob(Z))*2
def akurtosistest(a,dimension=None):
"""
Tests whether a dataset has normal kurtosis (i.e.,
kurtosis=3(n-1)/(n+1)) Valid only for n>20. Dimension can equal None
(ravel array first), an integer (the dimension over which to operate),
or a sequence (operate over multiple dimensions).
Usage: akurtosistest(a,dimension=None)
Returns: z-score and 2-tail z-probability, returns 0 for bad pixels
"""
if dimension == None:
a = N.ravel(a)
dimension = 0
n = float(a.shape[dimension])
if n<20:
print "akurtosistest only valid for n>=20 ... continuing anyway, n=",n
b2 = akurtosis(a,dimension)
E = 3.0*(n-1) /(n+1)
varb2 = 24.0*n*(n-2)*(n-3) / ((n+1)*(n+1)*(n+3)*(n+5))
x = (b2-E)/N.sqrt(varb2)
sqrtbeta1 = 6.0*(n*n-5*n+2)/((n+7)*(n+9)) * N.sqrt((6.0*(n+3)*(n+5))/
(n*(n-2)*(n-3)))
A = 6.0 + 8.0/sqrtbeta1 *(2.0/sqrtbeta1 + N.sqrt(1+4.0/(sqrtbeta1**2)))
term1 = 1 -2/(9.0*A)
denom = 1 +x*N.sqrt(2/(A-4.0))
denom = N.where(N.less(denom,0), 99, denom)
term2 = N.where(N.equal(denom,0), term1, N.power((1-2.0/A)/denom,1/3.0))
Z = ( term1 - term2 ) / N.sqrt(2/(9.0*A))
Z = N.where(N.equal(denom,99), 0, Z)
return Z, (1.0-zprob(Z))*2
def anormaltest(a,dimension=None):
"""
Tests whether skew and/OR kurtosis of dataset differs from normal
curve. Can operate over multiple dimensions. Dimension can equal
None (ravel array first), an integer (the dimension over which to
operate), or a sequence (operate over multiple dimensions).
Usage: anormaltest(a,dimension=None)
Returns: z-score and 2-tail probability
"""
if dimension == None:
a = N.ravel(a)
dimension = 0
s,p = askewtest(a,dimension)
k,p = akurtosistest(a,dimension)
k2 = N.power(s,2) + N.power(k,2)
return k2, achisqprob(k2,2)
#####################################
###### AFREQUENCY FUNCTIONS #######
#####################################
def aitemfreq(a):
"""
Returns a 2D array of item frequencies. Column 1 contains item values,
column 2 contains their respective counts. Assumes a 1D array is passed.
Usage: aitemfreq(a)
Returns: a 2D frequency table (col [0:n-1]=scores, col n=frequencies)
"""
scores = pstat.aunique(a)
scores = N.sort(scores)
freq = N.zeros(len(scores))
for i in range(len(scores)):
freq[i] = N.add.reduce(N.equal(a,scores[i]))
return N.array(pstat.aabut(scores, freq))
def ascoreatpercentile (inarray, percent):
"""
Usage: ascoreatpercentile(inarray,percent) 0<percent<100
Returns: score at given percentile, relative to inarray distribution
"""
percent = percent / 100.0
targetcf = percent*len(inarray)
h, lrl, binsize, extras = histogram(inarray)
cumhist = cumsum(h*1)
for i in range(len(cumhist)):
if cumhist[i] >= targetcf:
break
score = binsize * ((targetcf - cumhist[i-1]) / float(h[i])) + (lrl+binsize*i)
return score
def apercentileofscore (inarray,score,histbins=10,defaultlimits=None):
"""
Note: result of this function depends on the values used to histogram
the data(!).
Usage: apercentileofscore(inarray,score,histbins=10,defaultlimits=None)
Returns: percentile-position of score (0-100) relative to inarray
"""
h, lrl, binsize, extras = histogram(inarray,histbins,defaultlimits)
cumhist = cumsum(h*1)
i = int((score - lrl)/float(binsize))
pct = (cumhist[i-1]+((score-(lrl+binsize*i))/float(binsize))*h[i])/float(len(inarray)) * 100
return pct
def ahistogram (inarray,numbins=10,defaultlimits=None,printextras=1):
"""
Returns (i) an array of histogram bin counts, (ii) the smallest value
of the histogram binning, and (iii) the bin width (the last 2 are not
necessarily integers). Default number of bins is 10. Defaultlimits
can be None (the routine picks bins spanning all the numbers in the
inarray) or a 2-sequence (lowerlimit, upperlimit). Returns all of the
following: array of bin values, lowerreallimit, binsize, extrapoints.
Usage: ahistogram(inarray,numbins=10,defaultlimits=None,printextras=1)
Returns: (array of bin counts, bin-minimum, min-width, #-points-outside-range)
"""
inarray = N.ravel(inarray) # flatten any >1D arrays
if (defaultlimits <> None):
lowerreallimit = defaultlimits[0]
upperreallimit = defaultlimits[1]
binsize = (upperreallimit-lowerreallimit) / float(numbins)
else:
Min = N.minimum.reduce(inarray)
Max = N.maximum.reduce(inarray)
estbinwidth = float(Max - Min)/float(numbins) + 1
binsize = (Max-Min+estbinwidth)/float(numbins)
lowerreallimit = Min - binsize/2.0 #lower real limit,1st bin
bins = N.zeros(numbins)
extrapoints = 0
for num in inarray:
try:
if (num-lowerreallimit) < 0:
extrapoints = extrapoints + 1
else:
bintoincrement = int((num-lowerreallimit) / float(binsize))
bins[bintoincrement] = bins[bintoincrement] + 1
except: # point outside lower/upper limits
extrapoints = extrapoints + 1
if (extrapoints > 0 and printextras == 1):
print '\nPoints outside given histogram range =',extrapoints
return (bins, lowerreallimit, binsize, extrapoints)
def acumfreq(a,numbins=10,defaultreallimits=None):
"""
Returns a cumulative frequency histogram, using the histogram function.
Defaultreallimits can be None (use all data), or a 2-sequence containing
lower and upper limits on values to include.
Usage: acumfreq(a,numbins=10,defaultreallimits=None)
Returns: array of cumfreq bin values, lowerreallimit, binsize, extrapoints
"""
h,l,b,e = histogram(a,numbins,defaultreallimits)
cumhist = cumsum(h*1)
return cumhist,l,b,e
def arelfreq(a,numbins=10,defaultreallimits=None):
"""
Returns a relative frequency histogram, using the histogram function.
Defaultreallimits can be None (use all data), or a 2-sequence containing
lower and upper limits on values to include.
Usage: arelfreq(a,numbins=10,defaultreallimits=None)
Returns: array of cumfreq bin values, lowerreallimit, binsize, extrapoints
"""
h,l,b,e = histogram(a,numbins,defaultreallimits)
h = N.array(h/float(a.shape[0]))
return h,l,b,e
#####################################
###### AVARIABILITY FUNCTIONS #####
#####################################
def aobrientransform(*args):
"""
Computes a transform on input data (any number of columns). Used to
test for homogeneity of variance prior to running one-way stats. Each
array in *args is one level of a factor. If an F_oneway() run on the
transformed data and found significant, variances are unequal. From
Maxwell and Delaney, p.112.
Usage: aobrientransform(*args) *args = 1D arrays, one per level of factor
Returns: transformed data for use in an ANOVA
"""
TINY = 1e-10
k = len(args)
n = N.zeros(k,N.Float)
v = N.zeros(k,N.Float)
m = N.zeros(k,N.Float)
nargs = []
for i in range(k):
nargs.append(args[i].astype(N.Float))
n[i] = float(len(nargs[i]))
v[i] = var(nargs[i])
m[i] = mean(nargs[i])
for j in range(k):
for i in range(n[j]):
t1 = (n[j]-1.5)*n[j]*(nargs[j][i]-m[j])**2
t2 = 0.5*v[j]*(n[j]-1.0)
t3 = (n[j]-1.0)*(n[j]-2.0)
nargs[j][i] = (t1-t2) / float(t3)
check = 1
for j in range(k):
if v[j] - mean(nargs[j]) > TINY:
check = 0
if check <> 1:
raise ValueError, 'Lack of convergence in obrientransform.'
else:
return N.array(nargs)
def asamplevar (inarray,dimension=None,keepdims=0):
"""
Returns the sample standard deviation of the values in the passed
array (i.e., using N). Dimension can equal None (ravel array first),
an integer (the dimension over which to operate), or a sequence
(operate over multiple dimensions). Set keepdims=1 to return an array
with the same number of dimensions as inarray.
Usage: asamplevar(inarray,dimension=None,keepdims=0)
"""
if dimension == None:
inarray = N.ravel(inarray)
dimension = 0
if dimension == 1:
mn = amean(inarray,dimension)[:,N.NewAxis]
else:
mn = amean(inarray,dimension,keepdims=1)
deviations = inarray - mn
if type(dimension) == ListType:
n = 1
for d in dimension:
n = n*inarray.shape[d]
else:
n = inarray.shape[dimension]
svar = ass(deviations,dimension,keepdims) / float(n)
return svar
def asamplestdev (inarray, dimension=None, keepdims=0):
"""
Returns the sample standard deviation of the values in the passed
array (i.e., using N). Dimension can equal None (ravel array first),
an integer (the dimension over which to operate), or a sequence
(operate over multiple dimensions). Set keepdims=1 to return an array
with the same number of dimensions as inarray.
Usage: asamplestdev(inarray,dimension=None,keepdims=0)
"""
return N.sqrt(asamplevar(inarray,dimension,keepdims))
def asignaltonoise(instack,dimension=0):
"""
Calculates signal-to-noise. Dimension can equal None (ravel array
first), an integer (the dimension over which to operate), or a
sequence (operate over multiple dimensions).
Usage: asignaltonoise(instack,dimension=0):
Returns: array containing the value of (mean/stdev) along dimension,
or 0 when stdev=0
"""
m = mean(instack,dimension)
sd = stdev(instack,dimension)
return N.where(N.equal(sd,0),0,m/sd)
def avar (inarray, dimension=None,keepdims=0):
"""
Returns the estimated population variance of the values in the passed
array (i.e., N-1). Dimension can equal None (ravel array first), an
integer (the dimension over which to operate), or a sequence (operate
over multiple dimensions). Set keepdims=1 to return an array with the
same number of dimensions as inarray.
Usage: avar(inarray,dimension=None,keepdims=0)
"""
if dimension == None:
inarray = N.ravel(inarray)
dimension = 0
mn = amean(inarray,dimension,1)
deviations = inarray - mn
if type(dimension) == ListType:
n = 1
for d in dimension:
n = n*inarray.shape[d]
else:
n = inarray.shape[dimension]
var = ass(deviations,dimension,keepdims)/float(n-1)
return var
def astdev (inarray, dimension=None, keepdims=0):
"""
Returns the estimated population standard deviation of the values in
the passed array (i.e., N-1). Dimension can equal None (ravel array
first), an integer (the dimension over which to operate), or a
sequence (operate over multiple dimensions). Set keepdims=1 to return
an array with the same number of dimensions as inarray.
Usage: astdev(inarray,dimension=None,keepdims=0)
"""
return N.sqrt(avar(inarray,dimension,keepdims))
def asterr (inarray, dimension=None, keepdims=0):
"""
Returns the estimated population standard error of the values in the
passed array (i.e., N-1). Dimension can equal None (ravel array
first), an integer (the dimension over which to operate), or a
sequence (operate over multiple dimensions). Set keepdims=1 to return
an array with the same number of dimensions as inarray.
Usage: asterr(inarray,dimension=None,keepdims=0)
"""
if dimension == None:
inarray = N.ravel(inarray)
dimension = 0
return astdev(inarray,dimension,keepdims) / float(N.sqrt(inarray.shape[dimension]))
def asem (inarray, dimension=None, keepdims=0):
"""
Returns the standard error of the mean (i.e., using N) of the values
in the passed array. Dimension can equal None (ravel array first), an
integer (the dimension over which to operate), or a sequence (operate
over multiple dimensions). Set keepdims=1 to return an array with the
same number of dimensions as inarray.
Usage: asem(inarray,dimension=None, keepdims=0)
"""
if dimension == None:
inarray = N.ravel(inarray)
dimension = 0
if type(dimension) == ListType:
n = 1
for d in dimension:
n = n*inarray.shape[d]
else:
n = inarray.shape[dimension]
s = asamplestdev(inarray,dimension,keepdims) / N.sqrt(n-1)
return s
def az (a, score):
"""
Returns the z-score of a given input score, given thearray from which
that score came. Not appropriate for population calculations, nor for
arrays > 1D.
Usage: az(a, score)
"""
z = (score-amean(a)) / asamplestdev(a)
return z
def azs (a):
"""
Returns a 1D array of z-scores, one for each score in the passed array,
computed relative to the passed array.
Usage: azs(a)
"""
zscores = []
for item in a:
zscores.append(z(a,item))
return N.array(zscores)
def azmap (scores, compare, dimension=0):
"""
Returns an array of z-scores the shape of scores (e.g., [x,y]), compared to
array passed to compare (e.g., [time,x,y]). Assumes collapsing over dim 0
of the compare array.
Usage: azs(scores, compare, dimension=0)
"""
mns = amean(compare,dimension)
sstd = asamplestdev(compare,0)
return (scores - mns) / sstd
#####################################
####### ATRIMMING FUNCTIONS #######
#####################################
def around(a,digits=1):
"""
Rounds all values in array a to 'digits' decimal places.
Usage: around(a,digits)
Returns: a, where each value is rounded to 'digits' decimals
"""
def ar(x,d=digits):
return round(x,d)
if type(a) <> N.ArrayType:
try:
a = N.array(a)
except:
a = N.array(a,'O')
shp = a.shape
if a.typecode() in ['f','F','d','D']:
b = N.ravel(a)
b = N.array(map(ar,b))
b.shape = shp
elif a.typecode() in ['o','O']:
b = N.ravel(a)*1
for i in range(len(b)):
if type(b[i]) == FloatType:
b[i] = round(b[i],digits)
b.shape = shp
else: # not a float, double or Object array
b = a*1
return b
def athreshold(a,threshmin=None,threshmax=None,newval=0):
"""
Like Numeric.clip() except that values <threshmid or >threshmax are replaced
by newval instead of by threshmin/threshmax (respectively).
Usage: athreshold(a,threshmin=None,threshmax=None,newval=0)
Returns: a, with values <threshmin or >threshmax replaced with newval
"""
mask = N.zeros(a.shape)
if threshmin <> None:
mask = mask + N.where(N.less(a,threshmin),1,0)
if threshmax <> None:
mask = mask + N.where(N.greater(a,threshmax),1,0)
mask = N.clip(mask,0,1)
return N.where(mask,newval,a)
def atrimboth (a,proportiontocut):
"""
Slices off the passed proportion of items from BOTH ends of the passed
array (i.e., with proportiontocut=0.1, slices 'leftmost' 10% AND
'rightmost' 10% of scores. You must pre-sort the array if you want
"proper" trimming. Slices off LESS if proportion results in a
non-integer slice index (i.e., conservatively slices off
proportiontocut).
Usage: atrimboth (a,proportiontocut)
Returns: trimmed version of array a
"""
lowercut = int(proportiontocut*len(a))
uppercut = len(a) - lowercut
return a[lowercut:uppercut]
def atrim1 (a,proportiontocut,tail='right'):
"""
Slices off the passed proportion of items from ONE end of the passed
array (i.e., if proportiontocut=0.1, slices off 'leftmost' or 'rightmost'
10% of scores). Slices off LESS if proportion results in a non-integer
slice index (i.e., conservatively slices off proportiontocut).
Usage: atrim1(a,proportiontocut,tail='right') or set tail='left'
Returns: trimmed version of array a
"""
if string.lower(tail) == 'right':
lowercut = 0
uppercut = len(a) - int(proportiontocut*len(a))
elif string.lower(tail) == 'left':
lowercut = int(proportiontocut*len(a))
uppercut = len(a)
return a[lowercut:uppercut]
#####################################
##### ACORRELATION FUNCTIONS ######
#####################################
def acovariance(X):
"""
Computes the covariance matrix of a matrix X. Requires a 2D matrix input.
Usage: acovariance(X)
Returns: covariance matrix of X
"""
if len(X.shape) <> 2:
raise TypeError, "acovariance requires 2D matrices"
n = X.shape[0]
mX = amean(X,0)
return N.dot(N.transpose(X),X) / float(n) - N.multiply.outer(mX,mX)
def acorrelation(X):
"""
Computes the correlation matrix of a matrix X. Requires a 2D matrix input.
Usage: acorrelation(X)
Returns: correlation matrix of X
"""
C = acovariance(X)
V = N.diagonal(C)
return C / N.sqrt(N.multiply.outer(V,V))
def apaired(x,y):
"""
Interactively determines the type of data in x and y, and then runs the
appropriated statistic for paired group data.
Usage: apaired(x,y) x,y = the two arrays of values to be compared
Returns: appropriate statistic name, value, and probability
"""
samples = ''
while samples not in ['i','r','I','R','c','C']:
print '\nIndependent or related samples, or correlation (i,r,c): ',
samples = raw_input()
if samples in ['i','I','r','R']:
print '\nComparing variances ...',
# USE O'BRIEN'S TEST FOR HOMOGENEITY OF VARIANCE, Maxwell & delaney, p.112
r = obrientransform(x,y)
f,p = F_oneway(pstat.colex(r,0),pstat.colex(r,1))
if p<0.05:
vartype='unequal, p='+str(round(p,4))
else:
vartype='equal'
print vartype
if samples in ['i','I']:
if vartype[0]=='e':
t,p = ttest_ind(x,y,None,0)
print '\nIndependent samples t-test: ', round(t,4),round(p,4)
else:
if len(x)>20 or len(y)>20:
z,p = ranksums(x,y)
print '\nRank Sums test (NONparametric, n>20): ', round(z,4),round(p,4)
else:
u,p = mannwhitneyu(x,y)
print '\nMann-Whitney U-test (NONparametric, ns<20): ', round(u,4),round(p,4)
else: # RELATED SAMPLES
if vartype[0]=='e':
t,p = ttest_rel(x,y,0)
print '\nRelated samples t-test: ', round(t,4),round(p,4)
else:
t,p = ranksums(x,y)
print '\nWilcoxon T-test (NONparametric): ', round(t,4),round(p,4)
else: # CORRELATION ANALYSIS
corrtype = ''
while corrtype not in ['c','C','r','R','d','D']:
print '\nIs the data Continuous, Ranked, or Dichotomous (c,r,d): ',
corrtype = raw_input()
if corrtype in ['c','C']:
m,b,r,p,see = linregress(x,y)
print '\nLinear regression for continuous variables ...'
lol = [['Slope','Intercept','r','Prob','SEestimate'],[round(m,4),round(b,4),round(r,4),round(p,4),round(see,4)]]
pstat.printcc(lol)
elif corrtype in ['r','R']:
r,p = spearmanr(x,y)
print '\nCorrelation for ranked variables ...'
print "Spearman's r: ",round(r,4),round(p,4)
else: # DICHOTOMOUS
r,p = pointbiserialr(x,y)
print '\nAssuming x contains a dichotomous variable ...'
print 'Point Biserial r: ',round(r,4),round(p,4)
print '\n\n'
return None
def apearsonr(x,y,verbose=1):
"""
Calculates a Pearson correlation coefficient and returns p. Taken
from Heiman's Basic Statistics for the Behav. Sci (2nd), p.195.
Usage: apearsonr(x,y,verbose=1) where x,y are equal length arrays
Returns: Pearson's r, two-tailed p-value
"""
TINY = 1.0e-20
n = len(x)
xmean = amean(x)
ymean = amean(y)
r_num = n*(N.add.reduce(x*y)) - N.add.reduce(x)*N.add.reduce(y)
r_den = math.sqrt((n*ass(x) - asquare_of_sums(x))*(n*ass(y)-asquare_of_sums(y)))
r = (r_num / r_den)
df = n-2
t = r*math.sqrt(df/((1.0-r+TINY)*(1.0+r+TINY)))
prob = abetai(0.5*df,0.5,df/(df+t*t),verbose)
return r,prob
def aspearmanr(x,y):
"""
Calculates a Spearman rank-order correlation coefficient. Taken
from Heiman's Basic Statistics for the Behav. Sci (1st), p.192.
Usage: aspearmanr(x,y) where x,y are equal-length arrays
Returns: Spearman's r, two-tailed p-value
"""
TINY = 1e-30
n = len(x)
rankx = rankdata(x)
ranky = rankdata(y)
dsq = N.add.reduce((rankx-ranky)**2)
rs = 1 - 6*dsq / float(n*(n**2-1))
t = rs * math.sqrt((n-2) / ((rs+1.0)*(1.0-rs)))
df = n-2
probrs = abetai(0.5*df,0.5,df/(df+t*t))
# probability values for rs are from part 2 of the spearman function in
# Numerical Recipies, p.510. They close to tables, but not exact.(?)
return rs, probrs
def apointbiserialr(x,y):
"""
Calculates a point-biserial correlation coefficient and the associated
probability value. Taken from Heiman's Basic Statistics for the Behav.
Sci (1st), p.194.
Usage: apointbiserialr(x,y) where x,y are equal length arrays
Returns: Point-biserial r, two-tailed p-value
"""
TINY = 1e-30
categories = pstat.aunique(x)
data = pstat.aabut(x,y)
if len(categories) <> 2:
raise ValueError, "Exactly 2 categories required (in x) for pointbiserialr()."
else: # there are 2 categories, continue
codemap = pstat.aabut(categories,N.arange(2))
recoded = pstat.arecode(data,codemap,0)
x = pstat.alinexand(data,0,categories[0])
y = pstat.alinexand(data,0,categories[1])
xmean = amean(pstat.acolex(x,1))
ymean = amean(pstat.acolex(y,1))
n = len(data)
adjust = math.sqrt((len(x)/float(n))*(len(y)/float(n)))
rpb = (ymean - xmean)/asamplestdev(pstat.acolex(data,1))*adjust
df = n-2
t = rpb*math.sqrt(df/((1.0-rpb+TINY)*(1.0+rpb+TINY)))
prob = abetai(0.5*df,0.5,df/(df+t*t))
return rpb, prob
def akendalltau(x,y):
"""
Calculates Kendall's tau ... correlation of ordinal data. Adapted
from function kendl1 in Numerical Recipies. Needs good test-cases.@@@
Usage: akendalltau(x,y)
Returns: Kendall's tau, two-tailed p-value
"""
n1 = 0
n2 = 0
iss = 0
for j in range(len(x)-1):
for k in range(j,len(y)):
a1 = x[j] - x[k]
a2 = y[j] - y[k]
aa = a1 * a2
if (aa): # neither array has a tie
n1 = n1 + 1
n2 = n2 + 1
if aa > 0:
iss = iss + 1
else:
iss = iss -1
else:
if (a1):
n1 = n1 + 1
else:
n2 = n2 + 1
tau = iss / math.sqrt(n1*n2)
svar = (4.0*len(x)+10.0) / (9.0*len(x)*(len(x)-1))
z = tau / math.sqrt(svar)
prob = erfcc(abs(z)/1.4142136)
return tau, prob
def alinregress(*args):
"""
Calculates a regression line on two arrays, x and y, corresponding to x,y
pairs. If a single 2D array is passed, alinregress finds dim with 2 levels
and splits data into x,y pairs along that dim.
Usage: alinregress(*args) args=2 equal-length arrays, or one 2D array
Returns: slope, intercept, r, two-tailed prob, sterr-of-the-estimate
"""
TINY = 1.0e-20
if len(args) == 1: # more than 1D array?
args = args[0]
if len(args) == 2:
x = args[0]
y = args[1]
else:
x = args[:,0]
y = args[:,1]
else:
x = args[0]
y = args[1]
n = len(x)
xmean = amean(x)
ymean = amean(y)
r_num = n*(N.add.reduce(x*y)) - N.add.reduce(x)*N.add.reduce(y)
r_den = math.sqrt((n*ass(x) - asquare_of_sums(x))*(n*ass(y)-asquare_of_sums(y)))
r = r_num / r_den
z = 0.5*math.log((1.0+r+TINY)/(1.0-r+TINY))
df = n-2
t = r*math.sqrt(df/((1.0-r+TINY)*(1.0+r+TINY)))
prob = abetai(0.5*df,0.5,df/(df+t*t))
slope = r_num / (float(n)*ass(x) - asquare_of_sums(x))
intercept = ymean - slope*xmean
sterrest = math.sqrt(1-r*r)*asamplestdev(y)
return slope, intercept, r, prob, sterrest
#####################################
##### AINFERENTIAL STATISTICS #####
#####################################
def attest_1samp(a,popmean,printit=0,name='Sample',writemode='a'):
"""
Calculates the t-obtained for the independent samples T-test on ONE group
of scores a, given a population mean. If printit=1, results are printed
to the screen. If printit='filename', the results are output to 'filename'
using the given writemode (default=append). Returns t-value, and prob.
Usage: attest_1samp(a,popmean,Name='Sample',printit=0,writemode='a')
Returns: t-value, two-tailed prob
"""
if type(a) != N.ArrayType:
a = N.array(a)
x = amean(a)
v = avar(a)
n = len(a)
df = n-1
svar = ((n-1)*v) / float(df)
t = (x-popmean)/math.sqrt(svar*(1.0/n))
prob = abetai(0.5*df,0.5,df/(df+t*t))
if printit <> 0:
statname = 'Single-sample T-test.'
outputpairedstats(printit,writemode,
'Population','--',popmean,0,0,0,
name,n,x,v,N.minimum.reduce(N.ravel(a)),
N.maximum.reduce(N.ravel(a)),
statname,t,prob)
return t,prob
def attest_ind (a, b, dimension=None, printit=0, name1='Samp1', name2='Samp2',writemode='a'):
"""
Calculates the t-obtained T-test on TWO INDEPENDENT samples of scores
a, and b. From Numerical Recipies, p.483. If printit=1, results are
printed to the screen. If printit='filename', the results are output
to 'filename' using the given writemode (default=append). Dimension
can equal None (ravel array first), or an integer (the dimension over
which to operate on a and b).
Usage: attest_ind (a,b,dimension=None,printit=0,
Name1='Samp1',Name2='Samp2',writemode='a')
Returns: t-value, two-tailed p-value
"""
if dimension == None:
a = N.ravel(a)
b = N.ravel(b)
dimension = 0
x1 = amean(a,dimension)
x2 = amean(b,dimension)
v1 = avar(a,dimension)
v2 = avar(b,dimension)
n1 = a.shape[dimension]
n2 = b.shape[dimension]
df = n1+n2-2
svar = ((n1-1)*v1+(n2-1)*v2) / float(df)
zerodivproblem = N.equal(svar,0)
svar = N.where(zerodivproblem,1,svar) # avoid zero-division in 1st place
t = (x1-x2)/N.sqrt(svar*(1.0/n1 + 1.0/n2)) # N-D COMPUTATION HERE!!!!!!
t = N.where(zerodivproblem,1.0,t) # replace NaN/wrong t-values with 1.0
probs = abetai(0.5*df,0.5,float(df)/(df+t*t))
if type(t) == N.ArrayType:
probs = N.reshape(probs,t.shape)
if len(probs) == 1:
probs = probs[0]
if printit <> 0:
if type(t) == N.ArrayType:
t = t[0]
if type(probs) == N.ArrayType:
probs = probs[0]
statname = 'Independent samples T-test.'
outputpairedstats(printit,writemode,
name1,n1,x1,v1,N.minimum.reduce(N.ravel(a)),
N.maximum.reduce(N.ravel(a)),
name2,n2,x2,v2,N.minimum.reduce(N.ravel(b)),
N.maximum.reduce(N.ravel(b)),
statname,t,probs)
return
return t, probs
def attest_rel (a,b,dimension=None,printit=0,name1='Samp1',name2='Samp2',writemode='a'):
"""
Calculates the t-obtained T-test on TWO RELATED samples of scores, a
and b. From Numerical Recipies, p.483. If printit=1, results are
printed to the screen. If printit='filename', the results are output
to 'filename' using the given writemode (default=append). Dimension
can equal None (ravel array first), or an integer (the dimension over
which to operate on a and b).
Usage: attest_rel(a,b,dimension=None,printit=0,
name1='Samp1',name2='Samp2',writemode='a')
Returns: t-value, two-tailed p-value
"""
if dimension == None:
a = N.ravel(a)
b = N.ravel(b)
dimension = 0
if len(a)<>len(b):
raise ValueError, 'Unequal length arrays.'
x1 = amean(a,dimension)
x2 = amean(b,dimension)
v1 = avar(a,dimension)
v2 = avar(b,dimension)
n = a.shape[dimension]
df = float(n-1)
d = (a-b).astype('d')
denom = N.sqrt((n*N.add.reduce(d*d,dimension) - N.add.reduce(d,dimension)**2) /df)
zerodivproblem = N.equal(denom,0)
denom = N.where(zerodivproblem,1,denom) # avoid zero-division in 1st place
t = N.add.reduce(d,dimension) / denom # N-D COMPUTATION HERE!!!!!!
t = N.where(zerodivproblem,1.0,t) # replace NaN/wrong t-values with 1.0
probs = abetai(0.5*df,0.5,float(df)/(df+t*t))
if type(t) == N.ArrayType:
probs = N.reshape(probs,t.shape)
if len(probs) == 1:
probs = probs[0]
if printit <> 0:
statname = 'Related samples T-test.'
outputpairedstats(printit,writemode,
name1,n,x1,v1,N.minimum.reduce(N.ravel(a)),
N.maximum.reduce(N.ravel(a)),
name2,n,x2,v2,N.minimum.reduce(N.ravel(b)),
N.maximum.reduce(N.ravel(b)),
statname,t,probs)
return
return t, probs
def achisquare(f_obs,f_exp=None):
"""
Calculates a one-way chi square for array of observed frequencies and returns
the result. If no expected frequencies are given, the total N is assumed to
be equally distributed across all groups.
Usage: achisquare(f_obs, f_exp=None) f_obs = array of observed cell freq.
Returns: chisquare-statistic, associated p-value
"""
k = len(f_obs)
if f_exp == None:
f_exp = N.array([sum(f_obs)/float(k)] * len(f_obs),N.Float)
f_exp = f_exp.astype(N.Float)
chisq = N.add.reduce((f_obs-f_exp)**2 / f_exp)
return chisq, chisqprob(chisq, k-1)
def aks_2samp (data1,data2):
"""
Computes the Kolmogorov-Smirnof statistic on 2 samples. Modified from
Numerical Recipies in C, page 493. Returns KS D-value, prob. Not ufunc-
like.
Usage: aks_2samp(data1,data2) where data1 and data2 are 1D arrays
Returns: KS D-value, p-value
"""
j1 = 0 # N.zeros(data1.shape[1:]) TRIED TO MAKE THIS UFUNC-LIKE
j2 = 0 # N.zeros(data2.shape[1:])
fn1 = 0.0 # N.zeros(data1.shape[1:],N.Float)
fn2 = 0.0 # N.zeros(data2.shape[1:],N.Float)
n1 = data1.shape[0]
n2 = data2.shape[0]
en1 = n1*1
en2 = n2*1
d = N.zeros(data1.shape[1:],N.Float)
data1 = N.sort(data1,0)
data2 = N.sort(data2,0)
while j1 < n1 and j2 < n2:
d1=data1[j1]
d2=data2[j2]
if d1 <= d2:
fn1 = (j1)/float(en1)
j1 = j1 + 1
if d2 <= d1:
fn2 = (j2)/float(en2)
j2 = j2 + 1
dt = (fn2-fn1)
if abs(dt) > abs(d):
d = dt
try:
en = math.sqrt(en1*en2/float(en1+en2))
prob = aksprob((en+0.12+0.11/en)*N.fabs(d))
except:
prob = 1.0
return d, prob
def amannwhitneyu(x,y):
"""
Calculates a Mann-Whitney U statistic on the provided scores and
returns the result. Use only when the n in each condition is < 20 and
you have 2 independent samples of ranks. REMEMBER: Mann-Whitney U is
significant if the u-obtained is LESS THAN or equal to the critical
value of U.
Usage: amannwhitneyu(x,y) where x,y are arrays of values for 2 conditions
Returns: u-statistic, one-tailed p-value (i.e., p(z(U)))
"""
n1 = len(x)
n2 = len(y)
ranked = rankdata(N.concatenate((x,y)))
rankx = ranked[0:n1] # get the x-ranks
ranky = ranked[n1:] # the rest are y-ranks
u1 = n1*n2 + (n1*(n1+1))/2.0 - sum(rankx) # calc U for x
u2 = n1*n2 - u1 # remainder is U for y
bigu = max(u1,u2)
smallu = min(u1,u2)
T = math.sqrt(tiecorrect(ranked)) # correction factor for tied scores
if T == 0:
raise ValueError, 'All numbers are identical in amannwhitneyu'
sd = math.sqrt(T*n1*n2*(n1+n2+1)/12.0)
z = abs((bigu-n1*n2/2.0) / sd) # normal approximation for prob calc
return smallu, 1.0 - zprob(z)
def atiecorrect(rankvals):
"""
Tie-corrector for ties in Mann Whitney U and Kruskal Wallis H tests.
See Siegel, S. (1956) Nonparametric Statistics for the Behavioral
Sciences. New York: McGraw-Hill. Code adapted from |Stat rankind.c
code.
Usage: atiecorrect(rankvals)
Returns: T correction factor for U or H
"""
sorted,posn = ashellsort(N.array(rankvals))
n = len(sorted)
T = 0.0
i = 0
while (i<n-1):
if sorted[i] == sorted[i+1]:
nties = 1
while (i<n-1) and (sorted[i] == sorted[i+1]):
nties = nties +1
i = i +1
T = T + nties**3 - nties
i = i+1
T = T / float(n**3-n)
return 1.0 - T
def aranksums(x,y):
"""
Calculates the rank sums statistic on the provided scores and returns
the result.
Usage: aranksums(x,y) where x,y are arrays of values for 2 conditions
Returns: z-statistic, two-tailed p-value
"""
n1 = len(x)
n2 = len(y)
alldata = N.concatenate((x,y))
ranked = arankdata(alldata)
x = ranked[:n1]
y = ranked[n1:]
s = sum(x)
expected = n1*(n1+n2+1) / 2.0
z = (s - expected) / math.sqrt(n1*n2*(n1+n2+1)/12.0)
prob = 2*(1.0 -zprob(abs(z)))
return z, prob
def awilcoxont(x,y):
"""
Calculates the Wilcoxon T-test for related samples and returns the
result. A non-parametric T-test.
Usage: awilcoxont(x,y) where x,y are equal-length arrays for 2 conditions
Returns: t-statistic, two-tailed p-value
"""
if len(x) <> len(y):
raise ValueError, 'Unequal N in awilcoxont. Aborting.'
d = x-y
d = N.compress(N.not_equal(d,0),d) # Keep all non-zero differences
count = len(d)
absd = abs(d)
absranked = arankdata(absd)
r_plus = 0.0
r_minus = 0.0
for i in range(len(absd)):
if d[i] < 0:
r_minus = r_minus + absranked[i]
else:
r_plus = r_plus + absranked[i]
wt = min(r_plus, r_minus)
mn = count * (count+1) * 0.25
se = math.sqrt(count*(count+1)*(2.0*count+1.0)/24.0)
z = math.fabs(wt-mn) / se
z = math.fabs(wt-mn) / se
prob = 2*(1.0 -zprob(abs(z)))
return wt, prob
def akruskalwallish(*args):
"""
The Kruskal-Wallis H-test is a non-parametric ANOVA for 3 or more
groups, requiring at least 5 subjects in each group. This function
calculates the Kruskal-Wallis H and associated p-value for 3 or more
independent samples.
Usage: akruskalwallish(*args) args are separate arrays for 3+ conditions
Returns: H-statistic (corrected for ties), associated p-value
"""
assert len(args) == 3, "Need at least 3 groups in stats.akruskalwallish()"
args = list(args)
n = [0]*len(args)
n = map(len,args)
all = []
for i in range(len(args)):
all = all + args[i].tolist()
ranked = rankdata(all)
T = tiecorrect(ranked)
for i in range(len(args)):
args[i] = ranked[0:n[i]]
del ranked[0:n[i]]
rsums = []
for i in range(len(args)):
rsums.append(sum(args[i])**2)
rsums[i] = rsums[i] / float(n[i])
ssbn = sum(rsums)
totaln = sum(n)
h = 12.0 / (totaln*(totaln+1)) * ssbn - 3*(totaln+1)
df = len(args) - 1
if T == 0:
raise ValueError, 'All numbers are identical in akruskalwallish'
h = h / float(T)
return h, chisqprob(h,df)
def afriedmanchisquare(*args):
"""
Friedman Chi-Square is a non-parametric, one-way within-subjects
ANOVA. This function calculates the Friedman Chi-square test for
repeated measures and returns the result, along with the associated
probability value. It assumes 3 or more repeated measures. Only 3
levels requires a minimum of 10 subjects in the study. Four levels
requires 5 subjects per level(??).
Usage: afriedmanchisquare(*args) args are separate arrays for 2+ conditions
Returns: chi-square statistic, associated p-value
"""
k = len(args)
if k < 3:
raise ValueError, '\nLess than 3 levels. Friedman test not appropriate.\n'
n = len(args[0])
data = apply(pstat.aabut,args)
data = data.astype(N.Float)
for i in range(len(data)):
data[i] = arankdata(data[i])
ssbn = asum(asum(args,1)**2)
chisq = 12.0 / (k*n*(k+1)) * ssbn - 3*n*(k+1)
return chisq, chisqprob(chisq,k-1)
#####################################
#### APROBABILITY CALCULATIONS ####
#####################################
def achisqprob(chisq,df):
"""
Returns the (1-tail) probability value associated with the provided chi-square
value and df. Heavily modified from chisq.c in Gary Perlman's |Stat. Can
handle multiple dimensions.
Usage: achisqprob(chisq,df) chisq=chisquare stat., df=degrees of freedom
"""
BIG = 200.0
def ex(x):
BIG = 200.0
exponents = N.where(N.less(x,-BIG),-BIG,x)
return N.exp(exponents)
if type(chisq) == N.ArrayType:
arrayflag = 1
else:
arrayflag = 0
chisq = N.array([chisq])
if df < 1:
return N.ones(chisq.shape,N.float)
probs = N.zeros(chisq.shape,N.Float)
probs = N.where(N.less_equal(chisq,0),1.0,probs) # set prob=1 for chisq<0
a = 0.5 * chisq
if df > 1:
y = ex(-a)
if df%2 == 0:
even = 1
s = y*1
s2 = s*1
else:
even = 0
s = 2.0 * azprob(-N.sqrt(chisq))
s2 = s*1
if (df > 2):
chisq = 0.5 * (df - 1.0)
if even:
z = N.ones(probs.shape,N.Float)
else:
z = 0.5 *N.ones(probs.shape,N.Float)
if even:
e = N.zeros(probs.shape,N.Float)
else:
e = N.log(N.sqrt(N.pi)) *N.ones(probs.shape,N.Float)
c = N.log(a)
mask = N.zeros(probs.shape)
a_big = N.greater(a,BIG)
a_big_frozen = -1 *N.ones(probs.shape,N.Float)
totalelements = N.multiply.reduce(N.array(probs.shape))
while asum(mask)<>totalelements:
e = N.log(z) + e
s = s + ex(c*z-a-e)
z = z + 1.0
# print z, e, s
newmask = N.greater(z,chisq)
a_big_frozen = N.where(newmask*N.equal(mask,0)*a_big, s, a_big_frozen)
mask = N.clip(newmask+mask,0,1)
if even:
z = N.ones(probs.shape,N.Float)
e = N.ones(probs.shape,N.Float)
else:
z = 0.5 *N.ones(probs.shape,N.Float)
e = 1.0 / N.sqrt(N.pi) / N.sqrt(a) * N.ones(probs.shape,N.Float)
c = 0.0
mask = N.zeros(probs.shape)
a_notbig_frozen = -1 *N.ones(probs.shape,N.Float)
while asum(mask)<>totalelements:
e = e * (a/z.astype(N.Float))
c = c + e
z = z + 1.0
# print '#2', z, e, c, s, c*y+s2
newmask = N.greater(z,chisq)
a_notbig_frozen = N.where(newmask*N.equal(mask,0)*(1-a_big),
c*y+s2, a_notbig_frozen)
mask = N.clip(newmask+mask,0,1)
probs = N.where(N.equal(probs,1),1,
N.where(N.greater(a,BIG),a_big_frozen,a_notbig_frozen))
return probs
else:
return s
def aerfcc(x):
"""
Returns the complementary error function erfc(x) with fractional error
everywhere less than 1.2e-7. Adapted from Numerical Recipies. Can
handle multiple dimensions.
Usage: aerfcc(x)
"""
z = abs(x)
t = 1.0 / (1.0+0.5*z)
ans = t * N.exp(-z*z-1.26551223 + t*(1.00002368+t*(0.37409196+t*(0.09678418+t*(-0.18628806+t*(0.27886807+t*(-1.13520398+t*(1.48851587+t*(-0.82215223+t*0.17087277)))))))))
return N.where(N.greater_equal(x,0), ans, 2.0-ans)
def azprob(z):
"""
Returns the area under the normal curve 'to the left of' the given z value.
Thus,
for z<0, zprob(z) = 1-tail probability
for z>0, 1.0-zprob(z) = 1-tail probability
for any z, 2.0*(1.0-zprob(abs(z))) = 2-tail probability
Adapted from z.c in Gary Perlman's |Stat. Can handle multiple dimensions.
Usage: azprob(z) where z is a z-value
"""
def yfunc(y):
x = (((((((((((((-0.000045255659 * y
+0.000152529290) * y -0.000019538132) * y
-0.000676904986) * y +0.001390604284) * y
-0.000794620820) * y -0.002034254874) * y
+0.006549791214) * y -0.010557625006) * y
+0.011630447319) * y -0.009279453341) * y
+0.005353579108) * y -0.002141268741) * y
+0.000535310849) * y +0.999936657524
return x
def wfunc(w):
x = ((((((((0.000124818987 * w
-0.001075204047) * w +0.005198775019) * w
-0.019198292004) * w +0.059054035642) * w
-0.151968751364) * w +0.319152932694) * w
-0.531923007300) * w +0.797884560593) * N.sqrt(w) * 2.0
return x
Z_MAX = 6.0 # maximum meaningful z-value
x = N.zeros(z.shape,N.Float) # initialize
y = 0.5 * N.fabs(z)
x = N.where(N.less(y,1.0),wfunc(y*y),yfunc(y-2.0)) # get x's
x = N.where(N.greater(y,Z_MAX*0.5),1.0,x) # kill those with big Z
prob = N.where(N.greater(z,0),(x+1)*0.5,(1-x)*0.5)
return prob
def aksprob(alam):
"""
Returns the probability value for a K-S statistic computed via ks_2samp.
Adapted from Numerical Recipies. Can handle multiple dimensions.
Usage: aksprob(alam)
"""
if type(alam) == N.ArrayType:
frozen = -1 *N.ones(alam.shape,N.Float64)
alam = alam.astype(N.Float64)
arrayflag = 1
else:
frozen = N.array(-1.)
alam = N.array(alam,N.Float64)
mask = N.zeros(alam.shape)
fac = 2.0 *N.ones(alam.shape,N.Float)
sum = N.zeros(alam.shape,N.Float)
termbf = N.zeros(alam.shape,N.Float)
a2 = N.array(-2.0*alam*alam,N.Float64)
totalelements = N.multiply.reduce(N.array(mask.shape))
for j in range(1,201):
if asum(mask) == totalelements:
break
exponents = (a2*j*j)
overflowmask = N.less(exponents,-746)
frozen = N.where(overflowmask,0,frozen)
mask = mask+overflowmask
term = fac*N.exp(exponents)
sum = sum + term
newmask = N.where(N.less_equal(abs(term),(0.001*termbf)) +
N.less(abs(term),1.0e-8*sum), 1, 0)
frozen = N.where(newmask*N.equal(mask,0), sum, frozen)
mask = N.clip(mask+newmask,0,1)
fac = -fac
termbf = abs(term)
if arrayflag:
return N.where(N.equal(frozen,-1), 1.0, frozen) # 1.0 if doesn't converge
else:
return N.where(N.equal(frozen,-1), 1.0, frozen)[0] # 1.0 if doesn't converge
def afprob (dfnum, dfden, F):
"""
Returns the 1-tailed significance level (p-value) of an F statistic
given the degrees of freedom for the numerator (dfR-dfF) and the degrees
of freedom for the denominator (dfF). Can handle multiple dims for F.
Usage: afprob(dfnum, dfden, F) where usually dfnum=dfbn, dfden=dfwn
"""
if type(F) == N.ArrayType:
return abetai(0.5*dfden, 0.5*dfnum, dfden/(1.0*dfden+dfnum*F))
else:
return abetai(0.5*dfden, 0.5*dfnum, dfden/float(dfden+dfnum*F))
def abetacf(a,b,x,verbose=1):
"""
Evaluates the continued fraction form of the incomplete Beta function,
betai. (Adapted from: Numerical Recipies in C.) Can handle multiple
dimensions for x.
Usage: abetacf(a,b,x,verbose=1)
"""
ITMAX = 200
EPS = 3.0e-7
arrayflag = 1
if type(x) == N.ArrayType:
frozen = N.ones(x.shape,N.Float) *-1 #start out w/ -1s, should replace all
else:
arrayflag = 0
frozen = N.array([-1])
x = N.array([x])
mask = N.zeros(x.shape)
bm = az = am = 1.0
qab = a+b
qap = a+1.0
qam = a-1.0
bz = 1.0-qab*x/qap
for i in range(ITMAX+1):
if N.sum(N.ravel(N.equal(frozen,-1)))==0:
break
em = float(i+1)
tem = em + em
d = em*(b-em)*x/((qam+tem)*(a+tem))
ap = az + d*am
bp = bz+d*bm
d = -(a+em)*(qab+em)*x/((qap+tem)*(a+tem))
app = ap+d*az
bpp = bp+d*bz
aold = az*1
am = ap/bpp
bm = bp/bpp
az = app/bpp
bz = 1.0
newmask = N.less(abs(az-aold),EPS*abs(az))
frozen = N.where(newmask*N.equal(mask,0), az, frozen)
mask = N.clip(mask+newmask,0,1)
noconverge = asum(N.equal(frozen,-1))
if noconverge <> 0 and verbose:
print 'a or b too big, or ITMAX too small in Betacf for ',noconverge,' elements'
if arrayflag:
return frozen
else:
return frozen[0]
def agammln(xx):
"""
Returns the gamma function of xx.
Gamma(z) = Integral(0,infinity) of t^(z-1)exp(-t) dt.
Adapted from: Numerical Recipies in C. Can handle multiple dims ... but
probably doesn't normally have to.
Usage: agammln(xx)
"""
coeff = [76.18009173, -86.50532033, 24.01409822, -1.231739516,
0.120858003e-2, -0.536382e-5]
x = xx - 1.0
tmp = x + 5.5
tmp = tmp - (x+0.5)*N.log(tmp)
ser = 1.0
for j in range(len(coeff)):
x = x + 1
ser = ser + coeff[j]/x
return -tmp + N.log(2.50662827465*ser)
def abetai(a,b,x,verbose=1):
"""
Returns the incomplete beta function:
I-sub-x(a,b) = 1/B(a,b)*(Integral(0,x) of t^(a-1)(1-t)^(b-1) dt)
where a,b>0 and B(a,b) = G(a)*G(b)/(G(a+b)) where G(a) is the gamma
function of a. The continued fraction formulation is implemented
here, using the betacf function. (Adapted from: Numerical Recipies in
C.) Can handle multiple dimensions.
Usage: abetai(a,b,x,verbose=1)
"""
TINY = 1e-15
if type(a) == N.ArrayType:
if asum(N.less(x,0)+N.greater(x,1)) <> 0:
raise ValueError, 'Bad x in abetai'
x = N.where(N.equal(x,0),TINY,x)
x = N.where(N.equal(x,1.0),1-TINY,x)
bt = N.where(N.equal(x,0)+N.equal(x,1), 0, -1)
exponents = ( gammln(a+b)-gammln(a)-gammln(b)+a*N.log(x)+b*
N.log(1.0-x) )
# 746 (below) is the MAX POSSIBLE BEFORE OVERFLOW
exponents = N.where(N.less(exponents,-740),-740,exponents)
bt = N.exp(exponents)
if type(x) == N.ArrayType:
ans = N.where(N.less(x,(a+1)/(a+b+2.0)),
bt*abetacf(a,b,x,verbose)/float(a),
1.0-bt*abetacf(b,a,1.0-x,verbose)/float(b))
else:
if x<(a+1)/(a+b+2.0):
ans = bt*abetacf(a,b,x,verbose)/float(a)
else:
ans = 1.0-bt*abetacf(b,a,1.0-x,verbose)/float(b)
return ans
#####################################
####### AANOVA CALCULATIONS #######
#####################################
import LinearAlgebra, operator
LA = LinearAlgebra
def aglm(data,para):
"""
Calculates a linear model fit ... anova/ancova/lin-regress/t-test/etc. Taken
from:
Peterson et al. Statistical limitations in functional neuroimaging
I. Non-inferential methods and statistical models. Phil Trans Royal Soc
Lond B 354: 1239-1260.
Usage: aglm(data,para)
Returns: statistic, p-value ???
"""
if len(para) <> len(data):
print "data and para must be same length in aglm"
return
n = len(para)
p = pstat.aunique(para)
x = N.zeros((n,len(p))) # design matrix
for l in range(len(p)):
x[:,l] = N.equal(para,p[l])
b = N.dot(N.dot(LA.inverse(N.dot(N.transpose(x),x)), # i.e., b=inv(X'X)X'Y
N.transpose(x)),
data)
diffs = (data - N.dot(x,b))
s_sq = 1./(n-len(p)) * N.dot(N.transpose(diffs), diffs)
if len(p) == 2: # ttest_ind
c = N.array([1,-1])
df = n-2
fact = asum(1.0/asum(x,0)) # i.e., 1/n1 + 1/n2 + 1/n3 ...
t = N.dot(c,b) / N.sqrt(s_sq*fact)
probs = abetai(0.5*df,0.5,float(df)/(df+t*t))
return t, probs
def aF_oneway(*args):
"""
Performs a 1-way ANOVA, returning an F-value and probability given
any number of groups. From Heiman, pp.394-7.
Usage: aF_oneway (*args) where *args is 2 or more arrays, one per
treatment group
Returns: f-value, probability
"""
na = len(args) # ANOVA on 'na' groups, each in it's own array
means = [0]*na
vars = [0]*na
ns = [0]*na
alldata = []
tmp = map(N.array,args)
means = map(amean,tmp)
vars = map(avar,tmp)
ns = map(len,args)
alldata = N.concatenate(args)
bign = len(alldata)
sstot = ass(alldata)-(asquare_of_sums(alldata)/float(bign))
ssbn = 0
for a in args:
ssbn = ssbn + asquare_of_sums(N.array(a))/float(len(a))
ssbn = ssbn - (asquare_of_sums(alldata)/float(bign))
sswn = sstot-ssbn
dfbn = na-1
dfwn = bign - na
msb = ssbn/float(dfbn)
msw = sswn/float(dfwn)
f = msb/msw
prob = fprob(dfbn,dfwn,f)
return f, prob
def aF_value (ER,EF,dfR,dfF):
"""
Returns an F-statistic given the following:
ER = error associated with the null hypothesis (the Restricted model)
EF = error associated with the alternate hypothesis (the Full model)
dfR = degrees of freedom the Restricted model
dfF = degrees of freedom associated with the Restricted model
"""
return ((ER-EF)/float(dfR-dfF) / (EF/float(dfF)))
def outputfstats(Enum, Eden, dfnum, dfden, f, prob):
Enum = round(Enum,3)
Eden = round(Eden,3)
dfnum = round(Enum,3)
dfden = round(dfden,3)
f = round(f,3)
prob = round(prob,3)
suffix = '' # for *s after the p-value
if prob < 0.001: suffix = ' ***'
elif prob < 0.01: suffix = ' **'
elif prob < 0.05: suffix = ' *'
title = [['EF/ER','DF','Mean Square','F-value','prob','']]
lofl = title+[[Enum, dfnum, round(Enum/float(dfnum),3), f, prob, suffix],
[Eden, dfden, round(Eden/float(dfden),3),'','','']]
pstat.printcc(lofl)
return
def F_value_multivariate(ER, EF, dfnum, dfden):
"""
Returns an F-statistic given the following:
ER = error associated with the null hypothesis (the Restricted model)
EF = error associated with the alternate hypothesis (the Full model)
dfR = degrees of freedom the Restricted model
dfF = degrees of freedom associated with the Restricted model
where ER and EF are matrices from a multivariate F calculation.
"""
if type(ER) in [IntType, FloatType]:
ER = N.array([[ER]])
if type(EF) in [IntType, FloatType]:
EF = N.array([[EF]])
n_um = (LA.determinant(ER) - LA.determinant(EF)) / float(dfnum)
d_en = LA.determinant(EF) / float(dfden)
return n_um / d_en
#####################################
####### ASUPPORT FUNCTIONS ########
#####################################
def asign(a):
"""
Usage: asign(a)
Returns: array shape of a, with -1 where a<0 and +1 where a>=0
"""
a = N.asarray(a)
if ((type(a) == type(1.4)) or (type(a) == type(1))):
return a-a-N.less(a,0)+N.greater(a,0)
else:
return N.zeros(N.shape(a))-N.less(a,0)+N.greater(a,0)
def asum (a, dimension=None,keepdims=0):
"""
An alternative to the Numeric.add.reduce function, which allows one to
(1) collapse over multiple dimensions at once, and/or (2) to retain
all dimensions in the original array (squashing one down to size.
Dimension can equal None (ravel array first), an integer (the
dimension over which to operate), or a sequence (operate over multiple
dimensions). If keepdims=1, the resulting array will have as many
dimensions as the input array.
Usage: asum(a, dimension=None, keepdims=0)
Returns: array summed along 'dimension'(s), same _number_ of dims if keepdims=1
"""
if type(a) == N.ArrayType and a.typecode() in ['l','s','b']:
a = a.astype(N.Float)
if dimension == None:
s = N.sum(N.ravel(a))
elif type(dimension) in [IntType,FloatType]:
s = N.add.reduce(a, dimension)
if keepdims == 1:
shp = list(a.shape)
shp[dimension] = 1
s = N.reshape(s,shp)
else: # must be a SEQUENCE of dims to sum over
dims = list(dimension)
dims.sort()
dims.reverse()
s = a *1.0
for dim in dims:
s = N.add.reduce(s,dim)
if keepdims == 1:
shp = list(a.shape)
for dim in dims:
shp[dim] = 1
s = N.reshape(s,shp)
return s
def acumsum (a,dimension=None):
"""
Returns an array consisting of the cumulative sum of the items in the
passed array. Dimension can equal None (ravel array first), an
integer (the dimension over which to operate), or a sequence (operate
over multiple dimensions, but this last one just barely makes sense).
Usage: acumsum(a,dimension=None)
"""
if dimension == None:
a = N.ravel(a)
dimension = 0
if type(dimension) in [ListType, TupleType, N.ArrayType]:
dimension = list(dimension)
dimension.sort()
dimension.reverse()
for d in dimension:
a = N.add.accumulate(a,d)
return a
else:
return N.add.accumulate(a,dimension)
def ass(inarray, dimension=None, keepdims=0):
"""
Squares each value in the passed array, adds these squares & returns
the result. Unfortunate function name. :-) Defaults to ALL values in
the array. Dimension can equal None (ravel array first), an integer
(the dimension over which to operate), or a sequence (operate over
multiple dimensions). Set keepdims=1 to maintain the original number
of dimensions.
Usage: ass(inarray, dimension=None, keepdims=0)
Returns: sum-along-'dimension' for (inarray*inarray)
"""
if dimension == None:
inarray = N.ravel(inarray)
dimension = 0
return asum(inarray*inarray,dimension,keepdims)
def asummult (array1,array2,dimension=None,keepdims=0):
"""
Multiplies elements in array1 and array2, element by element, and
returns the sum (along 'dimension') of all resulting multiplications.
Dimension can equal None (ravel array first), an integer (the
dimension over which to operate), or a sequence (operate over multiple
dimensions). A trivial function, but included for completeness.
Usage: asummult(array1,array2,dimension=None,keepdims=0)
"""
if dimension == None:
array1 = N.ravel(array1)
array2 = N.ravel(array2)
dimension = 0
return asum(array1*array2,dimension,keepdims)
def asquare_of_sums(inarray, dimension=None, keepdims=0):
"""
Adds the values in the passed array, squares that sum, and returns the
result. Dimension can equal None (ravel array first), an integer (the
dimension over which to operate), or a sequence (operate over multiple
dimensions). If keepdims=1, the returned array will have the same
NUMBER of dimensions as the original.
Usage: asquare_of_sums(inarray, dimension=None, keepdims=0)
Returns: the square of the sum over dim(s) in dimension
"""
if dimension == None:
inarray = N.ravel(inarray)
dimension = 0
s = asum(inarray,dimension,keepdims)
if type(s) == N.ArrayType:
return s.astype(N.Float)*s
else:
return float(s)*s
def asumdiffsquared(a,b, dimension=None, keepdims=0):
"""
Takes pairwise differences of the values in arrays a and b, squares
these differences, and returns the sum of these squares. Dimension
can equal None (ravel array first), an integer (the dimension over
which to operate), or a sequence (operate over multiple dimensions).
keepdims=1 means the return shape = len(a.shape) = len(b.shape)
Usage: asumdiffsquared(a,b)
Returns: sum[ravel(a-b)**2]
"""
if dimension == None:
inarray = N.ravel(a)
dimension = 0
return asum((a-b)**2,dimension,keepdims)
def ashellsort(inarray):
"""
Shellsort algorithm. Sorts a 1D-array.
Usage: ashellsort(inarray)
Returns: sorted-inarray, sorting-index-vector (for original array)
"""
n = len(inarray)
svec = inarray *1.0
ivec = range(n)
gap = n/2 # integer division needed
while gap >0:
for i in range(gap,n):
for j in range(i-gap,-1,-gap):
while j>=0 and svec[j]>svec[j+gap]:
temp = svec[j]
svec[j] = svec[j+gap]
svec[j+gap] = temp
itemp = ivec[j]
ivec[j] = ivec[j+gap]
ivec[j+gap] = itemp
gap = gap / 2 # integer division needed
# svec is now sorted input vector, ivec has the order svec[i] = vec[ivec[i]]
return svec, ivec
def arankdata(inarray):
"""
Ranks the data in inarray, dealing with ties appropritely. Assumes
a 1D inarray. Adapted from Gary Perlman's |Stat ranksort.
Usage: arankdata(inarray)
Returns: array of length equal to inarray, containing rank scores
"""
n = len(inarray)
svec, ivec = ashellsort(inarray)
sumranks = 0
dupcount = 0
newarray = N.zeros(n,N.Float)
for i in range(n):
sumranks = sumranks + i
dupcount = dupcount + 1
if i==n-1 or svec[i] <> svec[i+1]:
averank = sumranks / float(dupcount) + 1
for j in range(i-dupcount+1,i+1):
newarray[ivec[j]] = averank
sumranks = 0
dupcount = 0
return newarray
def afindwithin(data):
"""
Returns a binary vector, 1=within-subject factor, 0=between. Input
equals the entire data array (i.e., column 1=random factor, last
column = measured values.
Usage: afindwithin(data) data in |Stat format
"""
numfact = len(data[0])-2
withinvec = [0]*numfact
for col in range(1,numfact+1):
rows = pstat.linexand(data,col,pstat.unique(pstat.colex(data,1))[0]) # get 1 level of this factor
if len(pstat.unique(pstat.colex(rows,0))) < len(rows): # if fewer subjects than scores on this factor
withinvec[col-1] = 1
return withinvec
#########################################################
#########################################################
###### RE-DEFINE DISPATCHES TO INCLUDE ARRAYS #########
#########################################################
#########################################################
## CENTRAL TENDENCY:
geometricmean = Dispatch ( (lgeometricmean, (ListType, TupleType)),
(ageometricmean, (N.ArrayType,)) )
harmonicmean = Dispatch ( (lharmonicmean, (ListType, TupleType)),
(aharmonicmean, (N.ArrayType,)) )
mean = Dispatch ( (lmean, (ListType, TupleType)),
(amean, (N.ArrayType,)) )
median = Dispatch ( (lmedian, (ListType, TupleType)),
(amedian, (N.ArrayType,)) )
medianscore = Dispatch ( (lmedianscore, (ListType, TupleType)),
(amedianscore, (N.ArrayType,)) )
mode = Dispatch ( (lmode, (ListType, TupleType)),
(amode, (N.ArrayType,)) )
tmean = Dispatch ( (atmean, (N.ArrayType,)) )
tvar = Dispatch ( (atvar, (N.ArrayType,)) )
tstdev = Dispatch ( (atstdev, (N.ArrayType,)) )
tsem = Dispatch ( (atsem, (N.ArrayType,)) )
## VARIATION:
moment = Dispatch ( (lmoment, (ListType, TupleType)),
(amoment, (N.ArrayType,)) )
variation = Dispatch ( (lvariation, (ListType, TupleType)),
(avariation, (N.ArrayType,)) )
skew = Dispatch ( (lskew, (ListType, TupleType)),
(askew, (N.ArrayType,)) )
kurtosis = Dispatch ( (lkurtosis, (ListType, TupleType)),
(akurtosis, (N.ArrayType,)) )
describe = Dispatch ( (ldescribe, (ListType, TupleType)),
(adescribe, (N.ArrayType,)) )
## DISTRIBUTION TESTS
skewtest = Dispatch ( (askewtest, (ListType, TupleType)),
(askewtest, (N.ArrayType,)) )
kurtosistest = Dispatch ( (akurtosistest, (ListType, TupleType)),
(akurtosistest, (N.ArrayType,)) )
normaltest = Dispatch ( (anormaltest, (ListType, TupleType)),
(anormaltest, (N.ArrayType,)) )
## FREQUENCY STATS:
itemfreq = Dispatch ( (litemfreq, (ListType, TupleType)),
(aitemfreq, (N.ArrayType,)) )
scoreatpercentile = Dispatch ( (lscoreatpercentile, (ListType, TupleType)),
(ascoreatpercentile, (N.ArrayType,)) )
percentileofscore = Dispatch ( (lpercentileofscore, (ListType, TupleType)),
(apercentileofscore, (N.ArrayType,)) )
histogram = Dispatch ( (lhistogram, (ListType, TupleType)),
(ahistogram, (N.ArrayType,)) )
cumfreq = Dispatch ( (lcumfreq, (ListType, TupleType)),
(acumfreq, (N.ArrayType,)) )
relfreq = Dispatch ( (lrelfreq, (ListType, TupleType)),
(arelfreq, (N.ArrayType,)) )
## VARIABILITY:
obrientransform = Dispatch ( (lobrientransform, (ListType, TupleType)),
(aobrientransform, (N.ArrayType,)) )
samplevar = Dispatch ( (lsamplevar, (ListType, TupleType)),
(asamplevar, (N.ArrayType,)) )
samplestdev = Dispatch ( (lsamplestdev, (ListType, TupleType)),
(asamplestdev, (N.ArrayType,)) )
signaltonoise = Dispatch( (asignaltonoise, (N.ArrayType,)),)
var = Dispatch ( (lvar, (ListType, TupleType)),
(avar, (N.ArrayType,)) )
stdev = Dispatch ( (lstdev, (ListType, TupleType)),
(astdev, (N.ArrayType,)) )
sterr = Dispatch ( (lsterr, (ListType, TupleType)),
(asterr, (N.ArrayType,)) )
sem = Dispatch ( (lsem, (ListType, TupleType)),
(asem, (N.ArrayType,)) )
z = Dispatch ( (lz, (ListType, TupleType)),
(az, (N.ArrayType,)) )
zs = Dispatch ( (lzs, (ListType, TupleType)),
(azs, (N.ArrayType,)) )
## TRIMMING FCNS:
threshold = Dispatch( (athreshold, (N.ArrayType,)),)
trimboth = Dispatch ( (ltrimboth, (ListType, TupleType)),
(atrimboth, (N.ArrayType,)) )
trim1 = Dispatch ( (ltrim1, (ListType, TupleType)),
(atrim1, (N.ArrayType,)) )
## CORRELATION FCNS:
paired = Dispatch ( (lpaired, (ListType, TupleType)),
(apaired, (N.ArrayType,)) )
pearsonr = Dispatch ( (lpearsonr, (ListType, TupleType)),
(apearsonr, (N.ArrayType,)) )
spearmanr = Dispatch ( (lspearmanr, (ListType, TupleType)),
(aspearmanr, (N.ArrayType,)) )
pointbiserialr = Dispatch ( (lpointbiserialr, (ListType, TupleType)),
(apointbiserialr, (N.ArrayType,)) )
kendalltau = Dispatch ( (lkendalltau, (ListType, TupleType)),
(akendalltau, (N.ArrayType,)) )
linregress = Dispatch ( (llinregress, (ListType, TupleType)),
(alinregress, (N.ArrayType,)) )
## INFERENTIAL STATS:
ttest_1samp = Dispatch ( (lttest_1samp, (ListType, TupleType)),
(attest_1samp, (N.ArrayType,)) )
ttest_ind = Dispatch ( (lttest_ind, (ListType, TupleType)),
(attest_ind, (N.ArrayType,)) )
ttest_rel = Dispatch ( (lttest_rel, (ListType, TupleType)),
(attest_rel, (N.ArrayType,)) )
chisquare = Dispatch ( (lchisquare, (ListType, TupleType)),
(achisquare, (N.ArrayType,)) )
ks_2samp = Dispatch ( (lks_2samp, (ListType, TupleType)),
(aks_2samp, (N.ArrayType,)) )
mannwhitneyu = Dispatch ( (lmannwhitneyu, (ListType, TupleType)),
(amannwhitneyu, (N.ArrayType,)) )
tiecorrect = Dispatch ( (ltiecorrect, (ListType, TupleType)),
(atiecorrect, (N.ArrayType,)) )
ranksums = Dispatch ( (lranksums, (ListType, TupleType)),
(aranksums, (N.ArrayType,)) )
wilcoxont = Dispatch ( (lwilcoxont, (ListType, TupleType)),
(awilcoxont, (N.ArrayType,)) )
kruskalwallish = Dispatch ( (lkruskalwallish, (ListType, TupleType)),
(akruskalwallish, (N.ArrayType,)) )
friedmanchisquare = Dispatch ( (lfriedmanchisquare, (ListType, TupleType)),
(afriedmanchisquare, (N.ArrayType,)) )
## PROBABILITY CALCS:
chisqprob = Dispatch ( (lchisqprob, (IntType, FloatType)),
(achisqprob, (N.ArrayType,)) )
zprob = Dispatch ( (lzprob, (IntType, FloatType)),
(azprob, (N.ArrayType,)) )
ksprob = Dispatch ( (lksprob, (IntType, FloatType)),
(aksprob, (N.ArrayType,)) )
fprob = Dispatch ( (lfprob, (IntType, FloatType)),
(afprob, (N.ArrayType,)) )
betacf = Dispatch ( (lbetacf, (IntType, FloatType)),
(abetacf, (N.ArrayType,)) )
betai = Dispatch ( (lbetai, (IntType, FloatType)),
(abetai, (N.ArrayType,)) )
erfcc = Dispatch ( (lerfcc, (IntType, FloatType)),
(aerfcc, (N.ArrayType,)) )
gammln = Dispatch ( (lgammln, (IntType, FloatType)),
(agammln, (N.ArrayType,)) )
## ANOVA FUNCTIONS:
F_oneway = Dispatch ( (lF_oneway, (ListType, TupleType)),
(aF_oneway, (N.ArrayType,)) )
F_value = Dispatch ( (lF_value, (ListType, TupleType)),
(aF_value, (N.ArrayType,)) )
## SUPPORT FUNCTIONS:
incr = Dispatch ( (lincr, (ListType, TupleType, N.ArrayType)), )
sum = Dispatch ( (lsum, (ListType, TupleType)),
(asum, (N.ArrayType,)) )
cumsum = Dispatch ( (lcumsum, (ListType, TupleType)),
(acumsum, (N.ArrayType,)) )
ss = Dispatch ( (lss, (ListType, TupleType)),
(ass, (N.ArrayType,)) )
summult = Dispatch ( (lsummult, (ListType, TupleType)),
(asummult, (N.ArrayType,)) )
square_of_sums = Dispatch ( (lsquare_of_sums, (ListType, TupleType)),
(asquare_of_sums, (N.ArrayType,)) )
sumdiffsquared = Dispatch ( (lsumdiffsquared, (ListType, TupleType)),
(asumdiffsquared, (N.ArrayType,)) )
shellsort = Dispatch ( (lshellsort, (ListType, TupleType)),
(ashellsort, (N.ArrayType,)) )
rankdata = Dispatch ( (lrankdata, (ListType, TupleType)),
(arankdata, (N.ArrayType,)) )
findwithin = Dispatch ( (lfindwithin, (ListType, TupleType)),
(afindwithin, (N.ArrayType,)) )
###################### END OF NUMERIC FUNCTION BLOCK #####################
###################### END OF STATISTICAL FUNCTIONS ######################
except ImportError:
pass
| Python |
# Copyright (c) Gary Strangman. All rights reserved
#
# Disclaimer
#
# This software is provided "as-is". There are no expressed or implied
# warranties of any kind, including, but not limited to, the warranties
# of merchantability and fittness for a given application. In no event
# shall Gary Strangman be liable for any direct, indirect, incidental,
# special, exemplary or consequential damages (including, but not limited
# to, loss of use, data or profits, or business interruption) however
# caused and on any theory of liability, whether in contract, strict
# liability or tort (including negligence or otherwise) arising in any way
# out of the use of this software, even if advised of the possibility of
# such damage.
#
# Comments and/or additions are welcome (send e-mail to:
# strang@nmr.mgh.harvard.edu).
#
"""
Defines a number of functions for pseudo-command-line OS functionality.
cd(directory)
pwd <-- can be used WITHOUT parens
ls(d='.')
rename(from,to)
get(namepatterns,verbose=1)
getstrings(namepatterns,verbose=1)
put(outlist,filename,writetype='w')
aget(namepatterns,verbose=1)
aput(outarray,filename,writetype='w')
bget(filename,numslices=1,xsize=64,ysize=64)
braw(filename,btype)
bput(outarray,filename,writeheader=0,packstring='h',writetype='wb')
mrget(filename)
find_dirs(sourcedir)
"""
## CHANGES:
## =======
## 02-11-20 ... added binget(), binput(), array2afni(), version 0.5
## 02-10-20 ... added find_dirs() function, changed version to 0.4
## 01-11-15 ... changed aput() and put() to accept a delimiter
## 01-04-19 ... added oneperline option to put() function
## 99-11-07 ... added DAs quick flat-text-file loaders, load() and fload()
## 99-11-01 ... added version number (0.1) for distribution
## 99-08-30 ... Put quickload in here
## 99-06-27 ... Changed bget thing back ... confused ...
## 99-06-24 ... exchanged xsize and ysize in bget for non-square images (NT??)
## modified bget to raise an IOError when file not found
## 99-06-12 ... added load() and save() aliases for aget() and aput() (resp.)
## 99-04-13 ... changed aget() to ignore (!!!!) lines beginning with # or %
## 99-01-17 ... changed get() so ints come in as ints (not floats)
##
try:
import mmapfile
except:
pass
import pstat
import glob, re, string, types, os, Numeric, struct, copy, time, tempfile, sys
from types import *
N = Numeric
__version__ = 0.5
def wrap(f):
"""
Wraps a function so that if it's entered *by itself*
in the interpreter without ()'s, it gets called anyway
"""
class W:
def __init__(self, f):
self.f = f
def __repr__(self):
x =apply(self.f)
if x:
return repr(x)
else:
return ''
return W(f)
def cd (directory):
"""
Changes the working python directory for the interpreter.
Usage: cd(directory) where 'directory' is a string
"""
os.chdir(directory)
return
def pwd():
"""
Changes the working python directory for the interpreter.
Usage: pwd (no parens needed)
"""
return os.getcwd()
pwd = wrap(pwd)
def ls(d='.'):
"""
Produces a directory listing. Default is the current directory.
Usage: ls(d='.')
"""
os.system('ls '+d)
return None
def rename(source, dest):
"""
Renames files specified by UNIX inpattern to those specified by UNIX
outpattern. Can only handle a single '*' in the two patterns!!!
Usage: rename (source, dest) e.g., rename('*.txt', '*.c')
"""
infiles = glob.glob(source)
outfiles = []
incutindex = string.index(source,'*')
outcutindex = string.index(source,'*')
findpattern1 = source[0:incutindex]
findpattern2 = source[incutindex+1:]
replpattern1 = dest[0:incutindex]
replpattern2 = dest[incutindex+1:]
for fname in infiles:
if incutindex > 0:
newname = re.sub(findpattern1,replpattern1,fname,1)
if outcutindex < len(dest)-1:
if incutindex > 0:
lastone = string.rfind(newname,replpattern2)
newname = newname[0:lastone] + re.sub(findpattern2,replpattern2,fname[lastone:],1)
else:
lastone = string.rfind(fname,findpattern2)
if lastone <> -1:
newname = fname[0:lastone]
newname = newname + re.sub(findpattern2,replpattern2,fname[lastone:],1)
os.rename(fname,newname)
return
def get (namepatterns,verbose=1):
"""
Loads a list of lists from text files (specified by a UNIX-style
wildcard filename pattern) and converts all numeric values to floats.
Uses the glob module for filename pattern conversion. Loaded filename
is printed if verbose=1.
Usage: get (namepatterns,verbose=1)
Returns: a 1D or 2D list of lists from whitespace delimited text files
specified by namepatterns; numbers that can be converted to floats
are so converted
"""
fnames = []
if type(namepatterns) in [ListType,TupleType]:
for item in namepatterns:
fnames = fnames + glob.glob(item)
else:
fnames = glob.glob(namepatterns)
if len(fnames) == 0:
if verbose:
print 'NO FILENAMES MATCH ('+namepatterns+') !!'
return None
if verbose:
print fnames # so user knows what has been loaded
elements = []
for i in range(len(fnames)):
file = open(fnames[i])
newelements = map(string.split,file.readlines())
for i in range(len(newelements)):
for j in range(len(newelements[i])):
try:
newelements[i][j] = string.atoi(newelements[i][j])
except ValueError:
try:
newelements[i][j] = string.atof(newelements[i][j])
except:
pass
elements = elements + newelements
if len(elements)==1: elements = elements[0]
return elements
def getstrings (namepattern,verbose=1):
"""
Loads a (set of) text file(s), with all elements left as string type.
Uses UNIX-style wildcards (i.e., function uses glob). Loaded filename
is printed if verbose=1.
Usage: getstrings (namepattern, verbose=1)
Returns: a list of strings, one per line in each text file specified by
namepattern
"""
fnames = glob.glob(namepattern)
if len(fnames) == 0:
if verbose:
print 'NO FILENAMES MATCH ('+namepattern+') !!'
return None
if verbose:
print fnames
elements = []
for filename in fnames:
file = open(filename)
newelements = map(string.split,file.readlines())
elements = elements + newelements
return elements
def put (outlist,fname,writetype='w',oneperline=0,delimit=' '):
"""
Writes a passed mixed-type list (str and/or numbers) to an output
file, and then closes the file. Default is overwrite the destination
file.
Usage: put (outlist,fname,writetype='w',oneperline=0,delimit=' ')
Returns: None
"""
if type(outlist) in [N.ArrayType]:
aput(outlist,fname,writetype)
return
if type(outlist[0]) not in [ListType,TupleType]: # 1D list
outfile = open(fname,writetype)
if not oneperline:
outlist = pstat.list2string(outlist,delimit)
outfile.write(outlist)
outfile.write('\n')
else: # they want one element from the list on each file line
for item in outlist:
outfile.write(str(item)+'\n')
outfile.close()
else: # 2D list (list-of-lists)
outfile = open(fname,writetype)
for row in outlist:
outfile.write(pstat.list2string(row,delimit))
outfile.write('\n')
outfile.close()
return None
def isstring(x):
if type(x)==StringType:
return 1
else:
return 0
def aget (namepattern,verbose=1):
"""
Loads an array from 2D text files (specified by a UNIX-style wildcard
filename pattern). ONLY 'GET' FILES WITH EQUAL NUMBERS OF COLUMNS
ON EVERY ROW (otherwise returned array will be zero-dimensional).
Usage: aget (namepattern)
Returns: an array of integers, floats or objects (type='O'), depending on the
contents of the files specified by namepattern
"""
fnames = glob.glob(namepattern)
if len(fnames) == 0:
if verbose:
print 'NO FILENAMES MATCH ('+namepattern+') !!'
return None
if verbose:
print fnames
elements = []
for filename in fnames:
file = open(filename)
newelements = file.readlines()
del_list = []
for row in range(len(newelements)):
if (newelements[row][0]=='%' or newelements[row][0]=='#'
or len(newelements[row])==1):
del_list.append(row)
del_list.reverse()
for i in del_list:
newelements.pop(i)
newelements = map(string.split,newelements)
for i in range(len(newelements)):
for j in range(len(newelements[i])):
try:
newelements[i][j] = string.atof(newelements[i][j])
except:
pass
elements = elements + newelements
for row in range(len(elements)):
if N.add.reduce(N.array(map(isstring,elements[row])))==len(elements[row]):
print "A row of strings was found. Returning a LIST."
return elements
try:
elements = N.array(elements)
except TypeError:
elements = N.array(elements,'O')
return elements
def aput (outarray,fname,writetype='w',delimit=' '):
"""
Sends passed 1D or 2D array to an output file and closes the file.
Usage: aput (outarray,fname,writetype='w',delimit=' ')
Returns: None
"""
outfile = open(fname,writetype)
if len(outarray.shape) == 1:
outarray = outarray[N.NewAxis,:]
if len(outarray.shape) > 2:
raise TypeError, "put() and aput() require 1D or 2D arrays. Otherwise use some kind of pickling."
else: # must be a 2D array
for row in outarray:
outfile.write(string.join(map(str,row),delimit))
outfile.write('\n')
outfile.close()
return None
def bget(imfile,shp=None,unpackstr=N.Int16,bytesperpixel=2.0,sliceinit=0):
"""
Reads in a binary file, typically with a .bshort or .bfloat extension.
If so, the last 3 parameters are set appropriately. If not, the last 3
parameters default to reading .bshort files (2-byte integers in big-endian
binary format).
Usage: bget(imfile,shp=None,unpackstr=N.Int16,bytesperpixel=2.0,sliceinit=0)
"""
if imfile[:3] == 'COR':
return CORget(imfile)
if imfile[-2:] == 'MR':
return mrget(imfile,unpackstr)
if imfile[-4:] == 'BRIK':
return brikget(imfile,unpackstr,shp)
if imfile[-3:] in ['mnc','MNC']:
return mincget(imfile,unpackstr,shp)
if imfile[-3:] == 'img':
return mghbget(imfile,unpackstr,shp)
if imfile[-6:] == 'bshort' or imfile[-6:] == 'bfloat':
if shp == None:
return mghbget(imfile,unpackstr=unpackstr,bytesperpixel=bytesperpixel,sliceinit=sliceinit)
else:
return mghbget(imfile,shp[0],shp[1],shp[2],unpackstr,bytesperpixel,sliceinit)
def CORget(infile):
"""
Reads a binary COR-nnn file (flattening file).
Usage: CORget(imfile)
Returns: 2D array of 16-bit ints
"""
d=braw(infile,N.Int8)
d.shape = (256,256)
d = N.where(N.greater_equal(d,0),d,256+d)
return d
def mincget(imfile,unpackstr=N.Int16,shp=None):
"""
Loads in a .MNC file.
Usage: mincget(imfile,unpackstr=N.Int16,shp=None) default shp = -1,20,64,64
"""
if shp == None:
shp = (-1,20,64,64)
os.system('mincextract -short -range 0 4095 -image_range 0 4095 ' +
imfile+' > minctemp.bshort')
try:
d = braw('minctemp.bshort',unpackstr)
except:
print "Couldn't find file: "+imfile
raise IOError, "Couldn't find file in mincget()"
print shp, d.shape
d.shape = shp
os.system('rm minctemp.bshort')
return d
def brikget(imfile,unpackstr=N.Int16,shp=None):
"""
Gets an AFNI BRIK file.
Usage: brikget(imfile,unpackstr=N.Int16,shp=None) default shp: (-1,48,61,51)
"""
if shp == None:
shp = (-1,48,61,51)
try:
file = open(imfile, "rb")
except:
print "Couldn't find file: "+imfile
raise IOError, "Couldn't find file in brikget()"
try:
header = imfile[0:-4]+'HEAD'
lines = open(header).readlines()
for i in range(len(lines)):
if string.find(lines[i],'DATASET_DIMENSIONS') <> -1:
dims = string.split(lines[i+2][0:string.find(lines[i+2],' 0')])
dims = map(string.atoi,dims)
if string.find(lines[i],'BRICK_FLOAT_FACS') <> -1:
count = string.atoi(string.split(lines[i+1])[2])
mults = []
for j in range(int(N.ceil(count/5.))):
mults += map(string.atof,string.split(lines[i+2+j]))
mults = N.array(mults)
dims.reverse()
shp = [-1]+dims
except IOError:
print "No header file. Continuing ..."
lines = None
print shp
print 'Using unpackstr:',unpackstr #,', bytesperpixel=',bytesperpixel
file = open(imfile, "rb")
bdata = file.read()
# the > forces big-endian (for or from Sun/SGI)
bdata = N.fromstring(bdata,unpackstr)
littleEndian = ( struct.pack('i',1)==struct.pack('<i',1) )
if (littleEndian and os.uname()[0]<>'Linux') or (max(bdata)>1e30):
bdata = bdata.byteswapped()
try:
bdata.shape = shp
except:
print 'Incorrect shape ...',shp,len(bdata)
raise ValueError, 'Incorrect shape for file size'
if len(bdata) == 1:
bdata = bdata[0]
if N.sum(mults) == 0:
return bdata
try:
multshape = [1]*len(bdata.shape)
for i in range(len(bdata.shape)):
if len(mults) == bdata.shape[i]:
multshape[i] = len(mults)
break
mults.shape = multshape
return bdata*mults
except:
return bdata
def mghbget(imfile,numslices=-1,xsize=64,ysize=64,
unpackstr=N.Int16,bytesperpixel=2.0,sliceinit=0):
"""
Reads in a binary file, typically with a .bshort or .bfloat extension.
If so, the last 3 parameters are set appropriately. If not, the last 3
parameters default to reading .bshort files (2-byte integers in big-endian
binary format).
Usage: mghbget(imfile, numslices=-1, xsize=64, ysize=64,
unpackstr=N.Int16, bytesperpixel=2.0, sliceinit=0)
"""
try:
file = open(imfile, "rb")
except:
print "Couldn't find file: "+imfile
raise IOError, "Couldn't find file in bget()"
try:
header = imfile[0:-6]+'hdr'
vals = get(header,0) # '0' means no missing-file warning msg
if type(vals[0]) == ListType: # it's an extended header
xsize = int(vals[0][0])
ysize = int(vals[0][1])
numslices = int(vals[0][2])
else:
xsize = int(vals[0])
ysize = int(vals[1])
numslices = int(vals[2])
except:
print "No header file. Continuing ..."
suffix = imfile[-6:]
if suffix == 'bshort':
pass
elif suffix[-3:] == 'img':
pass
elif suffix == 'bfloat':
unpackstr = N.Float32
bytesperpixel = 4.0
sliceinit = 0.0
else:
print 'Not a bshort, bfloat or img file.'
print 'Using unpackstr:',unpackstr,', bytesperpixel=',bytesperpixel
imsize = xsize*ysize
file = open(imfile, "rb")
bdata = file.read()
numpixels = len(bdata) / bytesperpixel
if numpixels%1 != 0:
raise ValueError, "Incorrect file size in fmri.bget()"
else: # the > forces big-endian (for or from Sun/SGI)
bdata = N.fromstring(bdata,unpackstr)
littleEndian = ( struct.pack('i',1)==struct.pack('<i',1) )
# if littleEndian:
# bdata = bdata.byteswapped()
if (littleEndian and os.uname()[0]<>'Linux') or (max(bdata)>1e30):
bdata = bdata.byteswapped()
if suffix[-3:] == 'img':
if numslices == -1:
numslices = len(bdata)/8200 # 8200=(64*64*2)+8 bytes per image
xsize = 64
ysize = 128
slices = N.zeros((numslices,xsize,ysize),N.Int)
for i in range(numslices):
istart = i*8 + i*xsize*ysize
iend = i*8 + (i+1)*xsize*ysize
print i, istart,iend
slices[i] = N.reshape(N.array(bdata[istart:iend]),(xsize,ysize))
else:
if numslices == 1:
slices = N.reshape(N.array(bdata),[xsize,ysize])
else:
slices = N.reshape(N.array(bdata),[numslices,xsize,ysize])
if len(slices) == 1:
slices = slices[0]
return slices
def braw(fname,btype,shp=None):
"""
Opens a binary file, unpacks it, and returns a flat array of the
type specified. Use Numeric types ... N.Float32, N.Int64, etc.
Usage: braw(fname,btype,shp=None)
Returns: flat array of floats, or ints (if btype=N.Int16)
"""
file = open(fname,'rb')
bdata = file.read()
bdata = N.fromstring(bdata,btype)
littleEndian = ( struct.pack('i',1)==struct.pack('<i',1) )
# if littleEndian:
# bdata = bdata.byteswapped() # didn't used to need this with '>' above
if (littleEndian and os.uname()[0]<>'Linux') or (max(bdata)>1e30):
bdata = bdata.byteswapped()
if shp:
try:
bdata.shape = shp
return bdata
except:
pass
return N.array(bdata)
def glget(fname,btype):
"""
Load in a file containing pixels from glReadPixels dump.
Usage: glget(fname,btype)
Returns: array of 'btype elements with shape 'shape', suitable for im.ashow()
"""
d = braw(fname,btype)
d = d[8:]
f = open(fname,'rb')
shp = f.read(8)
f.close()
shp = N.fromstring(shp,N.Int)
shp[0],shp[1] = shp[1],shp[0]
try:
carray = N.reshape(d,shp)
return
except:
pass
try:
r = d[0::3]+0
g = d[1::3]+0
b = d[2::3]+0
r.shape = shp
g.shape = shp
b.shape = shp
carray = N.array([r,g,b])
except:
outstr = "glget: shape not correct for data of length "+str(len(d))
raise ValueError, outstr
return carray
def mget(fname,btype):
"""
Load in a file that was saved from matlab
Usage: mget(fname,btype)
"""
d = braw(fname,btype)
try:
header = fname[0:-6]+'hdr'
vals = get(header,0) # '0' means no missing-file warning msg
if type(vals[0]) == ListType: # it's an extended header
xsize = int(vals[0][0])
ysize = int(vals[0][1])
numslices = int(vals[0][2])
else:
xsize = int(vals[0])
ysize = int(vals[1])
numslices = int(vals[2])
print xsize,ysize,numslices, d.shape
except:
print "No header file. Continuing ..."
if numslices == 1:
d.shape = [ysize,xsize]
return N.transpose(d)*1
else:
d.shape = [numslices,ysize,xsize]
return N.transpose(d)*1
def mput(outarray,fname,writeheader=0,btype=N.Int16):
"""
Save a file for use in matlab.
"""
outarray = N.transpose(outarray)
outdata = N.ravel(outarray).astype(btype)
outdata = outdata.tostring()
outfile = open(fname,'wb')
outfile.write(outdata)
outfile.close()
if writeheader == 1:
try:
suffixindex = string.rfind(fname,'.')
hdrname = fname[0:suffixindex]
except ValueError:
hdrname = fname
if len(outarray.shape) == 2:
hdr = [outarray.shape[1],outarray.shape[0], 1, 0]
else:
hdr = [outarray.shape[2],outarray.shape[1],outarray.shape[0], 0,'\n']
print hdrname+'.hdr'
outfile = open(hdrname+'.hdr','w')
outfile.write(pstat.list2string(hdr))
outfile.close()
return None
def bput(outarray,fname,writeheader=0,packtype=N.Int16,writetype='wb'):
"""
Writes the passed array to a binary output file, and then closes
the file. Default is overwrite the destination file.
Usage: bput (outarray,filename,writeheader=0,packtype=N.Int16,writetype='wb')
"""
suffix = fname[-6:]
if suffix == 'bshort':
packtype = N.Int16
elif suffix == 'bfloat':
packtype = N.Float32
else:
print 'Not a bshort or bfloat file. Using packtype=',packtype
outdata = N.ravel(outarray).astype(packtype)
littleEndian = ( struct.pack('i',1)==struct.pack('<i',1) )
if littleEndian and os.uname()[0]<>'Linux':
outdata = outdata.byteswapped()
outdata = outdata.tostring()
outfile = open(fname,writetype)
outfile.write(outdata)
outfile.close()
if writeheader == 1:
try:
suffixindex = string.rfind(fname,'.')
hdrname = fname[0:suffixindex]
except ValueError:
hdrname = fname
if len(outarray.shape) == 2:
hdr = [outarray.shape[0],outarray.shape[1], 1, 0]
else:
hdr = [outarray.shape[1],outarray.shape[2],outarray.shape[0], 0,'\n']
print hdrname+'.hdr'
outfile = open(hdrname+'.hdr','w')
outfile.write(pstat.list2string(hdr))
outfile.close()
return None
def mrget(fname,datatype=N.Int16):
"""
Opens a binary .MR file and clips off the tail data portion of it, returning
the result as an array.
Usage: mrget(fname,datatype=N.Int16)
"""
d = braw(fname,datatype)
if len(d) > 512*512:
return N.reshape(d[-512*512:],(512,512))
elif len(d) > 256*256:
return N.reshape(d[-256*256:],(256,256))
elif len(d) > 128*128:
return N.reshape(d[-128*128:],(128,128))
elif len(d) > 64*64:
return N.reshape(d[-64*64:],(64,64))
else:
return N.reshape(d[-32*32:],(32,32))
def quickload(fname,linestocut=4):
"""
Quickly loads in a long text file, chopping off first n 'linestocut'.
Usage: quickload(fname,linestocut=4)
Returns: array filled with data in fname
"""
f = open(fname,'r')
d = f.readlines()
f.close()
print fname,'read in.'
d = d[linestocut:]
d = map(string.split,d)
print 'Done with string.split on lines.'
for i in range(len(d)):
d[i] = map(string.atoi,d[i])
print 'Conversion to ints done.'
return N.array(d)
def writedelimited (listoflists, delimiter, file, writetype='w'):
"""
Writes a list of lists in columns, separated by character(s) delimiter
to specified file. File-overwrite is the default.
Usage: writedelimited (listoflists,delimiter,filename,writetype='w')
Returns: None
"""
if type(listoflists[0]) not in [ListType,TupleType]:
listoflists = [listoflists]
outfile = open(file,writetype)
rowstokill = []
list2print = copy.deepcopy(listoflists)
for i in range(len(listoflists)):
if listoflists[i] == ['\n'] or listoflists[i]=='\n' or listoflists[i]=='dashes':
rowstokill = rowstokill + [i]
rowstokill.reverse()
for row in rowstokill:
del list2print[row]
maxsize = [0]*len(list2print[0])
for row in listoflists:
if row == ['\n'] or row == '\n':
outfile.write('\n')
elif row == ['dashes'] or row == 'dashes':
dashes = [0]*len(maxsize)
for j in range(len(maxsize)):
dashes[j] = '------'
outfile.write(pstat.linedelimited(dashes,delimiter))
else:
outfile.write(pstat.linedelimited(row,delimiter))
outfile.write('\n')
outfile.close()
return None
def writecc (listoflists,file,writetype='w',extra=2):
"""
Writes a list of lists to a file in columns, customized by the max
size of items within the columns (max size of items in col, +2 characters)
to specified file. File-overwrite is the default.
Usage: writecc (listoflists,file,writetype='w',extra=2)
Returns: None
"""
if type(listoflists[0]) not in [ListType,TupleType]:
listoflists = [listoflists]
outfile = open(file,writetype)
rowstokill = []
list2print = copy.deepcopy(listoflists)
for i in range(len(listoflists)):
if listoflists[i] == ['\n'] or listoflists[i]=='\n' or listoflists[i]=='dashes':
rowstokill = rowstokill + [i]
rowstokill.reverse()
for row in rowstokill:
del list2print[row]
maxsize = [0]*len(list2print[0])
for col in range(len(list2print[0])):
items = pstat.colex(list2print,col)
items = map(pstat.makestr,items)
maxsize[col] = max(map(len,items)) + extra
for row in listoflists:
if row == ['\n'] or row == '\n':
outfile.write('\n')
elif row == ['dashes'] or row == 'dashes':
dashes = [0]*len(maxsize)
for j in range(len(maxsize)):
dashes[j] = '-'*(maxsize[j]-2)
outfile.write(pstat.lineincustcols(dashes,maxsize))
else:
outfile.write(pstat.lineincustcols(row,maxsize))
outfile.write('\n')
outfile.close()
return None
def writefc (listoflists,colsize,file,writetype='w'):
"""
Writes a list of lists to a file in columns of fixed size. File-overwrite
is the default.
Usage: writefc (listoflists,colsize,file,writetype='w')
Returns: None
"""
if type(listoflists) == N.ArrayType:
listoflists = listoflists.tolist()
if type(listoflists[0]) not in [ListType,TupleType]:
listoflists = [listoflists]
outfile = open(file,writetype)
rowstokill = []
list2print = copy.deepcopy(listoflists)
for i in range(len(listoflists)):
if listoflists[i] == ['\n'] or listoflists[i]=='\n' or listoflists[i]=='dashes':
rowstokill = rowstokill + [i]
rowstokill.reverse()
for row in rowstokill:
del list2print[row]
n = [0]*len(list2print[0])
for row in listoflists:
if row == ['\n'] or row == '\n':
outfile.write('\n')
elif row == ['dashes'] or row == 'dashes':
dashes = [0]*colsize
for j in range(len(n)):
dashes[j] = '-'*(colsize)
outfile.write(pstat.lineincols(dashes,colsize))
else:
outfile.write(pstat.lineincols(row,colsize))
outfile.write('\n')
outfile.close()
return None
def load(fname,lines_to_ignore=4,type='i'):
"""
Load in huge, flat, 2D text files. Can handle differing line-lengths AND
can strip #/% on UNIX (or with a better NT grep). Requires wc, grep, and
mmapfile.lib/.pyd. Type can be 'i', 'f' or 'd', for ints, floats or doubles,
respectively. Lines_to_ignore determines how many lines at the start of the
file to ignore (required for non-working grep).
Usage: load(fname,lines_to_ignore=4,type='i')
Returns: numpy array of specified type
"""
start = time.time() ## START TIMER
if type == 'i':
intype = int
elif type in ['f','d']:
intype = float
else:
raise ValueError, "type can be 'i', 'f' or 'd' in load()"
## STRIP OUT % AND # LINES
tmpname = tempfile.mktemp()
if sys.platform == 'win32':
# NT VERSION OF GREP DOESN'T DO THE STRIPPING ... SIGH
cmd = "grep.exe -v \'%\' "+fname+" > "+tmpname
print cmd
os.system(cmd)
else:
# UNIX SIDE SHOULD WORK
cmd = "cat "+fname+" | grep -v \'%\' |grep -v \'#\' > "+tmpname
print cmd
os.system(cmd)
## GET NUMBER OF ROWS, COLUMNS AND LINE-LENGTH, USING WC
wc = string.split(os.popen("wc "+tmpname).read())
numlines = int(wc[0]) - lines_to_ignore
tfp = open(tmpname)
if lines_to_ignore <> 0:
for i in range(lines_to_ignore):
junk = tfp.readline()
numcols = len(string.split(tfp.readline())) #int(float(wc[1])/numlines)
tfp.close()
## PREPARE INPUT SPACE
a = N.zeros((numlines*numcols), type)
block = 65536 # chunk to read, in bytes
data = mmapfile.mmapfile(tmpname, '', 0)
if lines_to_ignore <> 0 and sys.platform == 'win32':
for i in range(lines_to_ignore):
junk = data.readline()
i = 0
d = ' '
carryover = ''
while len(d) <> 0:
d = carryover + data.read(block)
cutindex = string.rfind(d,'\n')
carryover = d[cutindex+1:]
d = d[:cutindex+1]
d = map(intype,string.split(d))
a[i:i+len(d)] = d
i = i + len(d)
end = time.time()
print "%d sec" % round(end-start,2)
data.close()
os.remove(tmpname)
return N.reshape(a,[numlines,numcols])
def find_dirs(sourcedir):
"""Finds and returns all directories in sourcedir
Usage: find_dirs(sourcedir)
Returns: list of directory names (potentially empty)
"""
files = os.listdir(sourcedir)
dirs = []
for fname in files:
if os.path.isdir(os.path.join(sourcedir,fname)):
dirs.append(fname)
return dirs
# ALIASES ...
save = aput
def binget(fname,btype=None):
"""
Loads a binary file from disk. Assumes associated hdr file is in same
location. You can force an unpacking type, or else it tries to figure
it out from the filename (4th-to-last character). Hence, readable file
formats are ...
1bin=Int8, sbin=Int16, ibin=Int32, fbin=Float32, dbin=Float64, etc.
Usage: binget(fname,btype=None)
Returns: data in file fname of type btype
"""
file = open(fname,'rb')
bdata = file.read()
file.close()
# if none given, assume character preceeding 'bin' is the unpacktype
if not btype:
btype = fname[-4]
try:
bdata = N.fromstring(bdata,btype)
except:
raise ValueError, "Bad unpacking type."
# force the data on disk to be LittleEndian (for more efficient PC/Linux use)
if not N.LittleEndian:
bdata = bdata.byteswapped()
try:
header = fname[:-3]+'hdr'
vals = get(header,0) # '0' means no missing-file warning msg
print vals
if type(vals[0]) == ListType: # it's an extended header
xsize = int(vals[0][0])
ysize = int(vals[0][1])
numslices = int(vals[0][2])
else:
bdata.shape = vals
except:
print "No (or bad) header file. Returning unshaped array."
return N.array(bdata)
def binput(outarray,fname,packtype=None,writetype='wb'):
"""
Unravels outarray and writes the data to a file, always in LittleEndian
format, along with a header file containing the original data shape. Default
is overwrite the destination file. Tries to figure out packtype from
4th-to-last character in filename. Thus, the routine understands these
file formats ...
1bin=Int8, sbin=Int16, ibin=Int32, fbin=Float32, dbin=Float64, etc.
Usage: binput(outarray,filename,packtype=None,writetype='wb')
"""
if not packtype:
packtype = fname[-4]
# a speck of error checking
if packtype == N.Int16 and outarray.typecode() == 'f':
# check to see if there's data loss
if max(N.ravel(outarray)) > 32767 or min(N.ravel(outarray))<-32768:
print "*** WARNING: CONVERTING FLOAT DATA TO OUT-OF RANGE INT16 DATA"
outdata = N.ravel(outarray).astype(packtype)
# force the data on disk to be LittleEndian (for more efficient PC/Linux use)
if not N.LittleEndian:
outdata = outdata.byteswapped()
outdata = outdata.tostring()
outfile = open(fname,writetype)
outfile.write(outdata)
outfile.close()
# Now, write the header file
try:
suffixindex = string.rfind(fname,'.')
hdrname = fname[0:suffixindex+2]+'hdr' # include .s or .f or .1 or whatever
except ValueError:
hdrname = fname
hdr = outarray.shape
print hdrname
outfile = open(hdrname,'w')
outfile.write(pstat.list2string(hdr))
outfile.close()
return None
def array2afni(d,brikprefix,voltype=None,TR=2.0,sliceorder='seqplus',geomparent=None,view=None):
"""
Converts an array 'd' to an AFNI BRIK/HEAD combo via putbin and to3d. Tries to
guess the AFNI volume type
voltype = {'-anat','-epan','-fim'}
geomparent = filename of the afni BRIK file with the same geometry
view = {'tlrc', 'acpc' or 'orig'}
Usage: array2afni(d,brikprefix,voltype=None,TR=2.0,
sliceorder='seqplus',geomparent=None,view=None)
Returns: None
"""
# converts Numeric typecode()s into appropriate strings for to3d command line
typecodemapping = {'c':'b', # character
'b':'b', # UnsignedInt8
'f':'f', # Float0, Float8, Float16, Float32
'd':'f', # Float64
'1':'b', # Int0, Int8
's':'', # Int16
'i':'i', # Int32
'l':'i'} # Int
# Verify that the data is proper size (3- or 4-D)
if len(d.shape) not in [3,4]:
raise ValueError, "A 3D or 4D array is required for array2afni() ... %s" %d.shape
# Save out the array to a binary file, homebrew style
if d.typecode() == N.Float64:
outcode = 'f'
else:
outcode = d.typecode()
tmpoutname = 'afnitmp.%sbin' % outcode
binput(d.astype(outcode),tmpoutname)
if not voltype:
if len(d.shape) == 3: # either anatomy or functional
if d.typecode() in ['s','i','l']: # if floats, assume functional
voltype = '-anat'
else:
voltype = '-fim'
else: # 4D dataset, must be anatomical timeseries (epan)
voltype = '-anat'
if len(d.shape) == 3: # either anatomy or functional
timepts = 1
slices = d.shape[0]
timestr = ''
elif len(d.shape) == 4:
timepts = d.shape[0]
slices = d.shape[1]
timestr = '-time:zt %d %d %0.3f %s ' % (slices,timepts,TR,sliceorder)
cmd = 'to3d %s -prefix %s -session . ' % (voltype, brikprefix)
if view:
cmd += '-view %s ' % view
if geomparent:
cmd += '-geomparent %s ' % geomparent
cmd += timestr
cmd += '3D%s:0:0:%d:%d:%d:%s' % (typecodemapping[d.typecode()],d.shape[-1],d.shape[-2],slices*timepts,tmpoutname)
print cmd
os.system(cmd)
os.remove(tmpoutname)
os.remove(tmpoutname[:-3]+'hdr')
| Python |
# $Id: __init__.py 1945 2006-03-05 01:06:37Z cpbotha $
# importing this module shouldn't directly cause other large imports
# do large imports in the init() hook so that you can call back to the
# ModuleManager progress handler methods.
"""stats_kit package driver file.
Inserts the following modules in sys.modules: stats.
@author: Charl P. Botha <http://cpbotha.net/>
"""
import sys
# you have to define this
VERSION = 'Strangman - May 10, 2002'
def init(theModuleManager, pre_import=True):
# import the main module itself
global stats
import stats
# if we don't do this, the module will be in sys.modules as
# module_kits.stats_kit.stats because it's not in the sys.path.
# iow. if a module is in sys.path, "import module" will put 'module' in
# sys.modules. if a module isn't, "import module" will put
# 'relative.path.to.module' in sys.path.
sys.modules['stats'] = stats
theModuleManager.setProgress(100, 'Initialising stats_kit: complete.')
def refresh():
reload(stats)
| Python |
# Copyright (c) 1999-2000 Gary Strangman; All Rights Reserved.
#
# This software is distributable under the terms of the GNU
# General Public License (GPL) v2, the text of which can be found at
# http://www.gnu.org/copyleft/gpl.html. Installing, importing or otherwise
# using this module constitutes acceptance of the terms of this License.
#
# Disclaimer
#
# This software is provided "as-is". There are no expressed or implied
# warranties of any kind, including, but not limited to, the warranties
# of merchantability and fittness for a given application. In no event
# shall Gary Strangman be liable for any direct, indirect, incidental,
# special, exemplary or consequential damages (including, but not limited
# to, loss of use, data or profits, or business interruption) however
# caused and on any theory of liability, whether in contract, strict
# liability or tort (including negligence or otherwise) arising in any way
# out of the use of this software, even if advised of the possibility of
# such damage.
#
# Comments and/or additions are welcome (send e-mail to:
# strang@nmr.mgh.harvard.edu).
#
"""
pstat.py module
#################################################
####### Written by: Gary Strangman ###########
####### Last modified: Jun 29, 2001 ###########
#################################################
This module provides some useful list and array manipulation routines
modeled after those found in the |Stat package by Gary Perlman, plus a
number of other useful list/file manipulation functions. The list-based
functions include:
abut (source,*args)
simpleabut (source, addon)
colex (listoflists,cnums)
collapse (listoflists,keepcols,collapsecols,fcn1=None,fcn2=None,cfcn=None)
dm (listoflists,criterion)
flat (l)
linexand (listoflists,columnlist,valuelist)
linexor (listoflists,columnlist,valuelist)
linedelimited (inlist,delimiter)
lineincols (inlist,colsize)
lineincustcols (inlist,colsizes)
list2string (inlist)
makelol(inlist)
makestr(x)
printcc (lst,extra=2)
printincols (listoflists,colsize)
pl (listoflists)
printl(listoflists)
replace (lst,oldval,newval)
recode (inlist,listmap,cols='all')
remap (listoflists,criterion)
roundlist (inlist,num_digits_to_round_floats_to)
sortby(listoflists,sortcols)
unique (inlist)
duplicates(inlist)
writedelimited (listoflists, delimiter, file, writetype='w')
Some of these functions have alternate versions which are defined only if
Numeric (NumPy) can be imported. These functions are generally named as
above, with an 'a' prefix.
aabut (source, *args)
acolex (a,indices,axis=1)
acollapse (a,keepcols,collapsecols,sterr=0,ns=0)
adm (a,criterion)
alinexand (a,columnlist,valuelist)
alinexor (a,columnlist,valuelist)
areplace (a,oldval,newval)
arecode (a,listmap,col='all')
arowcompare (row1, row2)
arowsame (row1, row2)
asortrows(a,axis=0)
aunique(inarray)
aduplicates(inarray)
Currently, the code is all but completely un-optimized. In many cases, the
array versions of functions amount simply to aliases to built-in array
functions/methods. Their inclusion here is for function name consistency.
"""
## CHANGE LOG:
## ==========
## 01-11-15 ... changed list2string() to accept a delimiter
## 01-06-29 ... converted exec()'s to eval()'s to make compatible with Py2.1
## 01-05-31 ... added duplicates() and aduplicates() functions
## 00-12-28 ... license made GPL, docstring and import requirements
## 99-11-01 ... changed version to 0.3
## 99-08-30 ... removed get, getstrings, put, aget, aput (into io.py)
## 03/27/99 ... added areplace function, made replace fcn recursive
## 12/31/98 ... added writefc function for ouput to fixed column sizes
## 12/07/98 ... fixed import problem (failed on collapse() fcn)
## added __version__ variable (now 0.2)
## 12/05/98 ... updated doc-strings
## added features to collapse() function
## added flat() function for lists
## fixed a broken asortrows()
## 11/16/98 ... fixed minor bug in aput for 1D arrays
##
## 11/08/98 ... fixed aput to output large arrays correctly
import stats # required 3rd party module
import string, copy
from types import *
__version__ = 0.4
###=========================== LIST FUNCTIONS ==========================
###
### Here are the list functions, DEFINED FOR ALL SYSTEMS.
### Array functions (for NumPy-enabled computers) appear below.
###
def abut (source,*args):
"""
Like the |Stat abut command. It concatenates two lists side-by-side
and returns the result. '2D' lists are also accomodated for either argument
(source or addon). CAUTION: If one list is shorter, it will be repeated
until it is as long as the longest list. If this behavior is not desired,
use pstat.simpleabut().
Usage: abut(source, args) where args=any # of lists
Returns: a list of lists as long as the LONGEST list past, source on the
'left', lists in <args> attached consecutively on the 'right'
"""
if type(source) not in [ListType,TupleType]:
source = [source]
for addon in args:
if type(addon) not in [ListType,TupleType]:
addon = [addon]
if len(addon) < len(source): # is source list longer?
if len(source) % len(addon) == 0: # are they integer multiples?
repeats = len(source)/len(addon) # repeat addon n times
origadd = copy.deepcopy(addon)
for i in range(repeats-1):
addon = addon + origadd
else:
repeats = len(source)/len(addon)+1 # repeat addon x times,
origadd = copy.deepcopy(addon) # x is NOT an integer
for i in range(repeats-1):
addon = addon + origadd
addon = addon[0:len(source)]
elif len(source) < len(addon): # is addon list longer?
if len(addon) % len(source) == 0: # are they integer multiples?
repeats = len(addon)/len(source) # repeat source n times
origsour = copy.deepcopy(source)
for i in range(repeats-1):
source = source + origsour
else:
repeats = len(addon)/len(source)+1 # repeat source x times,
origsour = copy.deepcopy(source) # x is NOT an integer
for i in range(repeats-1):
source = source + origsour
source = source[0:len(addon)]
source = simpleabut(source,addon)
return source
def simpleabut (source, addon):
"""
Concatenates two lists as columns and returns the result. '2D' lists
are also accomodated for either argument (source or addon). This DOES NOT
repeat either list to make the 2 lists of equal length. Beware of list pairs
with different lengths ... the resulting list will be the length of the
FIRST list passed.
Usage: simpleabut(source,addon) where source, addon=list (or list-of-lists)
Returns: a list of lists as long as source, with source on the 'left' and
addon on the 'right'
"""
if type(source) not in [ListType,TupleType]:
source = [source]
if type(addon) not in [ListType,TupleType]:
addon = [addon]
minlen = min(len(source),len(addon))
list = copy.deepcopy(source) # start abut process
if type(source[0]) not in [ListType,TupleType]:
if type(addon[0]) not in [ListType,TupleType]:
for i in range(minlen):
list[i] = [source[i]] + [addon[i]] # source/addon = column
else:
for i in range(minlen):
list[i] = [source[i]] + addon[i] # addon=list-of-lists
else:
if type(addon[0]) not in [ListType,TupleType]:
for i in range(minlen):
list[i] = source[i] + [addon[i]] # source=list-of-lists
else:
for i in range(minlen):
list[i] = source[i] + addon[i] # source/addon = list-of-lists
source = list
return source
def colex (listoflists,cnums):
"""
Extracts from listoflists the columns specified in the list 'cnums'
(cnums can be an integer, a sequence of integers, or a string-expression that
corresponds to a slice operation on the variable x ... e.g., 'x[3:]' will colex
columns 3 onward from the listoflists).
Usage: colex (listoflists,cnums)
Returns: a list-of-lists corresponding to the columns from listoflists
specified by cnums, in the order the column numbers appear in cnums
"""
global index
column = 0
if type(cnums) in [ListType,TupleType]: # if multiple columns to get
index = cnums[0]
column = map(lambda x: x[index], listoflists)
for col in cnums[1:]:
index = col
column = abut(column,map(lambda x: x[index], listoflists))
elif type(cnums) == StringType: # if an 'x[3:]' type expr.
evalstring = 'map(lambda x: x'+cnums+', listoflists)'
column = eval(evalstring)
else: # else it's just 1 col to get
index = cnums
column = map(lambda x: x[index], listoflists)
return column
def collapse (listoflists,keepcols,collapsecols,fcn1=None,fcn2=None,cfcn=None):
"""
Averages data in collapsecol, keeping all unique items in keepcols
(using unique, which keeps unique LISTS of column numbers), retaining the
unique sets of values in keepcols, the mean for each. Setting fcn1
and/or fcn2 to point to a function rather than None (e.g., stats.sterr, len)
will append those results (e.g., the sterr, N) after each calculated mean.
cfcn is the collapse function to apply (defaults to mean, defined here in the
pstat module to avoid circular imports with stats.py, but harmonicmean or
others could be passed).
Usage: collapse (listoflists,keepcols,collapsecols,fcn1=None,fcn2=None,cfcn=None)
Returns: a list of lists with all unique permutations of entries appearing in
columns ("conditions") specified by keepcols, abutted with the result of
cfcn (if cfcn=None, defaults to the mean) of each column specified by
collapsecols.
"""
def collmean (inlist):
s = 0
for item in inlist:
s = s + item
return s/float(len(inlist))
if type(keepcols) not in [ListType,TupleType]:
keepcols = [keepcols]
if type(collapsecols) not in [ListType,TupleType]:
collapsecols = [collapsecols]
if cfcn == None:
cfcn = collmean
if keepcols == []:
means = [0]*len(collapsecols)
for i in range(len(collapsecols)):
avgcol = colex(listoflists,collapsecols[i])
means[i] = cfcn(avgcol)
if fcn1:
try:
test = fcn1(avgcol)
except:
test = 'N/A'
means[i] = [means[i], test]
if fcn2:
try:
test = fcn2(avgcol)
except:
test = 'N/A'
try:
means[i] = means[i] + [len(avgcol)]
except TypeError:
means[i] = [means[i],len(avgcol)]
return means
else:
values = colex(listoflists,keepcols)
uniques = unique(values)
uniques.sort()
newlist = []
if type(keepcols) not in [ListType,TupleType]: keepcols = [keepcols]
for item in uniques:
if type(item) not in [ListType,TupleType]: item =[item]
tmprows = linexand(listoflists,keepcols,item)
for col in collapsecols:
avgcol = colex(tmprows,col)
item.append(cfcn(avgcol))
if fcn1 <> None:
try:
test = fcn1(avgcol)
except:
test = 'N/A'
item.append(test)
if fcn2 <> None:
try:
test = fcn2(avgcol)
except:
test = 'N/A'
item.append(test)
newlist.append(item)
return newlist
def dm (listoflists,criterion):
"""
Returns rows from the passed list of lists that meet the criteria in
the passed criterion expression (a string as a function of x; e.g., 'x[3]>=9'
will return all rows where the 4th column>=9 and "x[2]=='N'" will return rows
with column 2 equal to the string 'N').
Usage: dm (listoflists, criterion)
Returns: rows from listoflists that meet the specified criterion.
"""
function = 'filter(lambda x: '+criterion+',listoflists)'
lines = eval(function)
return lines
def flat(l):
"""
Returns the flattened version of a '2D' list. List-correlate to the a.flat()
method of NumPy arrays.
Usage: flat(l)
"""
newl = []
for i in range(len(l)):
for j in range(len(l[i])):
newl.append(l[i][j])
return newl
def linexand (listoflists,columnlist,valuelist):
"""
Returns the rows of a list of lists where col (from columnlist) = val
(from valuelist) for EVERY pair of values (columnlist[i],valuelists[i]).
len(columnlist) must equal len(valuelist).
Usage: linexand (listoflists,columnlist,valuelist)
Returns: the rows of listoflists where columnlist[i]=valuelist[i] for ALL i
"""
if type(columnlist) not in [ListType,TupleType]:
columnlist = [columnlist]
if type(valuelist) not in [ListType,TupleType]:
valuelist = [valuelist]
criterion = ''
for i in range(len(columnlist)):
if type(valuelist[i])==StringType:
critval = '\'' + valuelist[i] + '\''
else:
critval = str(valuelist[i])
criterion = criterion + ' x['+str(columnlist[i])+']=='+critval+' and'
criterion = criterion[0:-3] # remove the "and" after the last crit
function = 'filter(lambda x: '+criterion+',listoflists)'
lines = eval(function)
return lines
def linexor (listoflists,columnlist,valuelist):
"""
Returns the rows of a list of lists where col (from columnlist) = val
(from valuelist) for ANY pair of values (colunmlist[i],valuelist[i[).
One value is required for each column in columnlist. If only one value
exists for columnlist but multiple values appear in valuelist, the
valuelist values are all assumed to pertain to the same column.
Usage: linexor (listoflists,columnlist,valuelist)
Returns: the rows of listoflists where columnlist[i]=valuelist[i] for ANY i
"""
if type(columnlist) not in [ListType,TupleType]:
columnlist = [columnlist]
if type(valuelist) not in [ListType,TupleType]:
valuelist = [valuelist]
criterion = ''
if len(columnlist) == 1 and len(valuelist) > 1:
columnlist = columnlist*len(valuelist)
for i in range(len(columnlist)): # build an exec string
if type(valuelist[i])==StringType:
critval = '\'' + valuelist[i] + '\''
else:
critval = str(valuelist[i])
criterion = criterion + ' x['+str(columnlist[i])+']=='+critval+' or'
criterion = criterion[0:-2] # remove the "or" after the last crit
function = 'filter(lambda x: '+criterion+',listoflists)'
lines = eval(function)
return lines
def linedelimited (inlist,delimiter):
"""
Returns a string composed of elements in inlist, with each element
separated by 'delimiter.' Used by function writedelimited. Use '\t'
for tab-delimiting.
Usage: linedelimited (inlist,delimiter)
"""
outstr = ''
for item in inlist:
if type(item) <> StringType:
item = str(item)
outstr = outstr + item + delimiter
outstr = outstr[0:-1]
return outstr
def lineincols (inlist,colsize):
"""
Returns a string composed of elements in inlist, with each element
right-aligned in columns of (fixed) colsize.
Usage: lineincols (inlist,colsize) where colsize is an integer
"""
outstr = ''
for item in inlist:
if type(item) <> StringType:
item = str(item)
size = len(item)
if size <= colsize:
for i in range(colsize-size):
outstr = outstr + ' '
outstr = outstr + item
else:
outstr = outstr + item[0:colsize+1]
return outstr
def lineincustcols (inlist,colsizes):
"""
Returns a string composed of elements in inlist, with each element
right-aligned in a column of width specified by a sequence colsizes. The
length of colsizes must be greater than or equal to the number of columns
in inlist.
Usage: lineincustcols (inlist,colsizes)
Returns: formatted string created from inlist
"""
outstr = ''
for i in range(len(inlist)):
if type(inlist[i]) <> StringType:
item = str(inlist[i])
else:
item = inlist[i]
size = len(item)
if size <= colsizes[i]:
for j in range(colsizes[i]-size):
outstr = outstr + ' '
outstr = outstr + item
else:
outstr = outstr + item[0:colsizes[i]+1]
return outstr
def list2string (inlist,delimit=' '):
"""
Converts a 1D list to a single long string for file output, using
the string.join function.
Usage: list2string (inlist,delimit=' ')
Returns: the string created from inlist
"""
stringlist = map(makestr,inlist)
return string.join(stringlist,delimit)
def makelol(inlist):
"""
Converts a 1D list to a 2D list (i.e., a list-of-lists). Useful when you
want to use put() to write a 1D list one item per line in the file.
Usage: makelol(inlist)
Returns: if l = [1,2,'hi'] then returns [[1],[2],['hi']] etc.
"""
x = []
for item in inlist:
x.append([item])
return x
def makestr (x):
if type(x) <> StringType:
x = str(x)
return x
def printcc (lst,extra=2):
"""
Prints a list of lists in columns, customized by the max size of items
within the columns (max size of items in col, plus 'extra' number of spaces).
Use 'dashes' or '\\n' in the list-of-lists to print dashes or blank lines,
respectively.
Usage: printcc (lst,extra=2)
Returns: None
"""
if type(lst[0]) not in [ListType,TupleType]:
lst = [lst]
rowstokill = []
list2print = copy.deepcopy(lst)
for i in range(len(lst)):
if lst[i] == ['\n'] or lst[i]=='\n' or lst[i]=='dashes' or lst[i]=='' or lst[i]==['']:
rowstokill = rowstokill + [i]
rowstokill.reverse() # delete blank rows from the end
for row in rowstokill:
del list2print[row]
maxsize = [0]*len(list2print[0])
for col in range(len(list2print[0])):
items = colex(list2print,col)
items = map(makestr,items)
maxsize[col] = max(map(len,items)) + extra
for row in lst:
if row == ['\n'] or row == '\n' or row == '' or row == ['']:
print
elif row == ['dashes'] or row == 'dashes':
dashes = [0]*len(maxsize)
for j in range(len(maxsize)):
dashes[j] = '-'*(maxsize[j]-2)
print lineincustcols(dashes,maxsize)
else:
print lineincustcols(row,maxsize)
return None
def printincols (listoflists,colsize):
"""
Prints a list of lists in columns of (fixed) colsize width, where
colsize is an integer.
Usage: printincols (listoflists,colsize)
Returns: None
"""
for row in listoflists:
print lineincols(row,colsize)
return None
def pl (listoflists):
"""
Prints a list of lists, 1 list (row) at a time.
Usage: pl(listoflists)
Returns: None
"""
for row in listoflists:
if row[-1] == '\n':
print row,
else:
print row
return None
def printl(listoflists):
"""Alias for pl."""
pl(listoflists)
return
def replace (inlst,oldval,newval):
"""
Replaces all occurrences of 'oldval' with 'newval', recursively.
Usage: replace (inlst,oldval,newval)
"""
lst = inlst*1
for i in range(len(lst)):
if type(lst[i]) not in [ListType,TupleType]:
if lst[i]==oldval: lst[i]=newval
else:
lst[i] = replace(lst[i],oldval,newval)
return lst
def recode (inlist,listmap,cols=None):
"""
Changes the values in a list to a new set of values (useful when
you need to recode data from (e.g.) strings to numbers. cols defaults
to None (meaning all columns are recoded).
Usage: recode (inlist,listmap,cols=None) cols=recode cols, listmap=2D list
Returns: inlist with the appropriate values replaced with new ones
"""
lst = copy.deepcopy(inlist)
if cols != None:
if type(cols) not in [ListType,TupleType]:
cols = [cols]
for col in cols:
for row in range(len(lst)):
try:
idx = colex(listmap,0).index(lst[row][col])
lst[row][col] = listmap[idx][1]
except ValueError:
pass
else:
for row in range(len(lst)):
for col in range(len(lst)):
try:
idx = colex(listmap,0).index(lst[row][col])
lst[row][col] = listmap[idx][1]
except ValueError:
pass
return lst
def remap (listoflists,criterion):
"""
Remaps values in a given column of a 2D list (listoflists). This requires
a criterion as a function of 'x' so that the result of the following is
returned ... map(lambda x: 'criterion',listoflists).
Usage: remap(listoflists,criterion) criterion=string
Returns: remapped version of listoflists
"""
function = 'map(lambda x: '+criterion+',listoflists)'
lines = eval(function)
return lines
def roundlist (inlist,digits):
"""
Goes through each element in a 1D or 2D inlist, and applies the following
function to all elements of FloatType ... round(element,digits).
Usage: roundlist(inlist,digits)
Returns: list with rounded floats
"""
if type(inlist[0]) in [IntType, FloatType]:
inlist = [inlist]
l = inlist*1
for i in range(len(l)):
for j in range(len(l[i])):
if type(l[i][j])==FloatType:
l[i][j] = round(l[i][j],digits)
return l
def sortby(listoflists,sortcols):
"""
Sorts a list of lists on the column(s) specified in the sequence
sortcols.
Usage: sortby(listoflists,sortcols)
Returns: sorted list, unchanged column ordering
"""
newlist = abut(colex(listoflists,sortcols),listoflists)
newlist.sort()
try:
numcols = len(sortcols)
except TypeError:
numcols = 1
crit = '[' + str(numcols) + ':]'
newlist = colex(newlist,crit)
return newlist
def unique (inlist):
"""
Returns all unique items in the passed list. If the a list-of-lists
is passed, unique LISTS are found (i.e., items in the first dimension are
compared).
Usage: unique (inlist)
Returns: the unique elements (or rows) in inlist
"""
uniques = []
for item in inlist:
if item not in uniques:
uniques.append(item)
return uniques
def duplicates(inlist):
"""
Returns duplicate items in the FIRST dimension of the passed list.
Usage: duplicates (inlist)
"""
dups = []
for i in range(len(inlist)):
if inlist[i] in inlist[i+1:]:
dups.append(inlist[i])
return dups
def nonrepeats(inlist):
"""
Returns items that are NOT duplicated in the first dim of the passed list.
Usage: nonrepeats (inlist)
"""
nonrepeats = []
for i in range(len(inlist)):
if inlist.count(inlist[i]) == 1:
nonrepeats.append(inlist[i])
return nonrepeats
#=================== PSTAT ARRAY FUNCTIONS =====================
#=================== PSTAT ARRAY FUNCTIONS =====================
#=================== PSTAT ARRAY FUNCTIONS =====================
#=================== PSTAT ARRAY FUNCTIONS =====================
#=================== PSTAT ARRAY FUNCTIONS =====================
#=================== PSTAT ARRAY FUNCTIONS =====================
#=================== PSTAT ARRAY FUNCTIONS =====================
#=================== PSTAT ARRAY FUNCTIONS =====================
#=================== PSTAT ARRAY FUNCTIONS =====================
#=================== PSTAT ARRAY FUNCTIONS =====================
#=================== PSTAT ARRAY FUNCTIONS =====================
#=================== PSTAT ARRAY FUNCTIONS =====================
#=================== PSTAT ARRAY FUNCTIONS =====================
#=================== PSTAT ARRAY FUNCTIONS =====================
#=================== PSTAT ARRAY FUNCTIONS =====================
#=================== PSTAT ARRAY FUNCTIONS =====================
try: # DEFINE THESE *ONLY* IF NUMERIC IS AVAILABLE
import Numeric
N = Numeric
def aabut (source, *args):
"""
Like the |Stat abut command. It concatenates two arrays column-wise
and returns the result. CAUTION: If one array is shorter, it will be
repeated until it is as long as the other.
Usage: aabut (source, args) where args=any # of arrays
Returns: an array as long as the LONGEST array past, source appearing on the
'left', arrays in <args> attached on the 'right'.
"""
if len(source.shape)==1:
width = 1
source = N.resize(source,[source.shape[0],width])
else:
width = source.shape[1]
for addon in args:
if len(addon.shape)==1:
width = 1
addon = N.resize(addon,[source.shape[0],width])
else:
width = source.shape[1]
if len(addon) < len(source):
addon = N.resize(addon,[source.shape[0],addon.shape[1]])
elif len(source) < len(addon):
source = N.resize(source,[addon.shape[0],source.shape[1]])
source = N.concatenate((source,addon),1)
return source
def acolex (a,indices,axis=1):
"""
Extracts specified indices (a list) from passed array, along passed
axis (column extraction is default). BEWARE: A 1D array is presumed to be a
column-array (and that the whole array will be returned as a column).
Usage: acolex (a,indices,axis=1)
Returns: the columns of a specified by indices
"""
if type(indices) not in [ListType,TupleType,N.ArrayType]:
indices = [indices]
if len(N.shape(a)) == 1:
cols = N.resize(a,[a.shape[0],1])
else:
cols = N.take(a,indices,axis)
return cols
def acollapse (a,keepcols,collapsecols,fcn1=None,fcn2=None,cfcn=None):
"""
Averages data in collapsecol, keeping all unique items in keepcols
(using unique, which keeps unique LISTS of column numbers), retaining
the unique sets of values in keepcols, the mean for each. If stderror or
N of the mean are desired, set either or both parameters to 1.
Usage: acollapse (a,keepcols,collapsecols,fcn1=None,fcn2=None,cfcn=None)
Returns: unique 'conditions' specified by the contents of columns specified
by keepcols, abutted with the mean(s) of column(s) specified by
collapsecols
"""
def acollmean (inarray):
return N.sum(N.ravel(inarray))
if cfcn == None:
cfcn = acollmean
if keepcols == []:
avgcol = acolex(a,collapsecols)
means = N.sum(avgcol)/float(len(avgcol))
if fcn1<>None:
try:
test = fcn1(avgcol)
except:
test = N.array(['N/A']*len(means))
means = aabut(means,test)
if fcn2<>None:
try:
test = fcn2(avgcol)
except:
test = N.array(['N/A']*len(means))
means = aabut(means,test)
return means
else:
if type(keepcols) not in [ListType,TupleType,N.ArrayType]:
keepcols = [keepcols]
values = colex(a,keepcols) # so that "item" can be appended (below)
uniques = unique(values) # get a LIST, so .sort keeps rows intact
uniques.sort()
newlist = []
for item in uniques:
if type(item) not in [ListType,TupleType,N.ArrayType]:
item =[item]
tmprows = alinexand(a,keepcols,item)
for col in collapsecols:
avgcol = acolex(tmprows,col)
item.append(acollmean(avgcol))
if fcn1<>None:
try:
test = fcn1(avgcol)
except:
test = 'N/A'
item.append(test)
if fcn2<>None:
try:
test = fcn2(avgcol)
except:
test = 'N/A'
item.append(test)
newlist.append(item)
try:
new_a = N.array(newlist)
except TypeError:
new_a = N.array(newlist,'O')
return new_a
def adm (a,criterion):
"""
Returns rows from the passed list of lists that meet the criteria in
the passed criterion expression (a string as a function of x).
Usage: adm (a,criterion) where criterion is like 'x[2]==37'
"""
function = 'filter(lambda x: '+criterion+',a)'
lines = eval(function)
try:
lines = N.array(lines)
except:
lines = N.array(lines,'O')
return lines
def isstring(x):
if type(x)==StringType:
return 1
else:
return 0
def alinexand (a,columnlist,valuelist):
"""
Returns the rows of an array where col (from columnlist) = val
(from valuelist). One value is required for each column in columnlist.
Usage: alinexand (a,columnlist,valuelist)
Returns: the rows of a where columnlist[i]=valuelist[i] for ALL i
"""
if type(columnlist) not in [ListType,TupleType,N.ArrayType]:
columnlist = [columnlist]
if type(valuelist) not in [ListType,TupleType,N.ArrayType]:
valuelist = [valuelist]
criterion = ''
for i in range(len(columnlist)):
if type(valuelist[i])==StringType:
critval = '\'' + valuelist[i] + '\''
else:
critval = str(valuelist[i])
criterion = criterion + ' x['+str(columnlist[i])+']=='+critval+' and'
criterion = criterion[0:-3] # remove the "and" after the last crit
return adm(a,criterion)
def alinexor (a,columnlist,valuelist):
"""
Returns the rows of an array where col (from columnlist) = val (from
valuelist). One value is required for each column in columnlist.
The exception is if either columnlist or valuelist has only 1 value,
in which case that item will be expanded to match the length of the
other list.
Usage: alinexor (a,columnlist,valuelist)
Returns: the rows of a where columnlist[i]=valuelist[i] for ANY i
"""
if type(columnlist) not in [ListType,TupleType,N.ArrayType]:
columnlist = [columnlist]
if type(valuelist) not in [ListType,TupleType,N.ArrayType]:
valuelist = [valuelist]
criterion = ''
if len(columnlist) == 1 and len(valuelist) > 1:
columnlist = columnlist*len(valuelist)
elif len(valuelist) == 1 and len(columnlist) > 1:
valuelist = valuelist*len(columnlist)
for i in range(len(columnlist)):
if type(valuelist[i])==StringType:
critval = '\'' + valuelist[i] + '\''
else:
critval = str(valuelist[i])
criterion = criterion + ' x['+str(columnlist[i])+']=='+critval+' or'
criterion = criterion[0:-2] # remove the "or" after the last crit
return adm(a,criterion)
def areplace (a,oldval,newval):
"""
Replaces all occurrences of oldval with newval in array a.
Usage: areplace(a,oldval,newval)
"""
newa = N.not_equal(a,oldval)*a
return newa+N.equal(a,oldval)*newval
def arecode (a,listmap,col='all'):
"""
Remaps the values in an array to a new set of values (useful when
you need to recode data from (e.g.) strings to numbers as most stats
packages require. Can work on SINGLE columns, or 'all' columns at once.
Usage: arecode (a,listmap,col='all')
Returns: a version of array a where listmap[i][0] = (instead) listmap[i][1]
"""
ashape = a.shape
if col == 'all':
work = a.flat
else:
work = acolex(a,col)
work = work.flat
for pair in listmap:
if type(pair[1]) == StringType or work.typecode()=='O' or a.typecode()=='O':
work = N.array(work,'O')
a = N.array(a,'O')
for i in range(len(work)):
if work[i]==pair[0]:
work[i] = pair[1]
if col == 'all':
return N.reshape(work,ashape)
else:
return N.concatenate([a[:,0:col],work[:,N.NewAxis],a[:,col+1:]],1)
else: # must be a non-Object type array and replacement
work = N.where(N.equal(work,pair[0]),pair[1],work)
return N.concatenate([a[:,0:col],work[:,N.NewAxis],a[:,col+1:]],1)
def arowcompare(row1, row2):
"""
Compares two rows from an array, regardless of whether it is an
array of numbers or of python objects (which requires the cmp function).
Usage: arowcompare(row1,row2)
Returns: an array of equal length containing 1s where the two rows had
identical elements and 0 otherwise
"""
if row1.typecode()=='O' or row2.typecode=='O':
cmpvect = N.logical_not(abs(N.array(map(cmp,row1,row2)))) # cmp fcn gives -1,0,1
else:
cmpvect = N.equal(row1,row2)
return cmpvect
def arowsame(row1, row2):
"""
Compares two rows from an array, regardless of whether it is an
array of numbers or of python objects (which requires the cmp function).
Usage: arowsame(row1,row2)
Returns: 1 if the two rows are identical, 0 otherwise.
"""
cmpval = N.alltrue(arowcompare(row1,row2))
return cmpval
def asortrows(a,axis=0):
"""
Sorts an array "by rows". This differs from the Numeric.sort() function,
which sorts elements WITHIN the given axis. Instead, this function keeps
the elements along the given axis intact, but shifts them 'up or down'
relative to one another.
Usage: asortrows(a,axis=0)
Returns: sorted version of a
"""
if axis != 0:
a = N.swapaxes(a, axis, 0)
l = a.tolist()
l.sort() # or l.sort(_sort)
y = N.array(l)
if axis != 0:
y = N.swapaxes(y, axis, 0)
return y
def aunique(inarray):
"""
Returns unique items in the FIRST dimension of the passed array. Only
works on arrays NOT including string items.
Usage: aunique (inarray)
"""
uniques = N.array([inarray[0]])
if len(uniques.shape) == 1: # IF IT'S A 1D ARRAY
for item in inarray[1:]:
if N.add.reduce(N.equal(uniques,item).flat) == 0:
try:
uniques = N.concatenate([uniques,N.array[N.NewAxis,:]])
except TypeError:
uniques = N.concatenate([uniques,N.array([item])])
else: # IT MUST BE A 2+D ARRAY
if inarray.typecode() != 'O': # not an Object array
for item in inarray[1:]:
if not N.sum(N.alltrue(N.equal(uniques,item),1)):
try:
uniques = N.concatenate( [uniques,item[N.NewAxis,:]] )
except TypeError: # the item to add isn't a list
uniques = N.concatenate([uniques,N.array([item])])
else:
pass # this item is already in the uniques array
else: # must be an Object array, alltrue/equal functions don't work
for item in inarray[1:]:
newflag = 1
for unq in uniques: # NOTE: cmp --> 0=same, -1=<, 1=>
test = N.sum(abs(N.array(map(cmp,item,unq))))
if test == 0: # if item identical to any 1 row in uniques
newflag = 0 # then not a novel item to add
break
if newflag == 1:
try:
uniques = N.concatenate( [uniques,item[N.NewAxis,:]] )
except TypeError: # the item to add isn't a list
uniques = N.concatenate([uniques,N.array([item])])
return uniques
def aduplicates(inarray):
"""
Returns duplicate items in the FIRST dimension of the passed array. Only
works on arrays NOT including string items.
Usage: aunique (inarray)
"""
inarray = N.array(inarray)
if len(inarray.shape) == 1: # IF IT'S A 1D ARRAY
dups = []
inarray = inarray.tolist()
for i in range(len(inarray)):
if inarray[i] in inarray[i+1:]:
dups.append(inarray[i])
dups = aunique(dups)
else: # IT MUST BE A 2+D ARRAY
dups = []
aslist = inarray.tolist()
for i in range(len(aslist)):
if aslist[i] in aslist[i+1:]:
dups.append(aslist[i])
dups = unique(dups)
dups = N.array(dups)
return dups
except ImportError: # IF NUMERIC ISN'T AVAILABLE, SKIP ALL arrayfuncs
pass
| Python |
# $Id: __init__.py 1945 2006-03-05 01:06:37Z cpbotha $
# importing this module shouldn't directly cause other large imports
# do large imports in the init() hook so that you can call back to the
# ModuleManager progress handler methods.
"""matplotlib_kit package driver file.
Inserts the following modules in sys.modules: matplotlib, pylab.
@author: Charl P. Botha <http://cpbotha.net/>
"""
import os
import re
import sys
import types
# you have to define this
VERSION = ''
def init(theModuleManager, pre_import=True):
if hasattr(sys, 'frozen') and sys.frozen:
# matplotlib supports py2exe by checking for matplotlibdata in the appdir
# but this is only done on windows (and therefore works for our windows
# installer builds). On non-windows, we have to stick it in the env
# to make sure that MPL finds its datadir (only if we're frozen)
mpldir = os.path.join(theModuleManager.get_appdir(), 'matplotlibdata')
os.environ['MATPLOTLIBDATA'] = mpldir
# import the main module itself
# this doesn't import numerix yet...
global matplotlib
import matplotlib
# use WX + Agg backend (slower, but nicer that WX)
matplotlib.use('WXAgg')
# interactive mode: user can use pylab commands from any introspection
# interface, changes will be made immediately and matplotlib cooperates
# nicely with main WX event loop
matplotlib.interactive(True)
# with matplotlib 1.0.1 we can't do this anymore.
# makes sure we use the numpy backend
#from matplotlib import rcParams
#rcParams['numerix'] = 'numpy'
theModuleManager.setProgress(25, 'Initialising matplotlib_kit: config')
# @PATCH:
# this is for the combination numpy 1.0.4 and matplotlib 0.91.2
# matplotlib/numerix/ma/__init__.py:
# . normal installation fails on "from numpy.ma import *", so "from
# numpy.core.ma import *" is done, thus bringing in e.g. getmask
# . pyinstaller binaries for some or other reason succeed on
# "from numpy.ma import *" (no exception raised), therefore do
# not do "from numpy.core.ma import *", and therefore things like
# getmask are not imported.
# solution:
# we make sure that "from numpy.ma import *" actually brings in
# numpy.core.ma by importing that and associating the module
# binding to the global numpy.ma.
#if hasattr(sys, 'frozen') and sys.frozen:
# import numpy.core.ma
# sys.modules['numpy.ma'] = sys.modules['numpy.core.ma']
# import the pylab interface, make sure it's available from this namespace
global pylab
import pylab
theModuleManager.setProgress(90, 'Initialising matplotlib_kit: pylab')
# build up VERSION
global VERSION
VERSION = '%s' % (matplotlib.__version__,)
theModuleManager.setProgress(100, 'Initialising matplotlib_kit: complete')
| Python |
# perceptually linear colour scales based on those published by Haim
# Levkowitz at http://www.cs.uml.edu/~haim/ColorCenter/
# code by Peter R. Krekel (c) 2009
# modified by Charl Botha to cache lookuptable per range
import vtk
class ColorScales():
def __init__(self):
self.BlueToYellow = {}
self.Linear_Heat = {}
self.Linear_BlackToWhite = {}
self.Linear_BlueToYellow = {}
def LUT_BlueToYellow(self, LUrange):
key = tuple(LUrange)
try:
return self.BlueToYellow[key]
except KeyError:
pass
differencetable = vtk.vtkLookupTable()
differencetable.SetNumberOfColors(50)
differencetable.SetRange(LUrange[0], LUrange[1])
i=0.0
while i<50:
differencetable.SetTableValue( int(i), (i/50.0, i/50.0, 1-(i/50.0) ,1.0))
i=i+1
differencetable.Build()
self.BlueToYellow[key] = differencetable
return self.BlueToYellow[key]
def LUT_Linear_Heat(self, LUrange):
key = tuple(LUrange)
try:
return self.Linear_Heat[key]
except KeyError:
pass
L1table = vtk.vtkLookupTable()
L1table.SetRange(LUrange[0], LUrange[1])
L1table.SetNumberOfColors(256)
L1table.SetTableValue( 0 , ( 0.000 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 1 , ( 0.000 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 2 , ( 0.000 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 3 , ( 0.004 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 4 , ( 0.008 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 5 , ( 0.008 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 6 , ( 0.012 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 7 , ( 0.012 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 8 , ( 0.016 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 9 , ( 0.020 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 10 , ( 0.020 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 11 , ( 0.024 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 12 , ( 0.027 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 13 , ( 0.027 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 14 , ( 0.031 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 15 , ( 0.035 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 16 , ( 0.035 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 17 , ( 0.039 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 18 , ( 0.043 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 19 , ( 0.047 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 20 , ( 0.051 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 21 , ( 0.055 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 22 , ( 0.059 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 23 , ( 0.063 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 24 , ( 0.067 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 25 , ( 0.071 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 26 , ( 0.075 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 27 , ( 0.078 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 28 , ( 0.082 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 29 , ( 0.086 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 30 , ( 0.090 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 31 , ( 0.098 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 32 , ( 0.102 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 33 , ( 0.106 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 34 , ( 0.110 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 35 , ( 0.118 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 36 , ( 0.122 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 37 , ( 0.129 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 38 , ( 0.133 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 39 , ( 0.137 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 40 , ( 0.145 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 41 , ( 0.153 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 42 , ( 0.157 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 43 , ( 0.169 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 44 , ( 0.176 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 45 , ( 0.180 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 46 , ( 0.192 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 47 , ( 0.200 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 48 , ( 0.208 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 49 , ( 0.212 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 50 , ( 0.220 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 51 , ( 0.227 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 52 , ( 0.235 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 53 , ( 0.243 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 54 , ( 0.251 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 55 , ( 0.263 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 56 , ( 0.271 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 57 , ( 0.278 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 58 , ( 0.290 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 59 , ( 0.298 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 60 , ( 0.314 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 61 , ( 0.318 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 62 , ( 0.329 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 63 , ( 0.337 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 64 , ( 0.349 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 65 , ( 0.361 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 66 , ( 0.369 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 67 , ( 0.380 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 68 , ( 0.392 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 69 , ( 0.404 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 70 , ( 0.416 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 71 , ( 0.427 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 72 , ( 0.439 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 73 , ( 0.451 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 74 , ( 0.459 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 75 , ( 0.478 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 76 , ( 0.494 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 77 , ( 0.502 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 78 , ( 0.514 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 79 , ( 0.529 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 80 , ( 0.529 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 81 , ( 0.529 , 0.004 , 0.000 ,1.0))
L1table.SetTableValue( 82 , ( 0.529 , 0.008 , 0.000 ,1.0))
L1table.SetTableValue( 83 , ( 0.529 , 0.012 , 0.000 ,1.0))
L1table.SetTableValue( 84 , ( 0.529 , 0.016 , 0.000 ,1.0))
L1table.SetTableValue( 85 , ( 0.529 , 0.024 , 0.000 ,1.0))
L1table.SetTableValue( 86 , ( 0.529 , 0.024 , 0.000 ,1.0))
L1table.SetTableValue( 87 , ( 0.529 , 0.031 , 0.000 ,1.0))
L1table.SetTableValue( 88 , ( 0.529 , 0.035 , 0.000 ,1.0))
L1table.SetTableValue( 89 , ( 0.529 , 0.039 , 0.000 ,1.0))
L1table.SetTableValue( 90 , ( 0.529 , 0.043 , 0.000 ,1.0))
L1table.SetTableValue( 91 , ( 0.529 , 0.051 , 0.000 ,1.0))
L1table.SetTableValue( 92 , ( 0.529 , 0.051 , 0.000 ,1.0))
L1table.SetTableValue( 93 , ( 0.529 , 0.059 , 0.000 ,1.0))
L1table.SetTableValue( 94 , ( 0.529 , 0.067 , 0.000 ,1.0))
L1table.SetTableValue( 95 , ( 0.529 , 0.067 , 0.000 ,1.0))
L1table.SetTableValue( 96 , ( 0.529 , 0.075 , 0.000 ,1.0))
L1table.SetTableValue( 97 , ( 0.529 , 0.082 , 0.000 ,1.0))
L1table.SetTableValue( 98 , ( 0.529 , 0.086 , 0.000 ,1.0))
L1table.SetTableValue( 99 , ( 0.529 , 0.090 , 0.000 ,1.0))
L1table.SetTableValue( 100 , ( 0.529 , 0.098 , 0.000 ,1.0))
L1table.SetTableValue( 101 , ( 0.529 , 0.102 , 0.000 ,1.0))
L1table.SetTableValue( 102 , ( 0.529 , 0.106 , 0.000 ,1.0))
L1table.SetTableValue( 103 , ( 0.529 , 0.114 , 0.000 ,1.0))
L1table.SetTableValue( 104 , ( 0.529 , 0.122 , 0.000 ,1.0))
L1table.SetTableValue( 105 , ( 0.529 , 0.125 , 0.000 ,1.0))
L1table.SetTableValue( 106 , ( 0.529 , 0.129 , 0.000 ,1.0))
L1table.SetTableValue( 107 , ( 0.529 , 0.137 , 0.000 ,1.0))
L1table.SetTableValue( 108 , ( 0.529 , 0.141 , 0.000 ,1.0))
L1table.SetTableValue( 109 , ( 0.529 , 0.149 , 0.000 ,1.0))
L1table.SetTableValue( 110 , ( 0.529 , 0.157 , 0.000 ,1.0))
L1table.SetTableValue( 111 , ( 0.529 , 0.165 , 0.000 ,1.0))
L1table.SetTableValue( 112 , ( 0.529 , 0.173 , 0.000 ,1.0))
L1table.SetTableValue( 113 , ( 0.529 , 0.180 , 0.000 ,1.0))
L1table.SetTableValue( 114 , ( 0.529 , 0.184 , 0.000 ,1.0))
L1table.SetTableValue( 115 , ( 0.529 , 0.192 , 0.000 ,1.0))
L1table.SetTableValue( 116 , ( 0.529 , 0.200 , 0.000 ,1.0))
L1table.SetTableValue( 117 , ( 0.529 , 0.204 , 0.000 ,1.0))
L1table.SetTableValue( 118 , ( 0.529 , 0.212 , 0.000 ,1.0))
L1table.SetTableValue( 119 , ( 0.529 , 0.220 , 0.000 ,1.0))
L1table.SetTableValue( 120 , ( 0.529 , 0.224 , 0.000 ,1.0))
L1table.SetTableValue( 121 , ( 0.529 , 0.231 , 0.000 ,1.0))
L1table.SetTableValue( 122 , ( 0.529 , 0.243 , 0.000 ,1.0))
L1table.SetTableValue( 123 , ( 0.529 , 0.247 , 0.000 ,1.0))
L1table.SetTableValue( 124 , ( 0.529 , 0.255 , 0.000 ,1.0))
L1table.SetTableValue( 125 , ( 0.529 , 0.263 , 0.000 ,1.0))
L1table.SetTableValue( 126 , ( 0.529 , 0.271 , 0.000 ,1.0))
L1table.SetTableValue( 127 , ( 0.529 , 0.282 , 0.000 ,1.0))
L1table.SetTableValue( 128 , ( 0.529 , 0.286 , 0.000 ,1.0))
L1table.SetTableValue( 129 , ( 0.529 , 0.298 , 0.000 ,1.0))
L1table.SetTableValue( 130 , ( 0.529 , 0.306 , 0.000 ,1.0))
L1table.SetTableValue( 131 , ( 0.529 , 0.314 , 0.000 ,1.0))
L1table.SetTableValue( 132 , ( 0.529 , 0.322 , 0.000 ,1.0))
L1table.SetTableValue( 133 , ( 0.529 , 0.329 , 0.000 ,1.0))
L1table.SetTableValue( 134 , ( 0.529 , 0.341 , 0.000 ,1.0))
L1table.SetTableValue( 135 , ( 0.529 , 0.345 , 0.000 ,1.0))
L1table.SetTableValue( 136 , ( 0.529 , 0.353 , 0.000 ,1.0))
L1table.SetTableValue( 137 , ( 0.529 , 0.365 , 0.000 ,1.0))
L1table.SetTableValue( 138 , ( 0.529 , 0.373 , 0.000 ,1.0))
L1table.SetTableValue( 139 , ( 0.529 , 0.384 , 0.000 ,1.0))
L1table.SetTableValue( 140 , ( 0.529 , 0.396 , 0.000 ,1.0))
L1table.SetTableValue( 141 , ( 0.529 , 0.404 , 0.000 ,1.0))
L1table.SetTableValue( 142 , ( 0.529 , 0.416 , 0.000 ,1.0))
L1table.SetTableValue( 143 , ( 0.529 , 0.420 , 0.000 ,1.0))
L1table.SetTableValue( 144 , ( 0.529 , 0.431 , 0.000 ,1.0))
L1table.SetTableValue( 145 , ( 0.529 , 0.443 , 0.000 ,1.0))
L1table.SetTableValue( 146 , ( 0.529 , 0.451 , 0.000 ,1.0))
L1table.SetTableValue( 147 , ( 0.529 , 0.463 , 0.000 ,1.0))
L1table.SetTableValue( 148 , ( 0.529 , 0.475 , 0.000 ,1.0))
L1table.SetTableValue( 149 , ( 0.529 , 0.486 , 0.000 ,1.0))
L1table.SetTableValue( 150 , ( 0.529 , 0.498 , 0.000 ,1.0))
L1table.SetTableValue( 151 , ( 0.529 , 0.506 , 0.000 ,1.0))
L1table.SetTableValue( 152 , ( 0.529 , 0.522 , 0.000 ,1.0))
L1table.SetTableValue( 153 , ( 0.529 , 0.529 , 0.000 ,1.0))
L1table.SetTableValue( 154 , ( 0.529 , 0.541 , 0.000 ,1.0))
L1table.SetTableValue( 155 , ( 0.529 , 0.553 , 0.000 ,1.0))
L1table.SetTableValue( 156 , ( 0.529 , 0.565 , 0.000 ,1.0))
L1table.SetTableValue( 157 , ( 0.529 , 0.580 , 0.000 ,1.0))
L1table.SetTableValue( 158 , ( 0.529 , 0.588 , 0.000 ,1.0))
L1table.SetTableValue( 159 , ( 0.529 , 0.608 , 0.000 ,1.0))
L1table.SetTableValue( 160 , ( 0.529 , 0.616 , 0.000 ,1.0))
L1table.SetTableValue( 161 , ( 0.529 , 0.627 , 0.000 ,1.0))
L1table.SetTableValue( 162 , ( 0.529 , 0.639 , 0.000 ,1.0))
L1table.SetTableValue( 163 , ( 0.529 , 0.651 , 0.000 ,1.0))
L1table.SetTableValue( 164 , ( 0.529 , 0.667 , 0.000 ,1.0))
L1table.SetTableValue( 165 , ( 0.529 , 0.682 , 0.000 ,1.0))
L1table.SetTableValue( 166 , ( 0.529 , 0.694 , 0.000 ,1.0))
L1table.SetTableValue( 167 , ( 0.529 , 0.706 , 0.000 ,1.0))
L1table.SetTableValue( 168 , ( 0.529 , 0.722 , 0.000 ,1.0))
L1table.SetTableValue( 169 , ( 0.529 , 0.737 , 0.000 ,1.0))
L1table.SetTableValue( 170 , ( 0.529 , 0.753 , 0.000 ,1.0))
L1table.SetTableValue( 171 , ( 0.529 , 0.765 , 0.000 ,1.0))
L1table.SetTableValue( 172 , ( 0.529 , 0.784 , 0.000 ,1.0))
L1table.SetTableValue( 173 , ( 0.529 , 0.796 , 0.000 ,1.0))
L1table.SetTableValue( 174 , ( 0.529 , 0.804 , 0.000 ,1.0))
L1table.SetTableValue( 175 , ( 0.529 , 0.824 , 0.000 ,1.0))
L1table.SetTableValue( 176 , ( 0.529 , 0.839 , 0.000 ,1.0))
L1table.SetTableValue( 177 , ( 0.529 , 0.855 , 0.000 ,1.0))
L1table.SetTableValue( 178 , ( 0.529 , 0.871 , 0.000 ,1.0))
L1table.SetTableValue( 179 , ( 0.529 , 0.886 , 0.000 ,1.0))
L1table.SetTableValue( 180 , ( 0.529 , 0.906 , 0.000 ,1.0))
L1table.SetTableValue( 181 , ( 0.529 , 0.925 , 0.000 ,1.0))
L1table.SetTableValue( 182 , ( 0.529 , 0.937 , 0.000 ,1.0))
L1table.SetTableValue( 183 , ( 0.529 , 0.957 , 0.000 ,1.0))
L1table.SetTableValue( 184 , ( 0.529 , 0.976 , 0.000 ,1.0))
L1table.SetTableValue( 185 , ( 0.529 , 0.996 , 0.000 ,1.0))
L1table.SetTableValue( 186 , ( 0.529 , 1.000 , 0.004 ,1.0))
L1table.SetTableValue( 187 , ( 0.529 , 1.000 , 0.020 ,1.0))
L1table.SetTableValue( 188 , ( 0.529 , 1.000 , 0.039 ,1.0))
L1table.SetTableValue( 189 , ( 0.529 , 1.000 , 0.059 ,1.0))
L1table.SetTableValue( 190 , ( 0.529 , 1.000 , 0.078 ,1.0))
L1table.SetTableValue( 191 , ( 0.529 , 1.000 , 0.090 ,1.0))
L1table.SetTableValue( 192 , ( 0.529 , 1.000 , 0.110 ,1.0))
L1table.SetTableValue( 193 , ( 0.529 , 1.000 , 0.129 ,1.0))
L1table.SetTableValue( 194 , ( 0.529 , 1.000 , 0.149 ,1.0))
L1table.SetTableValue( 195 , ( 0.529 , 1.000 , 0.169 ,1.0))
L1table.SetTableValue( 196 , ( 0.529 , 1.000 , 0.176 ,1.0))
L1table.SetTableValue( 197 , ( 0.529 , 1.000 , 0.192 ,1.0))
L1table.SetTableValue( 198 , ( 0.529 , 1.000 , 0.212 ,1.0))
L1table.SetTableValue( 199 , ( 0.529 , 1.000 , 0.231 ,1.0))
L1table.SetTableValue( 200 , ( 0.529 , 1.000 , 0.255 ,1.0))
L1table.SetTableValue( 201 , ( 0.529 , 1.000 , 0.275 ,1.0))
L1table.SetTableValue( 202 , ( 0.529 , 1.000 , 0.290 ,1.0))
L1table.SetTableValue( 203 , ( 0.529 , 1.000 , 0.314 ,1.0))
L1table.SetTableValue( 204 , ( 0.529 , 1.000 , 0.329 ,1.0))
L1table.SetTableValue( 205 , ( 0.529 , 1.000 , 0.353 ,1.0))
L1table.SetTableValue( 206 , ( 0.529 , 1.000 , 0.373 ,1.0))
L1table.SetTableValue( 207 , ( 0.529 , 1.000 , 0.384 ,1.0))
L1table.SetTableValue( 208 , ( 0.529 , 1.000 , 0.408 ,1.0))
L1table.SetTableValue( 209 , ( 0.529 , 1.000 , 0.431 ,1.0))
L1table.SetTableValue( 210 , ( 0.529 , 1.000 , 0.455 ,1.0))
L1table.SetTableValue( 211 , ( 0.529 , 1.000 , 0.471 ,1.0))
L1table.SetTableValue( 212 , ( 0.529 , 1.000 , 0.490 ,1.0))
L1table.SetTableValue( 213 , ( 0.529 , 1.000 , 0.514 ,1.0))
L1table.SetTableValue( 214 , ( 0.529 , 1.000 , 0.537 ,1.0))
L1table.SetTableValue( 215 , ( 0.529 , 1.000 , 0.565 ,1.0))
L1table.SetTableValue( 216 , ( 0.529 , 1.000 , 0.584 ,1.0))
L1table.SetTableValue( 217 , ( 0.529 , 1.000 , 0.604 ,1.0))
L1table.SetTableValue( 218 , ( 0.529 , 1.000 , 0.620 ,1.0))
L1table.SetTableValue( 219 , ( 0.529 , 1.000 , 0.647 ,1.0))
L1table.SetTableValue( 220 , ( 0.529 , 1.000 , 0.675 ,1.0))
L1table.SetTableValue( 221 , ( 0.529 , 1.000 , 0.702 ,1.0))
L1table.SetTableValue( 222 , ( 0.529 , 1.000 , 0.729 ,1.0))
L1table.SetTableValue( 223 , ( 0.529 , 1.000 , 0.749 ,1.0))
L1table.SetTableValue( 224 , ( 0.529 , 1.000 , 0.776 ,1.0))
L1table.SetTableValue( 225 , ( 0.529 , 1.000 , 0.796 ,1.0))
L1table.SetTableValue( 226 , ( 0.529 , 1.000 , 0.827 ,1.0))
L1table.SetTableValue( 227 , ( 0.529 , 1.000 , 0.847 ,1.0))
L1table.SetTableValue( 228 , ( 0.529 , 1.000 , 0.878 ,1.0))
L1table.SetTableValue( 229 , ( 0.529 , 1.000 , 0.910 ,1.0))
L1table.SetTableValue( 230 , ( 0.529 , 1.000 , 0.941 ,1.0))
L1table.SetTableValue( 231 , ( 0.529 , 1.000 , 0.973 ,1.0))
L1table.SetTableValue( 232 , ( 0.529 , 1.000 , 0.996 ,1.0))
L1table.SetTableValue( 233 , ( 0.529 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 234 , ( 0.549 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 235 , ( 0.573 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 236 , ( 0.600 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 237 , ( 0.612 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 238 , ( 0.631 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 239 , ( 0.659 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 240 , ( 0.675 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 241 , ( 0.694 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 242 , ( 0.714 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 243 , ( 0.741 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 244 , ( 0.753 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 245 , ( 0.780 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 246 , ( 0.800 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 247 , ( 0.824 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 248 , ( 0.843 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 249 , ( 0.863 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 250 , ( 0.882 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 251 , ( 0.910 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 252 , ( 0.925 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 253 , ( 0.941 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 254 , ( 0.973 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 255 , ( 1.000 , 1.000 , 1.000 ,1.0))
L1table.Build()
self.Linear_Heat[key] = L1table
return self.Linear_Heat[key]
def LUT_Linear_BlackToWhite(self, LUrange):
key = tuple(LUrange)
try:
return self.Linear_BlackToWhite[key]
except KeyError:
L1table = vtk.vtkLookupTable()
L1table.SetRange(LUrange[0], LUrange[1])
L1table.SetNumberOfColors(256)
L1table.SetTableValue( 0 , ( 0.000 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 1 , ( 0.000 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 2 , ( 0.000 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 3 , ( 0.000 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 4 , ( 0.000 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 5 , ( 0.000 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 6 , ( 0.000 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 7 , ( 0.004 , 0.004 , 0.004 ,1.0))
L1table.SetTableValue( 8 , ( 0.004 , 0.004 , 0.004 ,1.0))
L1table.SetTableValue( 9 , ( 0.004 , 0.004 , 0.004 ,1.0))
L1table.SetTableValue( 10 , ( 0.004 , 0.004 , 0.004 ,1.0))
L1table.SetTableValue( 11 , ( 0.004 , 0.004 , 0.004 ,1.0))
L1table.SetTableValue( 12 , ( 0.004 , 0.004 , 0.004 ,1.0))
L1table.SetTableValue( 13 , ( 0.004 , 0.004 , 0.004 ,1.0))
L1table.SetTableValue( 14 , ( 0.004 , 0.004 , 0.004 ,1.0))
L1table.SetTableValue( 15 , ( 0.004 , 0.004 , 0.004 ,1.0))
L1table.SetTableValue( 16 , ( 0.008 , 0.008 , 0.008 ,1.0))
L1table.SetTableValue( 17 , ( 0.008 , 0.008 , 0.008 ,1.0))
L1table.SetTableValue( 18 , ( 0.008 , 0.008 , 0.008 ,1.0))
L1table.SetTableValue( 19 , ( 0.008 , 0.008 , 0.008 ,1.0))
L1table.SetTableValue( 20 , ( 0.008 , 0.008 , 0.008 ,1.0))
L1table.SetTableValue( 21 , ( 0.008 , 0.008 , 0.008 ,1.0))
L1table.SetTableValue( 22 , ( 0.008 , 0.008 , 0.008 ,1.0))
L1table.SetTableValue( 23 , ( 0.012 , 0.012 , 0.012 ,1.0))
L1table.SetTableValue( 24 , ( 0.012 , 0.012 , 0.012 ,1.0))
L1table.SetTableValue( 25 , ( 0.012 , 0.012 , 0.012 ,1.0))
L1table.SetTableValue( 26 , ( 0.012 , 0.012 , 0.012 ,1.0))
L1table.SetTableValue( 27 , ( 0.012 , 0.012 , 0.012 ,1.0))
L1table.SetTableValue( 28 , ( 0.012 , 0.012 , 0.012 ,1.0))
L1table.SetTableValue( 29 , ( 0.012 , 0.012 , 0.012 ,1.0))
L1table.SetTableValue( 30 , ( 0.016 , 0.016 , 0.016 ,1.0))
L1table.SetTableValue( 31 , ( 0.016 , 0.016 , 0.016 ,1.0))
L1table.SetTableValue( 32 , ( 0.016 , 0.016 , 0.016 ,1.0))
L1table.SetTableValue( 33 , ( 0.016 , 0.016 , 0.016 ,1.0))
L1table.SetTableValue( 34 , ( 0.016 , 0.016 , 0.016 ,1.0))
L1table.SetTableValue( 35 , ( 0.020 , 0.020 , 0.020 ,1.0))
L1table.SetTableValue( 36 , ( 0.020 , 0.020 , 0.020 ,1.0))
L1table.SetTableValue( 37 , ( 0.020 , 0.020 , 0.020 ,1.0))
L1table.SetTableValue( 38 , ( 0.020 , 0.020 , 0.020 ,1.0))
L1table.SetTableValue( 39 , ( 0.020 , 0.020 , 0.020 ,1.0))
L1table.SetTableValue( 40 , ( 0.024 , 0.024 , 0.024 ,1.0))
L1table.SetTableValue( 41 , ( 0.024 , 0.024 , 0.024 ,1.0))
L1table.SetTableValue( 42 , ( 0.024 , 0.024 , 0.024 ,1.0))
L1table.SetTableValue( 43 , ( 0.024 , 0.024 , 0.024 ,1.0))
L1table.SetTableValue( 44 , ( 0.024 , 0.024 , 0.024 ,1.0))
L1table.SetTableValue( 45 , ( 0.027 , 0.027 , 0.027 ,1.0))
L1table.SetTableValue( 46 , ( 0.027 , 0.027 , 0.027 ,1.0))
L1table.SetTableValue( 47 , ( 0.027 , 0.027 , 0.027 ,1.0))
L1table.SetTableValue( 48 , ( 0.027 , 0.027 , 0.027 ,1.0))
L1table.SetTableValue( 49 , ( 0.027 , 0.027 , 0.027 ,1.0))
L1table.SetTableValue( 50 , ( 0.031 , 0.031 , 0.031 ,1.0))
L1table.SetTableValue( 51 , ( 0.031 , 0.031 , 0.031 ,1.0))
L1table.SetTableValue( 52 , ( 0.035 , 0.035 , 0.035 ,1.0))
L1table.SetTableValue( 53 , ( 0.035 , 0.035 , 0.035 ,1.0))
L1table.SetTableValue( 54 , ( 0.035 , 0.035 , 0.035 ,1.0))
L1table.SetTableValue( 55 , ( 0.035 , 0.035 , 0.035 ,1.0))
L1table.SetTableValue( 56 , ( 0.039 , 0.039 , 0.039 ,1.0))
L1table.SetTableValue( 57 , ( 0.039 , 0.039 , 0.039 ,1.0))
L1table.SetTableValue( 58 , ( 0.039 , 0.039 , 0.039 ,1.0))
L1table.SetTableValue( 59 , ( 0.039 , 0.039 , 0.039 ,1.0))
L1table.SetTableValue( 60 , ( 0.039 , 0.039 , 0.039 ,1.0))
L1table.SetTableValue( 61 , ( 0.043 , 0.043 , 0.043 ,1.0))
L1table.SetTableValue( 62 , ( 0.043 , 0.043 , 0.043 ,1.0))
L1table.SetTableValue( 63 , ( 0.047 , 0.047 , 0.047 ,1.0))
L1table.SetTableValue( 64 , ( 0.047 , 0.047 , 0.047 ,1.0))
L1table.SetTableValue( 65 , ( 0.047 , 0.047 , 0.047 ,1.0))
L1table.SetTableValue( 66 , ( 0.051 , 0.051 , 0.051 ,1.0))
L1table.SetTableValue( 67 , ( 0.051 , 0.051 , 0.051 ,1.0))
L1table.SetTableValue( 68 , ( 0.055 , 0.055 , 0.055 ,1.0))
L1table.SetTableValue( 69 , ( 0.055 , 0.055 , 0.055 ,1.0))
L1table.SetTableValue( 70 , ( 0.059 , 0.059 , 0.059 ,1.0))
L1table.SetTableValue( 71 , ( 0.059 , 0.059 , 0.059 ,1.0))
L1table.SetTableValue( 72 , ( 0.059 , 0.059 , 0.059 ,1.0))
L1table.SetTableValue( 73 , ( 0.063 , 0.063 , 0.063 ,1.0))
L1table.SetTableValue( 74 , ( 0.063 , 0.063 , 0.063 ,1.0))
L1table.SetTableValue( 75 , ( 0.067 , 0.067 , 0.067 ,1.0))
L1table.SetTableValue( 76 , ( 0.067 , 0.067 , 0.067 ,1.0))
L1table.SetTableValue( 77 , ( 0.071 , 0.071 , 0.071 ,1.0))
L1table.SetTableValue( 78 , ( 0.071 , 0.071 , 0.071 ,1.0))
L1table.SetTableValue( 79 , ( 0.075 , 0.075 , 0.075 ,1.0))
L1table.SetTableValue( 80 , ( 0.075 , 0.075 , 0.075 ,1.0))
L1table.SetTableValue( 81 , ( 0.075 , 0.075 , 0.075 ,1.0))
L1table.SetTableValue( 82 , ( 0.075 , 0.075 , 0.075 ,1.0))
L1table.SetTableValue( 83 , ( 0.075 , 0.075 , 0.075 ,1.0))
L1table.SetTableValue( 84 , ( 0.078 , 0.078 , 0.078 ,1.0))
L1table.SetTableValue( 85 , ( 0.078 , 0.078 , 0.078 ,1.0))
L1table.SetTableValue( 86 , ( 0.086 , 0.086 , 0.086 ,1.0))
L1table.SetTableValue( 87 , ( 0.086 , 0.086 , 0.086 ,1.0))
L1table.SetTableValue( 88 , ( 0.086 , 0.086 , 0.086 ,1.0))
L1table.SetTableValue( 89 , ( 0.090 , 0.090 , 0.090 ,1.0))
L1table.SetTableValue( 90 , ( 0.090 , 0.090 , 0.090 ,1.0))
L1table.SetTableValue( 91 , ( 0.094 , 0.094 , 0.094 ,1.0))
L1table.SetTableValue( 92 , ( 0.094 , 0.094 , 0.094 ,1.0))
L1table.SetTableValue( 93 , ( 0.102 , 0.102 , 0.102 ,1.0))
L1table.SetTableValue( 94 , ( 0.102 , 0.102 , 0.102 ,1.0))
L1table.SetTableValue( 95 , ( 0.102 , 0.102 , 0.102 ,1.0))
L1table.SetTableValue( 96 , ( 0.106 , 0.106 , 0.106 ,1.0))
L1table.SetTableValue( 97 , ( 0.106 , 0.106 , 0.106 ,1.0))
L1table.SetTableValue( 98 , ( 0.114 , 0.114 , 0.114 ,1.0))
L1table.SetTableValue( 99 , ( 0.114 , 0.114 , 0.114 ,1.0))
L1table.SetTableValue( 100 , ( 0.118 , 0.118 , 0.118 ,1.0))
L1table.SetTableValue( 101 , ( 0.118 , 0.118 , 0.118 ,1.0))
L1table.SetTableValue( 102 , ( 0.125 , 0.125 , 0.125 ,1.0))
L1table.SetTableValue( 103 , ( 0.125 , 0.125 , 0.125 ,1.0))
L1table.SetTableValue( 104 , ( 0.125 , 0.125 , 0.125 ,1.0))
L1table.SetTableValue( 105 , ( 0.125 , 0.125 , 0.125 ,1.0))
L1table.SetTableValue( 106 , ( 0.125 , 0.125 , 0.125 ,1.0))
L1table.SetTableValue( 107 , ( 0.133 , 0.133 , 0.133 ,1.0))
L1table.SetTableValue( 108 , ( 0.133 , 0.133 , 0.133 ,1.0))
L1table.SetTableValue( 109 , ( 0.137 , 0.137 , 0.137 ,1.0))
L1table.SetTableValue( 110 , ( 0.137 , 0.137 , 0.137 ,1.0))
L1table.SetTableValue( 111 , ( 0.137 , 0.137 , 0.137 ,1.0))
L1table.SetTableValue( 112 , ( 0.145 , 0.145 , 0.145 ,1.0))
L1table.SetTableValue( 113 , ( 0.145 , 0.145 , 0.145 ,1.0))
L1table.SetTableValue( 114 , ( 0.153 , 0.153 , 0.153 ,1.0))
L1table.SetTableValue( 115 , ( 0.153 , 0.153 , 0.153 ,1.0))
L1table.SetTableValue( 116 , ( 0.161 , 0.161 , 0.161 ,1.0))
L1table.SetTableValue( 117 , ( 0.161 , 0.161 , 0.161 ,1.0))
L1table.SetTableValue( 118 , ( 0.161 , 0.161 , 0.161 ,1.0))
L1table.SetTableValue( 119 , ( 0.169 , 0.169 , 0.169 ,1.0))
L1table.SetTableValue( 120 , ( 0.169 , 0.169 , 0.169 ,1.0))
L1table.SetTableValue( 121 , ( 0.176 , 0.176 , 0.176 ,1.0))
L1table.SetTableValue( 122 , ( 0.176 , 0.176 , 0.176 ,1.0))
L1table.SetTableValue( 123 , ( 0.180 , 0.180 , 0.180 ,1.0))
L1table.SetTableValue( 124 , ( 0.180 , 0.180 , 0.180 ,1.0))
L1table.SetTableValue( 125 , ( 0.180 , 0.180 , 0.180 ,1.0))
L1table.SetTableValue( 126 , ( 0.184 , 0.184 , 0.184 ,1.0))
L1table.SetTableValue( 127 , ( 0.184 , 0.184 , 0.184 ,1.0))
L1table.SetTableValue( 128 , ( 0.192 , 0.192 , 0.192 ,1.0))
L1table.SetTableValue( 129 , ( 0.192 , 0.192 , 0.192 ,1.0))
L1table.SetTableValue( 130 , ( 0.200 , 0.200 , 0.200 ,1.0))
L1table.SetTableValue( 131 , ( 0.200 , 0.200 , 0.200 ,1.0))
L1table.SetTableValue( 132 , ( 0.204 , 0.204 , 0.204 ,1.0))
L1table.SetTableValue( 133 , ( 0.204 , 0.204 , 0.204 ,1.0))
L1table.SetTableValue( 134 , ( 0.204 , 0.204 , 0.204 ,1.0))
L1table.SetTableValue( 135 , ( 0.212 , 0.212 , 0.212 ,1.0))
L1table.SetTableValue( 136 , ( 0.212 , 0.212 , 0.212 ,1.0))
L1table.SetTableValue( 137 , ( 0.220 , 0.220 , 0.220 ,1.0))
L1table.SetTableValue( 138 , ( 0.220 , 0.220 , 0.220 ,1.0))
L1table.SetTableValue( 139 , ( 0.231 , 0.231 , 0.231 ,1.0))
L1table.SetTableValue( 140 , ( 0.231 , 0.231 , 0.231 ,1.0))
L1table.SetTableValue( 141 , ( 0.231 , 0.231 , 0.231 ,1.0))
L1table.SetTableValue( 142 , ( 0.239 , 0.239 , 0.239 ,1.0))
L1table.SetTableValue( 143 , ( 0.239 , 0.239 , 0.239 ,1.0))
L1table.SetTableValue( 144 , ( 0.251 , 0.251 , 0.251 ,1.0))
L1table.SetTableValue( 145 , ( 0.251 , 0.251 , 0.251 ,1.0))
L1table.SetTableValue( 146 , ( 0.263 , 0.263 , 0.263 ,1.0))
L1table.SetTableValue( 147 , ( 0.263 , 0.263 , 0.263 ,1.0))
L1table.SetTableValue( 148 , ( 0.263 , 0.263 , 0.263 ,1.0))
L1table.SetTableValue( 149 , ( 0.271 , 0.271 , 0.271 ,1.0))
L1table.SetTableValue( 150 , ( 0.271 , 0.271 , 0.271 ,1.0))
L1table.SetTableValue( 151 , ( 0.282 , 0.282 , 0.282 ,1.0))
L1table.SetTableValue( 152 , ( 0.282 , 0.282 , 0.282 ,1.0))
L1table.SetTableValue( 153 , ( 0.294 , 0.294 , 0.294 ,1.0))
L1table.SetTableValue( 154 , ( 0.294 , 0.294 , 0.294 ,1.0))
L1table.SetTableValue( 155 , ( 0.298 , 0.298 , 0.298 ,1.0))
L1table.SetTableValue( 156 , ( 0.298 , 0.298 , 0.298 ,1.0))
L1table.SetTableValue( 157 , ( 0.298 , 0.298 , 0.298 ,1.0))
L1table.SetTableValue( 158 , ( 0.306 , 0.306 , 0.306 ,1.0))
L1table.SetTableValue( 159 , ( 0.306 , 0.306 , 0.306 ,1.0))
L1table.SetTableValue( 160 , ( 0.318 , 0.318 , 0.318 ,1.0))
L1table.SetTableValue( 161 , ( 0.318 , 0.318 , 0.318 ,1.0))
L1table.SetTableValue( 162 , ( 0.329 , 0.329 , 0.329 ,1.0))
L1table.SetTableValue( 163 , ( 0.329 , 0.329 , 0.329 ,1.0))
L1table.SetTableValue( 164 , ( 0.329 , 0.329 , 0.329 ,1.0))
L1table.SetTableValue( 165 , ( 0.341 , 0.341 , 0.341 ,1.0))
L1table.SetTableValue( 166 , ( 0.341 , 0.341 , 0.341 ,1.0))
L1table.SetTableValue( 167 , ( 0.357 , 0.357 , 0.357 ,1.0))
L1table.SetTableValue( 168 , ( 0.357 , 0.357 , 0.357 ,1.0))
L1table.SetTableValue( 169 , ( 0.369 , 0.369 , 0.369 ,1.0))
L1table.SetTableValue( 170 , ( 0.369 , 0.369 , 0.369 ,1.0))
L1table.SetTableValue( 171 , ( 0.369 , 0.369 , 0.369 ,1.0))
L1table.SetTableValue( 172 , ( 0.380 , 0.380 , 0.380 ,1.0))
L1table.SetTableValue( 173 , ( 0.380 , 0.380 , 0.380 ,1.0))
L1table.SetTableValue( 174 , ( 0.396 , 0.396 , 0.396 ,1.0))
L1table.SetTableValue( 175 , ( 0.396 , 0.396 , 0.396 ,1.0))
L1table.SetTableValue( 176 , ( 0.408 , 0.408 , 0.408 ,1.0))
L1table.SetTableValue( 177 , ( 0.408 , 0.408 , 0.408 ,1.0))
L1table.SetTableValue( 178 , ( 0.420 , 0.420 , 0.420 ,1.0))
L1table.SetTableValue( 179 , ( 0.420 , 0.420 , 0.420 ,1.0))
L1table.SetTableValue( 180 , ( 0.420 , 0.420 , 0.420 ,1.0))
L1table.SetTableValue( 181 , ( 0.424 , 0.424 , 0.424 ,1.0))
L1table.SetTableValue( 182 , ( 0.424 , 0.424 , 0.424 ,1.0))
L1table.SetTableValue( 183 , ( 0.439 , 0.439 , 0.439 ,1.0))
L1table.SetTableValue( 184 , ( 0.439 , 0.439 , 0.439 ,1.0))
L1table.SetTableValue( 185 , ( 0.455 , 0.455 , 0.455 ,1.0))
L1table.SetTableValue( 186 , ( 0.455 , 0.455 , 0.455 ,1.0))
L1table.SetTableValue( 187 , ( 0.455 , 0.455 , 0.455 ,1.0))
L1table.SetTableValue( 188 , ( 0.471 , 0.471 , 0.471 ,1.0))
L1table.SetTableValue( 189 , ( 0.471 , 0.471 , 0.471 ,1.0))
L1table.SetTableValue( 190 , ( 0.486 , 0.486 , 0.486 ,1.0))
L1table.SetTableValue( 191 , ( 0.486 , 0.486 , 0.486 ,1.0))
L1table.SetTableValue( 192 , ( 0.502 , 0.502 , 0.502 ,1.0))
L1table.SetTableValue( 193 , ( 0.502 , 0.502 , 0.502 ,1.0))
L1table.SetTableValue( 194 , ( 0.502 , 0.502 , 0.502 ,1.0))
L1table.SetTableValue( 195 , ( 0.518 , 0.518 , 0.518 ,1.0))
L1table.SetTableValue( 196 , ( 0.518 , 0.518 , 0.518 ,1.0))
L1table.SetTableValue( 197 , ( 0.533 , 0.533 , 0.533 ,1.0))
L1table.SetTableValue( 198 , ( 0.533 , 0.533 , 0.533 ,1.0))
L1table.SetTableValue( 199 , ( 0.553 , 0.553 , 0.553 ,1.0))
L1table.SetTableValue( 200 , ( 0.553 , 0.553 , 0.553 ,1.0))
L1table.SetTableValue( 201 , ( 0.569 , 0.569 , 0.569 ,1.0))
L1table.SetTableValue( 202 , ( 0.569 , 0.569 , 0.569 ,1.0))
L1table.SetTableValue( 203 , ( 0.569 , 0.569 , 0.569 ,1.0))
L1table.SetTableValue( 204 , ( 0.576 , 0.576 , 0.576 ,1.0))
L1table.SetTableValue( 205 , ( 0.576 , 0.576 , 0.576 ,1.0))
L1table.SetTableValue( 206 , ( 0.588 , 0.588 , 0.588 ,1.0))
L1table.SetTableValue( 207 , ( 0.588 , 0.588 , 0.588 ,1.0))
L1table.SetTableValue( 208 , ( 0.604 , 0.604 , 0.604 ,1.0))
L1table.SetTableValue( 209 , ( 0.604 , 0.604 , 0.604 ,1.0))
L1table.SetTableValue( 210 , ( 0.604 , 0.604 , 0.604 ,1.0))
L1table.SetTableValue( 211 , ( 0.624 , 0.624 , 0.624 ,1.0))
L1table.SetTableValue( 212 , ( 0.624 , 0.624 , 0.624 ,1.0))
L1table.SetTableValue( 213 , ( 0.643 , 0.643 , 0.643 ,1.0))
L1table.SetTableValue( 214 , ( 0.643 , 0.643 , 0.643 ,1.0))
L1table.SetTableValue( 215 , ( 0.663 , 0.663 , 0.663 ,1.0))
L1table.SetTableValue( 216 , ( 0.663 , 0.663 , 0.663 ,1.0))
L1table.SetTableValue( 217 , ( 0.663 , 0.663 , 0.663 ,1.0))
L1table.SetTableValue( 218 , ( 0.682 , 0.682 , 0.682 ,1.0))
L1table.SetTableValue( 219 , ( 0.682 , 0.682 , 0.682 ,1.0))
L1table.SetTableValue( 220 , ( 0.702 , 0.702 , 0.702 ,1.0))
L1table.SetTableValue( 221 , ( 0.702 , 0.702 , 0.702 ,1.0))
L1table.SetTableValue( 222 , ( 0.725 , 0.725 , 0.725 ,1.0))
L1table.SetTableValue( 223 , ( 0.725 , 0.725 , 0.725 ,1.0))
L1table.SetTableValue( 224 , ( 0.745 , 0.745 , 0.745 ,1.0))
L1table.SetTableValue( 225 , ( 0.745 , 0.745 , 0.745 ,1.0))
L1table.SetTableValue( 226 , ( 0.745 , 0.745 , 0.745 ,1.0))
L1table.SetTableValue( 227 , ( 0.765 , 0.765 , 0.765 ,1.0))
L1table.SetTableValue( 228 , ( 0.765 , 0.765 , 0.765 ,1.0))
L1table.SetTableValue( 229 , ( 0.765 , 0.765 , 0.765 ,1.0))
L1table.SetTableValue( 230 , ( 0.765 , 0.765 , 0.765 ,1.0))
L1table.SetTableValue( 231 , ( 0.788 , 0.788 , 0.788 ,1.0))
L1table.SetTableValue( 232 , ( 0.788 , 0.788 , 0.788 ,1.0))
L1table.SetTableValue( 233 , ( 0.788 , 0.788 , 0.788 ,1.0))
L1table.SetTableValue( 234 , ( 0.812 , 0.812 , 0.812 ,1.0))
L1table.SetTableValue( 235 , ( 0.812 , 0.812 , 0.812 ,1.0))
L1table.SetTableValue( 236 , ( 0.831 , 0.831 , 0.831 ,1.0))
L1table.SetTableValue( 237 , ( 0.831 , 0.831 , 0.831 ,1.0))
L1table.SetTableValue( 238 , ( 0.855 , 0.855 , 0.855 ,1.0))
L1table.SetTableValue( 239 , ( 0.855 , 0.855 , 0.855 ,1.0))
L1table.SetTableValue( 240 , ( 0.855 , 0.855 , 0.855 ,1.0))
L1table.SetTableValue( 241 , ( 0.878 , 0.878 , 0.878 ,1.0))
L1table.SetTableValue( 242 , ( 0.878 , 0.878 , 0.878 ,1.0))
L1table.SetTableValue( 243 , ( 0.902 , 0.902 , 0.902 ,1.0))
L1table.SetTableValue( 244 , ( 0.902 , 0.902 , 0.902 ,1.0))
L1table.SetTableValue( 245 , ( 0.929 , 0.929 , 0.929 ,1.0))
L1table.SetTableValue( 246 , ( 0.929 , 0.929 , 0.929 ,1.0))
L1table.SetTableValue( 247 , ( 0.953 , 0.953 , 0.953 ,1.0))
L1table.SetTableValue( 248 , ( 0.953 , 0.953 , 0.953 ,1.0))
L1table.SetTableValue( 249 , ( 0.953 , 0.953 , 0.953 ,1.0))
L1table.SetTableValue( 250 , ( 0.976 , 0.976 , 0.976 ,1.0))
L1table.SetTableValue( 251 , ( 0.976 , 0.976 , 0.976 ,1.0))
L1table.SetTableValue( 252 , ( 0.988 , 0.988 , 0.988 ,1.0))
L1table.SetTableValue( 253 , ( 0.988 , 0.988 , 0.988 ,1.0))
L1table.SetTableValue( 254 , ( 0.988 , 0.988 , 0.988 ,1.0))
L1table.SetTableValue( 255 , ( 1.000 , 1.000 , 1.000 ,1.0))
L1table.Build()
self.Linear_BlackToWhite[key] = L1table
return self.Linear_BlackToWhite[key]
def LUT_Linear_BlueToYellow(self, LUrange):
key = tuple(LUrange)
try:
return self.Linear_BlueToYellow[key]
except KeyError:
L1table = vtk.vtkLookupTable()
L1table.SetRange(LUrange[0], LUrange[1])
L1table.SetNumberOfColors(256)
L1table.SetTableValue( 0 , ( 0.027 , 0.027 , 0.996 ,1.0))
L1table.SetTableValue( 1 , ( 0.090 , 0.090 , 0.988 ,1.0))
L1table.SetTableValue( 2 , ( 0.118 , 0.118 , 0.980 ,1.0))
L1table.SetTableValue( 3 , ( 0.141 , 0.141 , 0.973 ,1.0))
L1table.SetTableValue( 4 , ( 0.157 , 0.157 , 0.969 ,1.0))
L1table.SetTableValue( 5 , ( 0.173 , 0.173 , 0.961 ,1.0))
L1table.SetTableValue( 6 , ( 0.184 , 0.184 , 0.953 ,1.0))
L1table.SetTableValue( 7 , ( 0.196 , 0.196 , 0.949 ,1.0))
L1table.SetTableValue( 8 , ( 0.204 , 0.204 , 0.941 ,1.0))
L1table.SetTableValue( 9 , ( 0.216 , 0.216 , 0.937 ,1.0))
L1table.SetTableValue( 10 , ( 0.224 , 0.224 , 0.933 ,1.0))
L1table.SetTableValue( 11 , ( 0.231 , 0.231 , 0.925 ,1.0))
L1table.SetTableValue( 12 , ( 0.239 , 0.239 , 0.922 ,1.0))
L1table.SetTableValue( 13 , ( 0.247 , 0.247 , 0.918 ,1.0))
L1table.SetTableValue( 14 , ( 0.255 , 0.255 , 0.914 ,1.0))
L1table.SetTableValue( 15 , ( 0.259 , 0.259 , 0.906 ,1.0))
L1table.SetTableValue( 16 , ( 0.267 , 0.267 , 0.902 ,1.0))
L1table.SetTableValue( 17 , ( 0.271 , 0.271 , 0.898 ,1.0))
L1table.SetTableValue( 18 , ( 0.278 , 0.278 , 0.894 ,1.0))
L1table.SetTableValue( 19 , ( 0.282 , 0.282 , 0.890 ,1.0))
L1table.SetTableValue( 20 , ( 0.290 , 0.290 , 0.886 ,1.0))
L1table.SetTableValue( 21 , ( 0.294 , 0.294 , 0.882 ,1.0))
L1table.SetTableValue( 22 , ( 0.298 , 0.298 , 0.882 ,1.0))
L1table.SetTableValue( 23 , ( 0.306 , 0.306 , 0.878 ,1.0))
L1table.SetTableValue( 24 , ( 0.310 , 0.310 , 0.875 ,1.0))
L1table.SetTableValue( 25 , ( 0.314 , 0.314 , 0.871 ,1.0))
L1table.SetTableValue( 26 , ( 0.318 , 0.318 , 0.867 ,1.0))
L1table.SetTableValue( 27 , ( 0.322 , 0.322 , 0.867 ,1.0))
L1table.SetTableValue( 28 , ( 0.329 , 0.329 , 0.863 ,1.0))
L1table.SetTableValue( 29 , ( 0.333 , 0.333 , 0.859 ,1.0))
L1table.SetTableValue( 30 , ( 0.337 , 0.337 , 0.855 ,1.0))
L1table.SetTableValue( 31 , ( 0.341 , 0.341 , 0.855 ,1.0))
L1table.SetTableValue( 32 , ( 0.345 , 0.345 , 0.851 ,1.0))
L1table.SetTableValue( 33 , ( 0.349 , 0.349 , 0.847 ,1.0))
L1table.SetTableValue( 34 , ( 0.353 , 0.353 , 0.847 ,1.0))
L1table.SetTableValue( 35 , ( 0.357 , 0.357 , 0.843 ,1.0))
L1table.SetTableValue( 36 , ( 0.361 , 0.361 , 0.839 ,1.0))
L1table.SetTableValue( 37 , ( 0.365 , 0.365 , 0.839 ,1.0))
L1table.SetTableValue( 38 , ( 0.369 , 0.369 , 0.835 ,1.0))
L1table.SetTableValue( 39 , ( 0.373 , 0.373 , 0.835 ,1.0))
L1table.SetTableValue( 40 , ( 0.376 , 0.376 , 0.831 ,1.0))
L1table.SetTableValue( 41 , ( 0.380 , 0.380 , 0.831 ,1.0))
L1table.SetTableValue( 42 , ( 0.384 , 0.384 , 0.827 ,1.0))
L1table.SetTableValue( 43 , ( 0.384 , 0.384 , 0.824 ,1.0))
L1table.SetTableValue( 44 , ( 0.388 , 0.388 , 0.824 ,1.0))
L1table.SetTableValue( 45 , ( 0.392 , 0.392 , 0.820 ,1.0))
L1table.SetTableValue( 46 , ( 0.396 , 0.396 , 0.820 ,1.0))
L1table.SetTableValue( 47 , ( 0.400 , 0.400 , 0.816 ,1.0))
L1table.SetTableValue( 48 , ( 0.404 , 0.404 , 0.816 ,1.0))
L1table.SetTableValue( 49 , ( 0.408 , 0.408 , 0.816 ,1.0))
L1table.SetTableValue( 50 , ( 0.412 , 0.412 , 0.812 ,1.0))
L1table.SetTableValue( 51 , ( 0.412 , 0.412 , 0.812 ,1.0))
L1table.SetTableValue( 52 , ( 0.416 , 0.416 , 0.808 ,1.0))
L1table.SetTableValue( 53 , ( 0.420 , 0.420 , 0.808 ,1.0))
L1table.SetTableValue( 54 , ( 0.424 , 0.424 , 0.804 ,1.0))
L1table.SetTableValue( 55 , ( 0.427 , 0.427 , 0.804 ,1.0))
L1table.SetTableValue( 56 , ( 0.431 , 0.431 , 0.800 ,1.0))
L1table.SetTableValue( 57 , ( 0.431 , 0.431 , 0.800 ,1.0))
L1table.SetTableValue( 58 , ( 0.435 , 0.435 , 0.800 ,1.0))
L1table.SetTableValue( 59 , ( 0.439 , 0.439 , 0.796 ,1.0))
L1table.SetTableValue( 60 , ( 0.443 , 0.443 , 0.796 ,1.0))
L1table.SetTableValue( 61 , ( 0.447 , 0.447 , 0.792 ,1.0))
L1table.SetTableValue( 62 , ( 0.447 , 0.447 , 0.792 ,1.0))
L1table.SetTableValue( 63 , ( 0.451 , 0.451 , 0.792 ,1.0))
L1table.SetTableValue( 64 , ( 0.455 , 0.455 , 0.788 ,1.0))
L1table.SetTableValue( 65 , ( 0.459 , 0.459 , 0.788 ,1.0))
L1table.SetTableValue( 66 , ( 0.463 , 0.463 , 0.784 ,1.0))
L1table.SetTableValue( 67 , ( 0.463 , 0.463 , 0.784 ,1.0))
L1table.SetTableValue( 68 , ( 0.467 , 0.467 , 0.784 ,1.0))
L1table.SetTableValue( 69 , ( 0.471 , 0.471 , 0.780 ,1.0))
L1table.SetTableValue( 70 , ( 0.475 , 0.475 , 0.780 ,1.0))
L1table.SetTableValue( 71 , ( 0.475 , 0.475 , 0.780 ,1.0))
L1table.SetTableValue( 72 , ( 0.478 , 0.478 , 0.776 ,1.0))
L1table.SetTableValue( 73 , ( 0.482 , 0.482 , 0.776 ,1.0))
L1table.SetTableValue( 74 , ( 0.486 , 0.486 , 0.776 ,1.0))
L1table.SetTableValue( 75 , ( 0.486 , 0.486 , 0.773 ,1.0))
L1table.SetTableValue( 76 , ( 0.490 , 0.490 , 0.773 ,1.0))
L1table.SetTableValue( 77 , ( 0.494 , 0.494 , 0.773 ,1.0))
L1table.SetTableValue( 78 , ( 0.498 , 0.498 , 0.769 ,1.0))
L1table.SetTableValue( 79 , ( 0.502 , 0.502 , 0.769 ,1.0))
L1table.SetTableValue( 80 , ( 0.502 , 0.502 , 0.765 ,1.0))
L1table.SetTableValue( 81 , ( 0.506 , 0.506 , 0.765 ,1.0))
L1table.SetTableValue( 82 , ( 0.510 , 0.510 , 0.765 ,1.0))
L1table.SetTableValue( 83 , ( 0.510 , 0.510 , 0.761 ,1.0))
L1table.SetTableValue( 84 , ( 0.514 , 0.514 , 0.761 ,1.0))
L1table.SetTableValue( 85 , ( 0.518 , 0.518 , 0.761 ,1.0))
L1table.SetTableValue( 86 , ( 0.522 , 0.522 , 0.757 ,1.0))
L1table.SetTableValue( 87 , ( 0.522 , 0.522 , 0.757 ,1.0))
L1table.SetTableValue( 88 , ( 0.525 , 0.525 , 0.757 ,1.0))
L1table.SetTableValue( 89 , ( 0.529 , 0.529 , 0.753 ,1.0))
L1table.SetTableValue( 90 , ( 0.533 , 0.533 , 0.753 ,1.0))
L1table.SetTableValue( 91 , ( 0.533 , 0.533 , 0.753 ,1.0))
L1table.SetTableValue( 92 , ( 0.537 , 0.537 , 0.749 ,1.0))
L1table.SetTableValue( 93 , ( 0.541 , 0.541 , 0.749 ,1.0))
L1table.SetTableValue( 94 , ( 0.545 , 0.545 , 0.749 ,1.0))
L1table.SetTableValue( 95 , ( 0.545 , 0.545 , 0.745 ,1.0))
L1table.SetTableValue( 96 , ( 0.549 , 0.549 , 0.745 ,1.0))
L1table.SetTableValue( 97 , ( 0.553 , 0.553 , 0.745 ,1.0))
L1table.SetTableValue( 98 , ( 0.557 , 0.557 , 0.741 ,1.0))
L1table.SetTableValue( 99 , ( 0.557 , 0.557 , 0.741 ,1.0))
L1table.SetTableValue( 100 , ( 0.561 , 0.561 , 0.741 ,1.0))
L1table.SetTableValue( 101 , ( 0.565 , 0.565 , 0.737 ,1.0))
L1table.SetTableValue( 102 , ( 0.565 , 0.565 , 0.737 ,1.0))
L1table.SetTableValue( 103 , ( 0.569 , 0.569 , 0.737 ,1.0))
L1table.SetTableValue( 104 , ( 0.573 , 0.573 , 0.733 ,1.0))
L1table.SetTableValue( 105 , ( 0.576 , 0.576 , 0.733 ,1.0))
L1table.SetTableValue( 106 , ( 0.576 , 0.576 , 0.733 ,1.0))
L1table.SetTableValue( 107 , ( 0.580 , 0.580 , 0.729 ,1.0))
L1table.SetTableValue( 108 , ( 0.584 , 0.584 , 0.729 ,1.0))
L1table.SetTableValue( 109 , ( 0.584 , 0.584 , 0.729 ,1.0))
L1table.SetTableValue( 110 , ( 0.588 , 0.588 , 0.725 ,1.0))
L1table.SetTableValue( 111 , ( 0.592 , 0.592 , 0.725 ,1.0))
L1table.SetTableValue( 112 , ( 0.596 , 0.596 , 0.725 ,1.0))
L1table.SetTableValue( 113 , ( 0.596 , 0.596 , 0.722 ,1.0))
L1table.SetTableValue( 114 , ( 0.600 , 0.600 , 0.722 ,1.0))
L1table.SetTableValue( 115 , ( 0.604 , 0.604 , 0.722 ,1.0))
L1table.SetTableValue( 116 , ( 0.604 , 0.604 , 0.718 ,1.0))
L1table.SetTableValue( 117 , ( 0.608 , 0.608 , 0.718 ,1.0))
L1table.SetTableValue( 118 , ( 0.612 , 0.612 , 0.714 ,1.0))
L1table.SetTableValue( 119 , ( 0.616 , 0.616 , 0.714 ,1.0))
L1table.SetTableValue( 120 , ( 0.616 , 0.616 , 0.714 ,1.0))
L1table.SetTableValue( 121 , ( 0.620 , 0.620 , 0.710 ,1.0))
L1table.SetTableValue( 122 , ( 0.624 , 0.624 , 0.710 ,1.0))
L1table.SetTableValue( 123 , ( 0.624 , 0.624 , 0.710 ,1.0))
L1table.SetTableValue( 124 , ( 0.627 , 0.627 , 0.706 ,1.0))
L1table.SetTableValue( 125 , ( 0.631 , 0.631 , 0.706 ,1.0))
L1table.SetTableValue( 126 , ( 0.635 , 0.635 , 0.706 ,1.0))
L1table.SetTableValue( 127 , ( 0.635 , 0.635 , 0.702 ,1.0))
L1table.SetTableValue( 128 , ( 0.639 , 0.639 , 0.702 ,1.0))
L1table.SetTableValue( 129 , ( 0.643 , 0.643 , 0.698 ,1.0))
L1table.SetTableValue( 130 , ( 0.643 , 0.643 , 0.698 ,1.0))
L1table.SetTableValue( 131 , ( 0.647 , 0.647 , 0.698 ,1.0))
L1table.SetTableValue( 132 , ( 0.651 , 0.651 , 0.694 ,1.0))
L1table.SetTableValue( 133 , ( 0.655 , 0.655 , 0.694 ,1.0))
L1table.SetTableValue( 134 , ( 0.655 , 0.655 , 0.690 ,1.0))
L1table.SetTableValue( 135 , ( 0.659 , 0.659 , 0.690 ,1.0))
L1table.SetTableValue( 136 , ( 0.663 , 0.663 , 0.690 ,1.0))
L1table.SetTableValue( 137 , ( 0.663 , 0.663 , 0.686 ,1.0))
L1table.SetTableValue( 138 , ( 0.667 , 0.667 , 0.686 ,1.0))
L1table.SetTableValue( 139 , ( 0.671 , 0.671 , 0.682 ,1.0))
L1table.SetTableValue( 140 , ( 0.675 , 0.675 , 0.682 ,1.0))
L1table.SetTableValue( 141 , ( 0.675 , 0.675 , 0.678 ,1.0))
L1table.SetTableValue( 142 , ( 0.678 , 0.678 , 0.678 ,1.0))
L1table.SetTableValue( 143 , ( 0.682 , 0.682 , 0.678 ,1.0))
L1table.SetTableValue( 144 , ( 0.682 , 0.682 , 0.675 ,1.0))
L1table.SetTableValue( 145 , ( 0.686 , 0.686 , 0.675 ,1.0))
L1table.SetTableValue( 146 , ( 0.690 , 0.690 , 0.671 ,1.0))
L1table.SetTableValue( 147 , ( 0.694 , 0.694 , 0.671 ,1.0))
L1table.SetTableValue( 148 , ( 0.694 , 0.694 , 0.667 ,1.0))
L1table.SetTableValue( 149 , ( 0.698 , 0.698 , 0.667 ,1.0))
L1table.SetTableValue( 150 , ( 0.702 , 0.702 , 0.663 ,1.0))
L1table.SetTableValue( 151 , ( 0.702 , 0.702 , 0.663 ,1.0))
L1table.SetTableValue( 152 , ( 0.706 , 0.706 , 0.659 ,1.0))
L1table.SetTableValue( 153 , ( 0.710 , 0.710 , 0.659 ,1.0))
L1table.SetTableValue( 154 , ( 0.710 , 0.710 , 0.655 ,1.0))
L1table.SetTableValue( 155 , ( 0.714 , 0.714 , 0.655 ,1.0))
L1table.SetTableValue( 156 , ( 0.718 , 0.718 , 0.651 ,1.0))
L1table.SetTableValue( 157 , ( 0.722 , 0.722 , 0.651 ,1.0))
L1table.SetTableValue( 158 , ( 0.722 , 0.722 , 0.647 ,1.0))
L1table.SetTableValue( 159 , ( 0.725 , 0.725 , 0.647 ,1.0))
L1table.SetTableValue( 160 , ( 0.729 , 0.729 , 0.643 ,1.0))
L1table.SetTableValue( 161 , ( 0.729 , 0.729 , 0.643 ,1.0))
L1table.SetTableValue( 162 , ( 0.733 , 0.733 , 0.639 ,1.0))
L1table.SetTableValue( 163 , ( 0.737 , 0.737 , 0.639 ,1.0))
L1table.SetTableValue( 164 , ( 0.741 , 0.741 , 0.635 ,1.0))
L1table.SetTableValue( 165 , ( 0.741 , 0.741 , 0.635 ,1.0))
L1table.SetTableValue( 166 , ( 0.745 , 0.745 , 0.631 ,1.0))
L1table.SetTableValue( 167 , ( 0.749 , 0.749 , 0.631 ,1.0))
L1table.SetTableValue( 168 , ( 0.749 , 0.749 , 0.627 ,1.0))
L1table.SetTableValue( 169 , ( 0.753 , 0.753 , 0.624 ,1.0))
L1table.SetTableValue( 170 , ( 0.757 , 0.757 , 0.624 ,1.0))
L1table.SetTableValue( 171 , ( 0.761 , 0.761 , 0.620 ,1.0))
L1table.SetTableValue( 172 , ( 0.761 , 0.761 , 0.620 ,1.0))
L1table.SetTableValue( 173 , ( 0.765 , 0.765 , 0.616 ,1.0))
L1table.SetTableValue( 174 , ( 0.769 , 0.769 , 0.616 ,1.0))
L1table.SetTableValue( 175 , ( 0.769 , 0.769 , 0.612 ,1.0))
L1table.SetTableValue( 176 , ( 0.773 , 0.773 , 0.608 ,1.0))
L1table.SetTableValue( 177 , ( 0.776 , 0.776 , 0.608 ,1.0))
L1table.SetTableValue( 178 , ( 0.780 , 0.780 , 0.604 ,1.0))
L1table.SetTableValue( 179 , ( 0.780 , 0.780 , 0.600 ,1.0))
L1table.SetTableValue( 180 , ( 0.784 , 0.784 , 0.600 ,1.0))
L1table.SetTableValue( 181 , ( 0.788 , 0.788 , 0.596 ,1.0))
L1table.SetTableValue( 182 , ( 0.788 , 0.788 , 0.592 ,1.0))
L1table.SetTableValue( 183 , ( 0.792 , 0.792 , 0.592 ,1.0))
L1table.SetTableValue( 184 , ( 0.796 , 0.796 , 0.588 ,1.0))
L1table.SetTableValue( 185 , ( 0.800 , 0.800 , 0.584 ,1.0))
L1table.SetTableValue( 186 , ( 0.800 , 0.800 , 0.584 ,1.0))
L1table.SetTableValue( 187 , ( 0.804 , 0.804 , 0.580 ,1.0))
L1table.SetTableValue( 188 , ( 0.808 , 0.808 , 0.576 ,1.0))
L1table.SetTableValue( 189 , ( 0.808 , 0.808 , 0.573 ,1.0))
L1table.SetTableValue( 190 , ( 0.812 , 0.812 , 0.573 ,1.0))
L1table.SetTableValue( 191 , ( 0.816 , 0.816 , 0.569 ,1.0))
L1table.SetTableValue( 192 , ( 0.820 , 0.820 , 0.565 ,1.0))
L1table.SetTableValue( 193 , ( 0.820 , 0.820 , 0.561 ,1.0))
L1table.SetTableValue( 194 , ( 0.824 , 0.824 , 0.561 ,1.0))
L1table.SetTableValue( 195 , ( 0.827 , 0.827 , 0.557 ,1.0))
L1table.SetTableValue( 196 , ( 0.827 , 0.827 , 0.553 ,1.0))
L1table.SetTableValue( 197 , ( 0.831 , 0.831 , 0.549 ,1.0))
L1table.SetTableValue( 198 , ( 0.835 , 0.835 , 0.545 ,1.0))
L1table.SetTableValue( 199 , ( 0.839 , 0.839 , 0.541 ,1.0))
L1table.SetTableValue( 200 , ( 0.839 , 0.839 , 0.541 ,1.0))
L1table.SetTableValue( 201 , ( 0.843 , 0.843 , 0.537 ,1.0))
L1table.SetTableValue( 202 , ( 0.847 , 0.847 , 0.533 ,1.0))
L1table.SetTableValue( 203 , ( 0.847 , 0.847 , 0.529 ,1.0))
L1table.SetTableValue( 204 , ( 0.851 , 0.851 , 0.525 ,1.0))
L1table.SetTableValue( 205 , ( 0.855 , 0.855 , 0.522 ,1.0))
L1table.SetTableValue( 206 , ( 0.859 , 0.859 , 0.518 ,1.0))
L1table.SetTableValue( 207 , ( 0.859 , 0.859 , 0.514 ,1.0))
L1table.SetTableValue( 208 , ( 0.863 , 0.863 , 0.510 ,1.0))
L1table.SetTableValue( 209 , ( 0.867 , 0.867 , 0.506 ,1.0))
L1table.SetTableValue( 210 , ( 0.867 , 0.867 , 0.502 ,1.0))
L1table.SetTableValue( 211 , ( 0.871 , 0.871 , 0.498 ,1.0))
L1table.SetTableValue( 212 , ( 0.875 , 0.875 , 0.494 ,1.0))
L1table.SetTableValue( 213 , ( 0.878 , 0.878 , 0.490 ,1.0))
L1table.SetTableValue( 214 , ( 0.878 , 0.878 , 0.486 ,1.0))
L1table.SetTableValue( 215 , ( 0.882 , 0.882 , 0.482 ,1.0))
L1table.SetTableValue( 216 , ( 0.886 , 0.886 , 0.478 ,1.0))
L1table.SetTableValue( 217 , ( 0.886 , 0.886 , 0.475 ,1.0))
L1table.SetTableValue( 218 , ( 0.890 , 0.890 , 0.467 ,1.0))
L1table.SetTableValue( 219 , ( 0.894 , 0.894 , 0.463 ,1.0))
L1table.SetTableValue( 220 , ( 0.898 , 0.898 , 0.459 ,1.0))
L1table.SetTableValue( 221 , ( 0.898 , 0.898 , 0.455 ,1.0))
L1table.SetTableValue( 222 , ( 0.902 , 0.902 , 0.447 ,1.0))
L1table.SetTableValue( 223 , ( 0.906 , 0.906 , 0.443 ,1.0))
L1table.SetTableValue( 224 , ( 0.910 , 0.910 , 0.439 ,1.0))
L1table.SetTableValue( 225 , ( 0.910 , 0.910 , 0.431 ,1.0))
L1table.SetTableValue( 226 , ( 0.914 , 0.914 , 0.427 ,1.0))
L1table.SetTableValue( 227 , ( 0.918 , 0.918 , 0.420 ,1.0))
L1table.SetTableValue( 228 , ( 0.918 , 0.918 , 0.416 ,1.0))
L1table.SetTableValue( 229 , ( 0.922 , 0.922 , 0.408 ,1.0))
L1table.SetTableValue( 230 , ( 0.925 , 0.925 , 0.404 ,1.0))
L1table.SetTableValue( 231 , ( 0.929 , 0.929 , 0.396 ,1.0))
L1table.SetTableValue( 232 , ( 0.929 , 0.929 , 0.392 ,1.0))
L1table.SetTableValue( 233 , ( 0.933 , 0.933 , 0.384 ,1.0))
L1table.SetTableValue( 234 , ( 0.937 , 0.937 , 0.376 ,1.0))
L1table.SetTableValue( 235 , ( 0.937 , 0.937 , 0.369 ,1.0))
L1table.SetTableValue( 236 , ( 0.941 , 0.941 , 0.361 ,1.0))
L1table.SetTableValue( 237 , ( 0.945 , 0.945 , 0.357 ,1.0))
L1table.SetTableValue( 238 , ( 0.949 , 0.949 , 0.349 ,1.0))
L1table.SetTableValue( 239 , ( 0.949 , 0.949 , 0.337 ,1.0))
L1table.SetTableValue( 240 , ( 0.953 , 0.953 , 0.329 ,1.0))
L1table.SetTableValue( 241 , ( 0.957 , 0.957 , 0.322 ,1.0))
L1table.SetTableValue( 242 , ( 0.961 , 0.961 , 0.314 ,1.0))
L1table.SetTableValue( 243 , ( 0.961 , 0.961 , 0.302 ,1.0))
L1table.SetTableValue( 244 , ( 0.965 , 0.965 , 0.290 ,1.0))
L1table.SetTableValue( 245 , ( 0.969 , 0.969 , 0.282 ,1.0))
L1table.SetTableValue( 246 , ( 0.969 , 0.969 , 0.271 ,1.0))
L1table.SetTableValue( 247 , ( 0.973 , 0.973 , 0.255 ,1.0))
L1table.SetTableValue( 248 , ( 0.976 , 0.976 , 0.243 ,1.0))
L1table.SetTableValue( 249 , ( 0.980 , 0.980 , 0.227 ,1.0))
L1table.SetTableValue( 250 , ( 0.980 , 0.980 , 0.212 ,1.0))
L1table.SetTableValue( 251 , ( 0.984 , 0.984 , 0.192 ,1.0))
L1table.SetTableValue( 252 , ( 0.988 , 0.988 , 0.173 ,1.0))
L1table.SetTableValue( 253 , ( 0.992 , 0.992 , 0.145 ,1.0))
L1table.SetTableValue( 254 , ( 0.992 , 0.992 , 0.110 ,1.0))
L1table.SetTableValue( 255 , ( 0.996 , 0.996 , 0.051 ,1.0))
L1table.Build()
self.Linear_BlueToYellow[key] = L1table
return self.Linear_BlueToYellow[key]
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
"""Utility methods for vtk_kit module kit.
@author Charl P. Botha <http://cpbotha.net/>
"""
import vtk
class DVOrientationWidget:
"""Convenience class for embedding orientation widget in any
renderwindowinteractor. If the data has DeVIDE style orientation
metadata, this class will show the little LRHFAP block, otherwise
x-y-z cursor.
"""
def __init__(self, rwi):
self._orientation_widget = vtk.vtkOrientationMarkerWidget()
self._orientation_widget.SetInteractor(rwi)
# we'll use this if there is no orientation metadata
# just a thingy with x-y-z indicators
self._axes_actor = vtk.vtkAxesActor()
# we'll use this if there is orientation metadata
self._annotated_cube_actor = aca = vtk.vtkAnnotatedCubeActor()
# configure the thing with better colours and no stupid edges
#aca.TextEdgesOff()
aca.GetXMinusFaceProperty().SetColor(1,0,0)
aca.GetXPlusFaceProperty().SetColor(1,0,0)
aca.GetYMinusFaceProperty().SetColor(0,1,0)
aca.GetYPlusFaceProperty().SetColor(0,1,0)
aca.GetZMinusFaceProperty().SetColor(0,0,1)
aca.GetZPlusFaceProperty().SetColor(0,0,1)
def close(self):
self.set_input(None)
self._orientation_widget.SetInteractor(None)
def set_input(self, input_data):
if input_data is None:
self._orientation_widget.Off()
return
ala = input_data.GetFieldData().GetArray('axis_labels_array')
if ala:
lut = list('LRPAFH')
labels = []
for i in range(6):
labels.append(lut[ala.GetValue(i)])
self._set_annotated_cube_actor_labels(labels)
self._orientation_widget.Off()
self._orientation_widget.SetOrientationMarker(
self._annotated_cube_actor)
self._orientation_widget.On()
else:
self._orientation_widget.Off()
self._orientation_widget.SetOrientationMarker(
self._axes_actor)
self._orientation_widget.On()
def _set_annotated_cube_actor_labels(self, labels):
aca = self._annotated_cube_actor
aca.SetXMinusFaceText(labels[0])
aca.SetXPlusFaceText(labels[1])
aca.SetYMinusFaceText(labels[2])
aca.SetYPlusFaceText(labels[3])
aca.SetZMinusFaceText(labels[4])
aca.SetZPlusFaceText(labels[5])
###########################################################################
def vtkmip_copy(src, dst):
"""Given two vtkMedicalImageProperties instances, copy all
attributes from the one to the other.
Rather use vtkMedicalImageProperties.DeepCopy.
"""
import module_kits.vtk_kit as vk
mip_kw = vk.constants.medical_image_properties_keywords
for kw in mip_kw:
# get method objects for the getter and the setter
gmo = getattr(src, 'Get%s' % (kw,))
smo = getattr(dst, 'Set%s' % (kw,))
# from the get to the set!
smo(gmo())
def setup_renderers(renwin, fg_ren, bg_ren):
"""Utility method to configure foreground and background renderer
and insert them into different layers of the renderenwinindow.
Use this if you want an incredibly cool gradient background!
"""
# bit of code thanks to
# http://www.bioengineering-research.com/vtk/BackgroundGradient.tcl
# had to change approach though to using background renderer,
# else transparent objects don't appear, and adding flat
# shaded objects breaks the background gradient.
# =================================================================
qpts = vtk.vtkPoints()
qpts.SetNumberOfPoints(4)
qpts.InsertPoint(0, 0, 0, 0)
qpts.InsertPoint(1, 1, 0, 0)
qpts.InsertPoint(2, 1, 1, 0)
qpts.InsertPoint(3, 0, 1, 0)
quad = vtk.vtkQuad()
quad.GetPointIds().SetId(0,0)
quad.GetPointIds().SetId(1,1)
quad.GetPointIds().SetId(2,2)
quad.GetPointIds().SetId(3,3)
uc = vtk.vtkUnsignedCharArray()
uc.SetNumberOfComponents(4)
uc.SetNumberOfTuples(4)
uc.SetTuple4(0, 128, 128, 128, 255) # bottom left RGBA
uc.SetTuple4(1, 128, 128, 128, 255) # bottom right RGBA
uc.SetTuple4(2, 255, 255, 255, 255) # top right RGBA
uc.SetTuple4(3, 255, 255, 255, 255) # tob left RGBA
dta = vtk.vtkPolyData()
dta.Allocate(1,1)
dta.InsertNextCell(quad.GetCellType(), quad.GetPointIds())
dta.SetPoints(qpts)
dta.GetPointData().SetScalars(uc)
coord = vtk.vtkCoordinate()
coord.SetCoordinateSystemToNormalizedDisplay()
mapper2d = vtk.vtkPolyDataMapper2D()
mapper2d.SetInput(dta)
mapper2d.SetTransformCoordinate(coord)
actor2d = vtk.vtkActor2D()
actor2d.SetMapper(mapper2d)
actor2d.GetProperty().SetDisplayLocationToBackground()
bg_ren.AddActor(actor2d)
bg_ren.SetLayer(0) # seems to be background
bg_ren.SetInteractive(0)
fg_ren.SetLayer(1) # and foreground
renwin.SetNumberOfLayers(2)
renwin.AddRenderer(fg_ren)
renwin.AddRenderer(bg_ren)
| Python |
# $Id$
"""Mixins that are useful for classes using vtk_kit.
@author: Charl P. Botha <http://cpbotha.net/>
"""
from external.vtkPipeline.ConfigVtkObj import ConfigVtkObj
from external.vtkPipeline.vtkMethodParser import VtkMethodParser
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin # temporary
import module_utils # temporary, most of this should be in utils.
import re
import types
import utils
#########################################################################
class PickleVTKObjectsModuleMixin(object):
"""This mixin will pickle the state of all vtk objects whose binding
attribute names have been added to self._vtkObjects, e.g. if you have
a self._imageMath, '_imageMath' should be in the list.
Your module has to derive from module_base as well so that it has a
self._config!
Remember to call the __init__ of this class with the list of attribute
strings representing vtk objects that you want pickled. All the objects
have to exist and be initially configured by then.
Remember to call close() when your child class close()s.
"""
def __init__(self, vtkObjectNames):
# you have to add the NAMES of the objects that you want pickled
# to this list.
self._vtkObjectNames = vtkObjectNames
self.statePattern = re.compile ("To[A-Z0-9]")
# make sure that the state of the vtkObjectNames objects is
# encapsulated in the initial _config
self.logic_to_config()
def close(self):
# make sure we get rid of these bindings as well
del self._vtkObjectNames
def logic_to_config(self):
parser = VtkMethodParser()
for vtkObjName in self._vtkObjectNames:
# pickled data: a list with toggle_methods, state_methods and
# get_set_methods as returned by the vtkMethodParser. Each of
# these is a list of tuples with the name of the method (as
# returned by the vtkMethodParser) and the value; in the case
# of the stateMethods, we use the whole stateGroup instead of
# just a single name
vtkObjPD = [[], [], []]
vtkObj = getattr(self, vtkObjName)
parser.parse_methods(vtkObj)
# parser now has toggle_methods(), state_methods() and
# get_set_methods();
# toggle_methods: ['BlaatOn', 'AbortExecuteOn']
# state_methods: [['SetBlaatToOne', 'SetBlaatToTwo'],
# ['SetMaatToThree', 'SetMaatToFive']]
# get_set_methods: ['NumberOfThreads', 'Progress']
for method in parser.toggle_methods():
# if you query ReleaseDataFlag on a filter with 0 outputs,
# VTK yields an error
if vtkObj.GetNumberOfOutputPorts() == 0 and \
method == 'ReleaseDataFlagOn':
continue
# we need to snip the 'On' off
val = eval("vtkObj.Get%s()" % (method[:-2],))
vtkObjPD[0].append((method, val))
for stateGroup in parser.state_methods():
# we search up to the To
end = self.statePattern.search (stateGroup[0]).start ()
# so we turn SetBlaatToOne to GetBlaat
get_m = 'G'+stateGroup[0][1:end]
# we're going to have to be more clever when we set_config...
# use a similar trick to get_state in vtkMethodParser
val = eval('vtkObj.%s()' % (get_m,))
vtkObjPD[1].append((stateGroup, val))
for method in parser.get_set_methods():
val = eval('vtkObj.Get%s()' % (method,))
vtkObjPD[2].append((method, val))
# finally set the pickle data in the correct position
setattr(self._config, vtkObjName, vtkObjPD)
def config_to_logic(self):
# go through at least the attributes in self._vtkObjectNames
for vtkObjName in self._vtkObjectNames:
try:
vtkObjPD = getattr(self._config, vtkObjName)
vtkObj = getattr(self, vtkObjName)
except AttributeError:
print "PickleVTKObjectsModuleMixin: %s not available " \
"in self._config OR in self. Skipping." % (vtkObjName,)
else:
for method, val in vtkObjPD[0]:
if val:
eval('vtkObj.%s()' % (method,))
else:
# snip off the On
eval('vtkObj.%sOff()' % (method[:-2],))
for stateGroup, val in vtkObjPD[1]:
# keep on calling the methods in stategroup until
# the getter returns a value == val.
end = self.statePattern.search(stateGroup[0]).start()
getMethod = 'G'+stateGroup[0][1:end]
for i in range(len(stateGroup)):
m = stateGroup[i]
eval('vtkObj.%s()' % (m,))
tempVal = eval('vtkObj.%s()' % (getMethod,))
if tempVal == val:
# success! break out of the for loop
break
for method, val in vtkObjPD[2]:
try:
eval('vtkObj.Set%s(val)' % (method,))
except TypeError:
if type(val) in [types.TupleType, types.ListType]:
# sometimes VTK wants the separate elements
# and not the tuple / list
eval("vtkObj.Set%s(*val)"%(method,))
else:
# re-raise the exception if it wasn't a
# tuple/list
raise
#########################################################################
# note that the pickle mixin comes first, as its config_to_logic/logic_to_config
# should be chosen over that of noConfig
class SimpleVTKClassModuleBase(PickleVTKObjectsModuleMixin,
IntrospectModuleMixin,
ModuleBase):
"""Use this base to make a DeVIDE module that wraps a single VTK
object. The state of the VTK object will be saved when the network
is.
You only have to override the __init__ method and call the __init__
of this class with the desired parameters.
The __doc__ string of your module class will be replaced with the
__doc__ string of the encapsulated VTK class (and will thus be
shown if the user requests module help). If you don't want this,
call the ctor with replaceDoc=False.
inputFunctions is a list of the complete methods that have to be called
on the encapsulated VTK class, e.g. ['SetInput1(inputStream)',
'SetInput1(inputStream)']. The same goes for outputFunctions, except that
there's no inputStream involved. Use None in both cases if you want
the default to be used (SetInput(), GetOutput()).
"""
def __init__(self, module_manager, vtkObjectBinding, progressText,
inputDescriptions, outputDescriptions,
replaceDoc=True,
inputFunctions=None, outputFunctions=None):
self._viewFrame = None
self._configVtkObj = None
# first these two mixins
ModuleBase.__init__(self, module_manager)
self._theFilter = vtkObjectBinding
if replaceDoc:
myMessage = "<em>"\
"This is a special DeVIDE module that very simply " \
"wraps a single VTK class. In general, the " \
"complete state of the class will be saved along " \
"with the rest of the network. The documentation " \
"below is that of the wrapped VTK class:</em>"
self.__doc__ = '%s\n\n%s' % (myMessage, self._theFilter.__doc__)
# now that we have the object, init the pickle mixin so
# that the state of this object will be saved
PickleVTKObjectsModuleMixin.__init__(self, ['_theFilter'])
# make progress hooks for the object
module_utils.setup_vtk_object_progress(self, self._theFilter,
progressText)
self._inputDescriptions = inputDescriptions
self._outputDescriptions = outputDescriptions
self._inputFunctions = inputFunctions
self._outputFunctions = outputFunctions
def _createViewFrame(self):
parentWindow = self._module_manager.get_module_view_parent_window()
import resources.python.defaultModuleViewFrame
reload(resources.python.defaultModuleViewFrame)
dMVF = resources.python.defaultModuleViewFrame.defaultModuleViewFrame
viewFrame = module_utils.instantiate_module_view_frame(
self, self._module_manager, dMVF)
# ConfigVtkObj parent not important, we're passing frame + panel
# this should populate the sizer with a new sizer7
# params: noParent, noRenwin, vtk_obj, frame, panel
self._configVtkObj = ConfigVtkObj(None, None,
self._theFilter,
viewFrame, viewFrame.viewFramePanel)
module_utils.create_standard_object_introspection(
self, viewFrame, viewFrame.viewFramePanel,
{'Module (self)' : self}, None)
# we don't want the Execute button to be default... else stuff gets
# executed with every enter in the command window (at least in Doze)
module_utils.create_eoca_buttons(self, viewFrame,
viewFrame.viewFramePanel,
False)
self._viewFrame = viewFrame
return viewFrame
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
PickleVTKObjectsModuleMixin.close(self)
IntrospectModuleMixin.close(self)
if self._viewFrame is not None:
self._configVtkObj.close()
self._viewFrame.Destroy()
ModuleBase.close(self)
# get rid of our binding to the vtkObject
del self._theFilter
def get_output_descriptions(self):
return self._outputDescriptions
def get_output(self, idx):
# this will only every be invoked if your get_output_descriptions has
# 1 or more elements
if self._outputFunctions:
return eval('self._theFilter.%s' % (self._outputFunctions[idx],))
else:
return self._theFilter.GetOutput()
def get_input_descriptions(self):
return self._inputDescriptions
def set_input(self, idx, inputStream):
# this will only be called for a certain idx if you've specified that
# many elements in your get_input_descriptions
if self._inputFunctions:
exec('self._theFilter.%s' %
(self._inputFunctions[idx]))
else:
if idx == 0:
self._theFilter.SetInput(inputStream)
else:
self._theFilter.SetInput(idx, inputStream)
def execute_module(self):
# it could be a writer, in that case, call the Write method.
if hasattr(self._theFilter, 'Write') and \
callable(self._theFilter.Write):
self._theFilter.Write()
else:
self._theFilter.Update()
def streaming_execute_module(self):
"""All VTK classes should be streamable.
"""
# it could be a writer, in that case, call the Write method.
if hasattr(self._theFilter, 'Write') and \
callable(self._theFilter.Write):
self._theFilter.Write()
else:
self._theFilter.Update()
def view(self):
if self._viewFrame is None:
# we have an initial config populated with stuff and in sync
# with theFilter. The viewFrame will also be in sync with the
# filter
self._viewFrame = self._createViewFrame()
self._viewFrame.Show(True)
self._viewFrame.Raise()
def config_to_view(self):
# the pickleVTKObjectsModuleMixin does logic <-> config
# so when the user clicks "sync", logic_to_config is called
# which transfers picklable state from the LOGIC to the CONFIG
# then we do double the work and call update_gui, which transfers
# the same state from the LOGIC straight up to the VIEW
self._configVtkObj.update_gui()
def view_to_config(self):
# same thing here: user clicks "apply", view_to_config is called which
# zaps UI changes straight to the LOGIC. Then we have to call
# logic_to_config explicitly which brings the info back up to the
# config... i.e. view -> logic -> config
# after that, config_to_logic is called which transfers all state AGAIN
# from the config to the logic
self._configVtkObj.apply_changes()
self.logic_to_config()
#########################################################################
| Python |
medical_image_properties_keywords = [
'PatientName',
'PatientID',
'PatientAge',
'PatientSex',
'PatientBirthDate',
'ImageDate',
'ImageTime',
'ImageNumber',
'StudyDescription',
'StudyID',
'StudyDate',
'AcquisitionDate',
'SeriesNumber',
'SeriesDescription',
'Modality',
'ManufacturerModelName',
'Manufacturer',
'StationName',
'InstitutionName',
'ConvolutionKernel',
'SliceThickness',
'KVP',
'GantryTilt',
'EchoTime',
'EchoTrainLength',
'RepetitionTime',
'ExposureTime',
'XRayTubeCurrent'
]
| Python |
# $Id$
# importing this module shouldn't directly cause other large imports
# do large imports in the init() hook so that you can call back to the
# ModuleManager progress handler methods.
"""vtk_kit package driver file.
This performs all initialisation necessary to use VTK from DeVIDE. Makes
sure that all VTK classes have ErrorEvent handlers that report back to
the ModuleManager.
Inserts the following modules in sys.modules: vtk, vtkdevide.
@author: Charl P. Botha <http://cpbotha.net/>
"""
import re
import sys
import traceback
import types
VERSION = ''
def preImportVTK(progressMethod):
vtkImportList = [('vtk.common', 'VTK Common.'),
('vtk.filtering', 'VTK Filtering.'),
('vtk.io', 'VTK IO.'),
('vtk.imaging', 'VTK Imaging.'),
('vtk.graphics', 'VTK Graphics.'),
('vtk.rendering', 'VTK Rendering.'),
('vtk.hybrid', 'VTK Hybrid.'),
#('vtk.patented', 'VTK Patented.'),
('vtk', 'Other VTK symbols')]
# set the dynamic loading flags. If we don't do this, we get strange
# errors on 64 bit machines. To see this happen, comment this statement
# and then run the VTK->ITK connection test case.
oldflags = setDLFlags()
percentStep = 100.0 / len(vtkImportList)
currentPercent = 0.0
# do the imports
for module, message in vtkImportList:
currentPercent += percentStep
progressMethod(currentPercent, 'Initialising vtk_kit: %s' % (message,),
noTime=True)
exec('import %s' % (module,))
# restore previous dynamic loading flags
resetDLFlags(oldflags)
def setDLFlags():
# brought over from ITK Wrapping/CSwig/Python
# Python "help(sys.setdlopenflags)" states:
#
# setdlopenflags(...)
# setdlopenflags(n) -> None
#
# Set the flags that will be used for dlopen() calls. Among other
# things, this will enable a lazy resolving of symbols when
# importing a module, if called as sys.setdlopenflags(0) To share
# symbols across extension modules, call as
#
# sys.setdlopenflags(dl.RTLD_NOW|dl.RTLD_GLOBAL)
#
# GCC 3.x depends on proper merging of symbols for RTTI:
# http://gcc.gnu.org/faq.html#dso
#
try:
import dl
newflags = dl.RTLD_NOW|dl.RTLD_GLOBAL
except:
newflags = 0x102 # No dl module, so guess (see above).
try:
oldflags = sys.getdlopenflags()
sys.setdlopenflags(newflags)
except:
oldflags = None
return oldflags
def resetDLFlags(data):
# brought over from ITK Wrapping/CSwig/Python
# Restore the original dlopen flags.
try:
sys.setdlopenflags(data)
except:
pass
def init(module_manager, pre_import=True):
# first do the VTK pre-imports: this is here ONLY to keep the user happy
# it's not necessary for normal functioning
if pre_import:
preImportVTK(module_manager.setProgress)
# import the main module itself
# the global is so that users can also do:
# from module_kits import vtk_kit
# vtk_kit.vtk.vtkSomeFilter()
global vtk
import vtk
# and do the same for vtkdevide
global vtkdevide
import vtkdevide
# load up some generic functions into this namespace
# user can, after import of module_kits.vtk_kit, address these as
# module_kits.vtk_kit.blaat. In this case we don't need "global",
# as these are modules directly in this package.
import module_kits.vtk_kit.misc as misc
import module_kits.vtk_kit.mixins as mixins
import module_kits.vtk_kit.utils as utils
import module_kits.vtk_kit.constants as constants
import module_kits.vtk_kit.color_scales as color_scales
# setup the kit version
global VERSION
VERSION = '%s' % (vtk.vtkVersion.GetVTKVersion(),)
| Python |
# $Id$
"""Miscellaneous functions that are part of the vtk_kit.
This module is imported by vtk_kit.init() after the rest of the vtk_kit has
been initialised. To use these functions in your module code, do e.g.:
import moduleKits; moduleKits.vtk_kit.misc.flatterProp3D(obj);
@author: Charl P. Botha <http://cpbotha.net/>
"""
# this import does no harm; we go after the rest of vtk_kit has been
# initialised
import vtk
def flattenProp3D(prop3D):
"""Get rid of the UserTransform() of an actor by integrating it with
the 'main' matrix.
"""
if not prop3D.GetUserTransform():
# no flattening here, move along
return
# get the current "complete" matrix (combining internal and user)
currentMatrix = vtk.vtkMatrix4x4()
prop3D.GetMatrix(currentMatrix)
# apply it to a transform
currentTransform = vtk.vtkTransform()
currentTransform.Identity()
currentTransform.SetMatrix(currentMatrix)
# zero the prop3D UserTransform
prop3D.SetUserTransform(None)
# and set the internal matrix of the prop3D
prop3D.SetPosition(currentTransform.GetPosition())
prop3D.SetScale(currentTransform.GetScale())
prop3D.SetOrientation(currentTransform.GetOrientation())
# we should now also be able to zero the origin
#prop3D.SetOrigin(0,0,0)
def planePlaneIntersection(
planeNormal0, planeOrigin0, planeNormal1, planeOrigin1):
"""Given two plane definitions, determine the intersection line using
the method on page 233 of Graphics Gems III: 'Plane-to-Plane Intersection'
Returns tuple with lineOrigin and lineVector.
"""
# convert planes to Hessian form first:
# http://mathworld.wolfram.com/HessianNormalForm.html
# calculate p, orthogonal distance from the plane to the origin
p0 = - vtk.vtkMath.Dot(planeOrigin0, planeNormal0)
p1 = - vtk.vtkMath.Dot(planeOrigin1, planeNormal1)
# we already have n, the planeNormal
# calculate cross product
L = [0.0, 0.0, 0.0]
vtk.vtkMath.Cross(planeNormal0, planeNormal1, L)
absL = [abs(e) for e in L]
maxAbsL = max(absL)
if maxAbsL == 0.0:
raise ValueError, "Planes are almost parallel."
w = absL.index(maxAbsL)
Lw = L[w]
# we're going to set the maxLidx'th component of our lineOrigin (i.e.
# any point on the line) to 0
P = [0.0, 0.0, 0.0]
# we want either [0, 1], [1, 2] or [2, 0]
if w == 0:
u = 1
v = 2
elif w == 1:
u = 2
v = 0
else:
u = 0
v = 1
P[u] = (planeNormal0[v] * p1 - planeNormal1[v] * p0) / float(Lw)
P[v] = (planeNormal1[u] * p0 - planeNormal0[u] * p1) / float(Lw)
P[w] = 0 # just for completeness
vtk.vtkMath.Normalize(L)
return (P, L)
| Python |
# $Id: __init__.py 1945 2006-03-05 01:06:37Z cpbotha $
# importing this module shouldn't directly cause other large imports
# do large imports in the init() hook so that you can call back to the
# ModuleManager progress handler methods.
"""vtktudoss_kit package driver file.
Inserts the following modules in sys.modules: vtktudoss.
@author: Charl P. Botha <http://cpbotha.net/>
"""
import re
import sys
import types
# you have to define this
VERSION = 'SVN'
def init(theModuleManager, pre_import=True):
# import the main module itself
import vtktudoss
# I added the version variable on 20070802
try:
global VERSION
VERSION = vtktudoss.version
except AttributeError:
pass
theModuleManager.setProgress(100, 'Initialising vtktudoss_kit')
| Python |
# $Id: __init__.py 1945 2006-03-05 01:06:37Z cpbotha $
# importing this module shouldn't directly cause other large imports
# do large imports in the init() hook so that you can call back to the
# ModuleManager progress handler methods.
"""numpy_kit package driver file.
Inserts the following modules in sys.modules: numpy.
@author: Charl P. Botha <http://cpbotha.net/>
"""
import os
import re
import sys
import types
# you have to define this
VERSION = ''
def init(theModuleManager, pre_import=True):
theModuleManager.setProgress(5, 'Initialising numpy_kit: start')
# import numpy into the global namespace
global numpy
import numpy
# we add this so that modules using "import Numeric" will probably also
# work (such as the FloatCanvas)
sys.modules['Numeric'] = numpy
sys.modules['numarray'] = numpy
theModuleManager.setProgress(95, 'Initialising numpy_kit: import done')
# build up VERSION
global VERSION
VERSION = '%s' % (numpy.version.version,)
theModuleManager.setProgress(100, 'Initialising numpy_kit: complete')
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
"""sqlite_kit package driver file.
With this we make sure that sqlite3 is always packaged.
"""
VERSION = ''
def init(module_manager, pre_import=True):
global sqlite3
import sqlite3
global VERSION
VERSION = '%s (sqlite %s)' % (sqlite3.version,
sqlite3.sqlite_version)
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
import re
# map from itk type string to string
ITKTSTR_STRING = {
'C' : 'char',
'D' : 'double',
'F' : 'float',
'L' : 'long',
'S' : 'short'
}
# map from itk type sign to string
ITKTSGN_STRING = {
'U' : 'unsigned',
'S' : 'signed'
}
def get_itk_img_type_and_dim_shortstring(itk_img):
"""Return short string representing type and dimension of itk
image.
This method has been put here so that it's available to non-itk
dependent modules, such as the QuickInfo, and does not require
any access to the ITK library itself.
"""
# repr is e.g.:
# <itkImagePython.itkImageSS3; proxy of <Swig Object of type 'itkImageSS3 *' at 0x6ec1570> >
rs = repr(itk_img)
# pick out the short code
mo = re.search('^<itkImagePython.itkImage(.*);.*>', rs)
if not mo:
raise TypeError, 'This method requires an ITK image as input.'
else:
return mo.groups()[0]
def get_itk_img_type_and_dim(itk_img):
"""Returns itk image type as a tuple with ('type', 'dim',
'qualifier'), e.g. ('float', '3', 'covariant vector')
This method has been put here so that it's available to non-itk
dependent modules, such as the QuickInfo, and does not require
any access to the ITK library itself.
"""
ss = get_itk_img_type_and_dim_shortstring(itk_img)
# pull that sucker apart
# groups:
# 0: covariant / complex
# 1: vector
# 2: type shortstring
# 3: dimensions (in case of vector, doubled up)
mo = re.search('(C*)(V*)([^0-9]+)([0-9]+)', ss)
c, v, tss, dim = mo.groups()
if c and v:
qualifier = 'covariant vector'
elif c:
qualifier = 'complex'
elif v:
qualifier = 'vector'
else:
qualifier = ''
if len(tss) > 1:
sign_string = ITKTSGN_STRING[tss[0]]
type_string = ITKTSTR_STRING[tss[1]]
else:
sign_string = ''
type_string = ITKTSTR_STRING[tss[0]]
# in the case of a vector of 10-dims, does that become 1010?
if qualifier == 'vector':
dim_string = dim[0:len(dim) / 2]
else:
dim_string = dim[0]
fss = '%s %s' % (sign_string, type_string)
return (fss.strip(), dim_string, qualifier)
def get_itk_img_type_and_dim_DEPRECATED(itk_img):
"""Returns itk image type as a tuple with ('type', 'dim', 'v').
This method has been put here so that it's available to non-itk
dependent modules, such as the QuickInfo, and does not require
any access to the ITK library itself.
"""
try:
t = itk_img.this
except AttributeError, e:
raise TypeError, 'This method requires an ITK image as input.'
else:
# g will be e.g. ('float', '3') or ('unsigned_char', '2')
# note that we use the NON-greedy version so it doesn't break
# on vectors
# example strings:
# Image.F3: _f04b4f1b_p_itk__SmartPointerTitk__ImageTfloat_3u_t_t
# Image.VF33: _600e411b_p_itk__SmartPointerTitk__ImageTitk__VectorTfloat_3u_t_3u_t_t'
mo = re.search('.*itk__ImageT(.*?)_([0-9]+)u*_t',
itk_img.this)
if not mo:
raise TypeError, 'This method requires an ITK Image as input.'
else:
g = mo.groups()
# see if it's a vector
if g[0].startswith('itk__VectorT'):
vectorString = 'V'
# it's a vector, so let's remove the 'itk__VectorT' bit
g = list(g)
g[0] = g[0][len('itk__VectorT'):]
g = tuple(g)
else:
vectorString = ''
# this could also be ('float', '3', 'V'), or ('unsigned_char', '2', '')
return g + (vectorString,)
def major_axis_from_iop_cosine(iop_cosine):
"""Given an IOP direction cosine, i.e. either the row or column,
return a tuple with two components from LRPAFH signifying the
direction of the cosine. For example, if the cosine is pointing from
Left to Right (1\0\0) we return ('L', 'R').
If the direction cosine is NOT aligned with any of the major axes,
we return None.
Based on a routine from dclunie's pixelmed software and info from
http://www.itk.org/pipermail/insight-users/2003-September/004762.html
but we've flipped some things around to make more sense.
IOP direction cosines are always in the LPH coordinate system (patient-relative):
* x is right to left
* y is anterior to posterior
* z is foot to head
"""
obliquity_threshold = 0.8
orientation_x = [('L', 'R'), ('R', 'L')][int(iop_cosine[0] > 0)]
orientation_y = [('P', 'A'), ('A', 'P')][int(iop_cosine[1] > 0)]
orientation_z = [('H', 'F'), ('F', 'H')][int(iop_cosine[2] > 0)]
abs_x = abs(iop_cosine[0])
abs_y = abs(iop_cosine[1])
abs_z = abs(iop_cosine[2])
if abs_x > obliquity_threshold and abs_x > abs_y and abs_x > abs_z:
return orientation_x
elif abs_y > obliquity_threshold and abs_y > abs_x and abs_y > abs_z:
return orientation_y
elif abs_z > obliquity_threshold and abs_z > abs_x and abs_z > abs_y:
return orientation_z
else:
return None
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
class SubjectMixin(object):
def __init__(self):
# dictionary mapping from event name to list of observer
# callables
self._observers = {}
def add_observer(self, event_name, observer):
"""Add an observer to this subject.
observer is a function that takes the subject instance as parameter.
"""
try:
if not observer in self._observers[event_name]:
self._observers[event_name].append(observer)
except KeyError:
self._observers[event_name] = [observer]
def close(self):
del self._observers
def notify(self, event_name):
try:
for observer in self._observers[event_name]:
if callable(observer):
# call observer with the observed subject as param
observer(self)
except KeyError:
# it could be that there are no observers for this event,
# in which case we just shut up
pass
def remove_observer(self, event_name, observer):
self._observers[event_name].remove(observer)
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
class MedicalMetaData:
def __init__(self):
self.medical_image_properties = None
self.direction_cosines = None
def close(self):
del self.medical_image_properties
del self.direction_cosines
def deep_copy(self, source_mmd):
"""Given another MedicalMetaData instance source_mmd, copy its
contents to this instance.
"""
if not source_mmd is None:
self.medical_image_properties.DeepCopy(
source_mmd.medical_image_properties)
self.direction_cosines.DeepCopy(
source_mmd.direction_cosines)
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
import sys
VERSION = 'INTEGRATED'
# debug print command: if DEBUG is true, outputs to stdout, if not
# then outputs nothing.
# import with: from module_kits.misc_kit import dprint
DEBUG=False
if DEBUG:
def dprint(*msg):
print msg
else:
def dprint(*msg):
pass
def init(module_manager, pre_import=True):
global misc_utils
import misc_utils
global mixins
import mixins
global types
module_manager.set_progress(100, 'Initialising misc_kit: complete.')
| Python |
# $Id: __init__.py 1945 2006-03-05 01:06:37Z cpbotha $
# importing this module shouldn't directly cause other large imports
# do large imports in the init() hook so that you can call back to the
# ModuleManager progress handler methods.
"""itktudoss_kit package driver file.
This driver makes sure that itktudoss has been integrated with the main WrapITK
instalation.
@author: Charl P. Botha <http://cpbotha.net/>
"""
import re
import sys
import types
# you have to define this
VERSION = 'SVN'
def init(theModuleManager, pre_import=True):
theModuleManager.setProgress(80, 'Initialising itktudoss_kit: TPGAC')
import itk # this will have been pre-imported by the itk_kit
a = itk.TPGACLevelSetImageFilter
theModuleManager.setProgress(100, 'Initialising itktudoss_kit: DONE')
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
import ConfigParser
import glob
import os
import sys
import time
"""Top-level __init__ of the module_kits.
All .mkd files in the module_kits directory are parsed and their
corresponding module_kits are loaded. MKD specify the priority (order
of loading), the dependencies and whether they are crucial kits or
not. Error on loading a crucial kit terminates the application, error
on loading a non-crucial kit simply notifies the user.
"""
module_kit_list = []
class MKDef:
def __init__(self):
self.name = ''
self.crucial = False
self.priority = 100
self.dependencies = []
def get_sorted_mkds(module_kits_dir):
"""Given the module_kits dir, return list, sorted according to
priority, of MKDef instances representing the mkd files that are
found and parsed. NoKits are NOT removed yet.
"""
mkd_fnames = glob.glob(
os.path.join(module_kits_dir, '*.mkd'))
mkd_defaults = {
'crucial' : False,
'priority' : 100,
'dependencies' : ''
}
mkds = []
for mkd_fname in mkd_fnames:
mkd = MKDef()
cp = ConfigParser.ConfigParser(mkd_defaults)
cp.read(mkd_fname)
mkd.name = os.path.splitext(os.path.basename(mkd_fname))[0]
mkd.crucial = cp.getboolean('default', 'crucial')
mkd.priority = cp.getint('default', 'priority')
mkd.dependencies = [i.strip()
for i in cp.get('default', 'dependencies').split(',')
if i]
mkds.append(mkd)
# now sort the mkds according to priority
def cmp(a,b):
if a.priority < b.priority:
return -1
elif a.priority > b.priority:
return 1
else:
return 0
mkds.sort(cmp)
return mkds
def load(module_manager):
tot_start_time = time.time()
module_kits_dir = os.path.join(
module_manager.get_appdir(), 'module_kits')
mkds = get_sorted_mkds(module_kits_dir)
# then remove the nokits
nokits = module_manager.get_app_main_config().nokits
mkds = [mkd for mkd in mkds
if mkd.name not in nokits]
loaded_kit_names = []
# load the remaining kits
for mkd in mkds:
# first check that all dependencies are satisfied
deps_satisfied = True
for d in mkd.dependencies:
if d not in loaded_kit_names:
deps_satisfied = False
# break out of the for loop
break
if not deps_satisfied:
# skip this iteration of the for, go to the next iteration
# (we don't want to try loading this module)
continue
start_time = time.time()
try:
# import module_kit into module_kits namespace
exec('import module_kits.%s' % (mkd.name,))
# call module_kit.init()
getattr(module_kits, mkd.name).init(module_manager)
# add it to the loaded_kits for dependency checking
loaded_kit_names.append(mkd.name)
except Exception, e:
# if it's a crucial module_kit, we re-raise with our own
# message added using th three argument raise form
# see: http://docs.python.org/ref/raise.html
if mkd.crucial:
es = 'Error loading required module_kit %s: %s.' \
% (mkd.name, str(e))
raise Exception, es, sys.exc_info()[2]
# if not we can report the error and continue
else:
module_manager.log_error_with_exception(
'Unable to load non-critical module_kit %s: '
'%s. Continuing with startup.' %
(mkd.name, str(e)))
end_time = time.time()
module_manager.log_info('Loaded %s in %.2f seconds.' %
(mkd.name, end_time - start_time))
# if we got this far, startup was successful, but not all kits
# were loaded: some not due to failure, and some not due to
# unsatisfied dependencies. set the current list to the list of
# module_kits that did actually load.
global module_kit_list
module_kit_list = loaded_kit_names
tot_end_time = time.time()
module_manager.log_info(
'Loaded ALL module_kits in %.2f seconds.' %
(tot_end_time - tot_start_time))
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
import gdcm
def sort_ipp(filenames):
"""STOP PRESS. This is currently incomplete. I'm waiting to see
what's going to happen with the IPPSorter in GDCM.
Given a list of filenames, make use of the gdcm scanner to sort
them all according to IPP.
@param filenames: list of full pathnames that you want to have
sorted.
@returns: tuple with (average z space,
"""
s = gdcm.Scanner()
# we need the IOP and the IPP tags
iop_tag = gdcm.Tag(0x0020, 0x0037)
s.AddTag(iop_tag)
ipp_tag = gdcm.Tag(0x0020, 0x0032)
s.AddTag(ipp_tag)
ret = s.Scan(filenames)
if not ret:
return (0, [])
for f in filenames:
mapping = s.GetMapping(f)
pttv = gdcm.PythonTagToValue(mapping)
pttv.Start()
while not pttv.IsAtEnd():
tag = pttv.GetCurrentTag()
val = pttv.GetCurrentValue()
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
"""gdcm_kit driver module.
This pre-loads GDCM2, the second generation Grass Roots Dicom library,
used since 2008 by DeVIDE for improved DICOM loading / saving support.
"""
import os
import sys
VERSION = ''
def init(module_manager, pre_import=True):
# as of 20080628, the order of importing vtkgdcm and gdcm IS
# important on Linux. vtkgdcm needs to go before gdcm, else very
# strange things happen due to the dl (dynamic loading) switches.
global vtkgdcm
import vtkgdcm
global gdcm
import gdcm
# since 2.0.9, we do the following to locate part3.xml:
if hasattr(sys, 'frozen') and sys.frozen:
g = gdcm.Global.GetInstance()
# devide.spec puts Part3.xml in devide_dir/gdcmdata/XML/
g.Prepend(os.path.join(
module_manager.get_appdir(), 'gdcmdata','XML'))
if not g.LoadResourcesFiles():
raise RuntimeError('Could not setup GDCM resource files.')
# will be available as module_kits.gdcm_kit.utils after the client
# programmer has done module_kits.gdcm_kit
import module_kits.gdcm_kit.utils
global VERSION
VERSION = gdcm.Version.GetVersion()
module_manager.set_progress(100, 'Initialising gdcm_kit: complete.')
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
import itk
import re
from module_kits.misc_kit.misc_utils import get_itk_img_type_and_dim
from module_kits.misc_kit.misc_utils import \
get_itk_img_type_and_dim_shortstring
get_img_type_and_dim = get_itk_img_type_and_dim
get_img_type_and_dim_shortstring = \
get_itk_img_type_and_dim_shortstring
def coordinates_to_vector_container(points, initial_distance=0):
"""Convert list of 3-D index coordinates to an ITK
VectorContainer for use with the FastMarching filter.
@param points: Python iterable containing 3-D index (integer)
coordinates.
@param initial_distance: Initial distance that will be set on
these nodes for the fast marching.
"""
vc = itk.VectorContainer[itk.UI,
itk.LevelSetNode[itk.F, 3]].New()
# this will clear it
vc.Initialize()
for pt_idx, pt in enumerate(points):
# cast each coordinate element to integer
x,y,z = [int(e) for e in pt]
idx = itk.Index[3]()
idx.SetElement(0, x)
idx.SetElement(1, y)
idx.SetElement(2, z)
node = itk.LevelSetNode[itk.F, 3]()
node.SetValue(initial_distance)
node.SetIndex(idx)
vc.InsertElement(pt_idx, node)
return vc
def setup_itk_object_progress(dvModule, obj, nameOfObject, progressText,
objEvals=None, module_manager=None):
"""
@param dvModlue: instance containing binding to obj. Usually this
is a DeVIDE module. If not, remember to pass module_manager
parameter.
@param obj: The ITK object that needs to be progress updated.
@param module_manager: If set, will be used as binding to
module_manager. If set to None, dvModule._module_manager will be
used. This can be used in cases when obj is NOT a member of a
DeVIDE module, iow when dvModule is not a DeVIDE module.
"""
# objEvals is on optional TUPLE of obj attributes that will be called
# at each progress callback and filled into progressText via the Python
# % operator. In other words, all string attributes in objEvals will be
# eval'ed on the object instance and these values will be filled into
# progressText, which has to contain the necessary number of format tokens
# first we have to find the attribute of dvModule that binds
# to obj. We _don't_ want to have a binding to obj hanging around
# in our callable, because this means that the ITK object can never
# be destroyed. Instead we look up the binding everytime the callable
# is invoked by making use of getattr on the devideModule binding.
# find attribute string of obj in dvModule
di = dvModule.__dict__.items()
objAttrString = None
for key, value in di:
if value is obj:
objAttrString = key
break
if not objAttrString:
raise Exception, 'Could not determine attribute string for ' \
'object %s.' % (obj.__class__.__name__)
if module_manager is None:
mm = dvModule._module_manager
else:
mm = module_manager
# sanity check objEvals
if type(objEvals) != type(()) and objEvals != None:
raise TypeError, 'objEvals should be a tuple or None.'
def commandCallable():
# setup for and get values of all requested objEvals
values = []
if type(objEvals) == type(()):
for objEval in objEvals:
values.append(
eval('dvModule.%s.%s' % (objAttrString, objEval)))
values = tuple(values)
# do the actual callback
mm.generic_progress_callback(getattr(dvModule, objAttrString),
nameOfObject, getattr(dvModule, objAttrString).GetProgress(),
progressText % values)
# get rid of all bindings
del values
pc = itk.PyCommand.New()
pc.SetCommandCallable(commandCallable)
res = obj.AddObserver(itk.ProgressEvent(), pc)
# we DON'T have to store a binding to the PyCommand; during AddObserver,
# the ITK object makes its own copy. The ITK object will also take care
# of destroying the observer when it (the ITK object) is destroyed
#obj.progressPyCommand = pc
setupITKObjectProgress = setup_itk_object_progress
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
"""itk_kit package driver file.
Inserts the following modules in sys.modules: itk, InsightToolkit.
@author: Charl P. Botha <http://cpbotha.net/>
"""
import os
import re
import sys
VERSION = ''
def setDLFlags():
# brought over from ITK Wrapping/CSwig/Python
# Python "help(sys.setdlopenflags)" states:
#
# setdlopenflags(...)
# setdlopenflags(n) -> None
#
# Set the flags that will be used for dlopen() calls. Among other
# things, this will enable a lazy resolving of symbols when
# importing a module, if called as sys.setdlopenflags(0) To share
# symbols across extension modules, call as
#
# sys.setdlopenflags(dl.RTLD_NOW|dl.RTLD_GLOBAL)
#
# GCC 3.x depends on proper merging of symbols for RTTI:
# http://gcc.gnu.org/faq.html#dso
#
try:
import dl
newflags = dl.RTLD_NOW|dl.RTLD_GLOBAL
except:
newflags = 0x102 # No dl module, so guess (see above).
try:
oldflags = sys.getdlopenflags()
sys.setdlopenflags(newflags)
except:
oldflags = None
return oldflags
def resetDLFlags(data):
# brought over from ITK Wrapping/CSwig/Python
# Restore the original dlopen flags.
try:
sys.setdlopenflags(data)
except:
pass
def init(theModuleManager, pre_import=True):
if hasattr(sys, 'frozen') and sys.frozen:
# if we're frozen, make sure we grab the wrapitk contained in this kit
p1 = os.path.dirname(__file__)
p2 = os.path.join(p1, os.path.join('wrapitk', 'python'))
p3 = os.path.join(p1, os.path.join('wrapitk', 'lib'))
sys.path.insert(0, p2)
sys.path.insert(0, p3)
# and now the LD_LIBRARY_PATH / PATH
if sys.platform == 'win32':
so_path_key = 'PATH'
else:
so_path_key = 'LD_LIBRARY_PATH'
# this doesn't work on Linux in anycase
if so_path_key in os.environ:
os.environ[so_path_key] = '%s%s%s' % \
(p3, os.pathsep, os.environ[so_path_key])
else:
os.environ[so_path_key] = p3
# with WrapITK, this takes almost no time
import itk
theModuleManager.setProgress(5, 'Initialising ITK: start')
# let's get the version (which will bring in VXLNumerics and Base)
# setup the kit version
global VERSION
isv = itk.Version.GetITKSourceVersion()
ind = re.match('.*Date: ([0-9]+-[0-9]+-[0-9]+).*', isv).group(1)
VERSION = '%s (%s)' % (itk.Version.GetITKVersion(), ind)
theModuleManager.setProgress(45, 'Initialising ITK: VXLNumerics, Base')
if pre_import:
# then ItkVtkGlue (at the moment this is fine, VTK is always there;
# keep in mind for later when we allow VTK-less startups)
a = itk.VTKImageToImageFilter
theModuleManager.setProgress(
75,
'Initialising ITK: BaseTransforms, SimpleFilters, ItkVtkGlue')
# user can address this as module_kits.itk_kit.utils.blaat()
import module_kits.itk_kit.utils as utils
theModuleManager.setProgress(100, 'Initialising ITK: DONE')
| Python |
# dummy
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
import ConfigParser
import sys, os, fnmatch
import re
import copy
import gen_utils
import glob
from meta_module import MetaModule
import modules
import mutex
from random import choice
from module_base import DefaultConfigClass
import time
import types
import traceback
# some notes with regards to extra module state/logic required for scheduling
# * in general, execute_module()/transfer_output()/etc calls do exactly that
# when called, i.e. they don't automatically cache. The scheduler should
# take care of caching by making the necessary isModified() or
# shouldTransfer() calls. The reason for this is so that the module
# actions can be forced
#
# notes with regards to execute on change:
# * devide.py should register a "change" handler with the ModuleManager.
# I've indicated places with "execute on change" where I think this
# handler should be invoked. devide.py can then invoke the scheduler.
#########################################################################
class ModuleManagerException(Exception):
pass
#########################################################################
class ModuleSearch:
"""Class for doing relative fast searches through module metadata.
@author Charl P. Botha <http://cpbotha.net/>
"""
def __init__(self):
# dict of dicts of tuple, e.g.:
# {'isosurface' : {('contour', 'keywords') : 1,
# ('marching', 'help') : 1} ...
self.search_dict = {}
self.previous_partial_text = ''
self.previous_results = None
def build_search_index(self, available_modules, available_segments):
"""Build search index given a list of available modules and segments.
@param available_modules: available modules dictionary from module
manager with module metadata classes as values.
@param available_segments: simple list of segments.
"""
self.search_dict.clear()
def index_field(index_name, mi_class, field_name, split=False):
try:
field = getattr(mi_class, field_name)
except AttributeError:
pass
else:
if split:
iter_list = field.split()
else:
iter_list = field
for w in iter_list:
wl = w.lower()
if wl not in self.search_dict:
self.search_dict[wl] = {(index_name,
field_name) : 1}
else:
self.search_dict[wl][(index_name,
field_name)] = 1
for module_name in available_modules:
mc = available_modules[module_name]
index_name = 'module:%s' % (module_name,)
short_module_name = mc.__name__.lower()
if short_module_name not in self.search_dict:
self.search_dict[short_module_name] = {(index_name, 'name') :
1}
else:
# we don't have to increment, there can be only one unique
# complete module_name
self.search_dict[short_module_name][(index_name, 'name')] = 1
index_field(index_name, mc, 'keywords')
index_field(index_name, mc, 'help', True)
for segment_name in available_segments:
index_name = 'segment:%s' % (segment_name,)
# segment name's are unique by definition (complete file names)
self.search_dict[segment_name] = {(index_name, 'name') : 1}
def find_matches(self, partial_text):
"""Do partial text (containment) search through all module names,
help and keywords.
Simple caching is currently done. Each space-separated word in
partial_text is searched for and results are 'AND'ed.
@returns: a list of unique tuples consisting of (modulename,
where_found) where where_found is 'name', 'keywords' or 'help'
"""
# cache results in case the user asks for exactly the same
if partial_text == self.previous_partial_text:
return self.previous_results
partial_words = partial_text.lower().split()
# dict mapping from full.module.name -> {'where_found' : 1, 'wf2' : 1}
# think about optimising this with a bit mask rather; less flexible
# but saves space and is at least as fast.
def find_one_word(search_word):
"""Searches for all partial / containment matches with
search_word.
@returns: search_results dict mapping from module name to
dictionary with where froms as keys and 1s as values.
"""
search_results = {}
for w in self.search_dict:
if w.find(search_word) >= 0:
# we can have partial matches with more than one key
# returning the same location, so we stuff results in a
# dict too to consolidate results
for k in self.search_dict[w].keys():
# k[1] is where_found, k[0] is module_name
if k[0] not in search_results:
search_results[k[0]] = {k[1] : 1}
else:
search_results[k[0]][k[1]] = 1
return search_results
# search using each of the words in the given list
search_results_list = []
for search_word in partial_words:
search_results_list.append(find_one_word(search_word))
# if more than one word, combine the results;
# a module + where_from result is only shown if ALL words occur in
# that specific module + where_from.
sr0 = search_results_list[0]
srl_len = len(search_results_list)
if srl_len > 1:
# will create brand-new combined search_results dict
search_results = {}
# iterate through all module names in the first word's results
for module_name in sr0:
# we will only process a module_name if it occurs in the
# search results of ALL search words
all_found = True
for sr in search_results_list[1:]:
if module_name not in sr:
all_found = False
break
# now only take results where ALL search words occur
# in the same where_from of a specific module
if all_found:
temp_finds = {}
for sr in search_results_list:
# sr[module_name] is a dict with where_founds as keys
# by definition (dictionary) all where_founds are
# unique per sr[module_name]
for i in sr[module_name].keys():
if i in temp_finds:
temp_finds[i] += 1
else:
temp_finds[i] = 1
# extract where_froms for which the number of hits is
# equal to the number of words.
temp_finds2 = [wf for wf in temp_finds.keys() if
temp_finds[wf] == srl_len]
# make new dictionary from temp_finds2 list as keys,
# 1 as value
search_results[module_name] = dict.fromkeys(temp_finds2,1)
else:
# only a single word was searched for.
search_results = sr0
self.previous_partial_text = partial_text
rl = search_results
self.previous_results = rl
return rl
#########################################################################
class PickledModuleState:
def __init__(self):
self.module_config = DefaultConfigClass()
# e.g. modules.Viewers.histogramSegment
self.module_name = None
# this is the unique name of the module, e.g. dvm15
self.instance_name = None
#########################################################################
class PickledConnection:
def __init__(self, source_instance_name=None, output_idx=None,
target_instance_name=None, input_idx=None, connection_type=None):
self.source_instance_name = source_instance_name
self.output_idx = output_idx
self.target_instance_name = target_instance_name
self.input_idx = input_idx
self.connection_type = connection_type
#########################################################################
class ModuleManager:
"""This class in responsible for picking up new modules in the modules
directory and making them available to the rest of the program.
@todo: we should split this functionality into a ModuleManager and
networkManager class. One ModuleManager per processing node,
global networkManager to coordinate everything.
@todo: ideally, ALL module actions should go via the MetaModule.
@author: Charl P. Botha <http://cpbotha.net/>
"""
def __init__(self, devide_app):
"""Initialise module manager by fishing .py devide modules from
all pertinent directories.
"""
self._devide_app = devide_app
# module dictionary, keyed on instance... cool.
# values are MetaModules
self._module_dict = {}
appdir = self._devide_app.get_appdir()
self._modules_dir = os.path.join(appdir, 'modules')
#sys.path.insert(0,self._modules_dir)
self._userModules_dir = os.path.join(appdir, 'userModules')
############################################################
# initialise module Kits - Kits are collections of libraries
# that modules can depend on. The Kits also make it possible
# for us to write hooks for when these libraries are imported
import module_kits
module_kits.load(self)
# binding to module that can be used without having to do
# import module_kits
self.module_kits = module_kits
##############################################################
self.module_search = ModuleSearch()
# make first scan of available modules
self.scan_modules()
# auto_execute mode, still need to link this up with the GUI
self.auto_execute = True
# this is a list of modules that have the ability to start a network
# executing all by themselves and usually do... when we break down
# a network, we should take these out first. when we build a network
# we should put them down last
# slice3dVWRs must be connected LAST, histogramSegment second to last
# and all the rest before them
self.consumerTypeTable = {'slice3dVWR' : 5,
'histogramSegment' : 4}
# we'll use this to perform mutex-based locking on the progress
# callback... (there SHOULD only be ONE ModuleManager instance)
self._inProgressCallback = mutex.mutex()
def refresh_module_kits(self):
"""Go through list of imported module kits, reload each one, and
also call its refresh() method if available.
This means a kit author can work on a module_kit and just refresh
when she wants her changes to be available. However, the kit must
have loaded successfully at startup, else no-go.
"""
for module_kit in self.module_kits.module_kit_list:
kit = getattr(self.module_kits, module_kit)
try:
refresh_method = getattr(kit, "refresh")
except AttributeError:
pass
else:
try:
reload(kit)
refresh_method()
except Exception, e:
self._devide_app.log_error_with_exception(
'Unable to refresh module_kit %s: '
'%s. Continuing...' %
(module_kit, str(e)))
else:
self.set_progress(100, 'Refreshed %s.' % (module_kit,))
def close(self):
"""Iterates through each module and closes it.
This is only called during devide application shutdown.
"""
self.delete_all_modules()
def delete_all_modules(self):
"""Deletes all modules.
This is usually only called during the offline mode of operation. In
view mode, the GraphEditor takes care of the deletion of all networks.
"""
# this is fine because .items() makes a copy of the dict
for mModule in self._module_dict.values():
print "Deleting %s (%s) >>>>>" % \
(mModule.instance_name,
mModule.instance.__class__.__name__)
try:
self.delete_module(mModule.instance)
except Exception, e:
# we can't allow a module to stop us
print "Error deleting %s (%s): %s" % \
(mModule.instance_name,
mModule.instance.__class__.__name__,
str(e))
print "FULL TRACE:"
traceback.print_exc()
def apply_module_view_to_logic(self, instance):
"""Interface method that can be used by clients to transfer module
view to underlying logic.
This is called by module_utils (the ECASH button handlers) and thunks
through to the relevant MetaModule call.
"""
mModule = self._module_dict[instance]
try:
# these two MetaModule wrapper calls will take care of setting
# the modified flag / time correctly
if self._devide_app.view_mode:
# only in view mode do we call this transfer
mModule.view_to_config()
mModule.config_to_logic()
# we round-trip so that view variables that are dependent on
# the effective changes to logic and/or config can update
instance.logic_to_config()
if self._devide_app.view_mode:
instance.config_to_view()
except Exception, e:
# we are directly reporting the error, as this is used by
# a utility function that is too compact to handle an
# exception by itself. Might change in the future.
self._devide_app.log_error_with_exception(str(e))
def sync_module_logic_with_config(self, instance):
"""Method that should be called during __init__ for all (view and
non-view) modules, after the config structure has been set.
In the view() method, or after having setup the view in view-modules,
also call syncModuleViewWithLogic()
"""
instance.config_to_logic()
instance.logic_to_config()
def sync_module_view_with_config(self, instance):
"""If DeVIDE is in view model, transfor config information to view
and back again. This is called AFTER sync_module_logic_with_config(),
usually in the module view() method after createViewFrame().
"""
if self._devide_app.view_mode:
# in this case we don't round trip, view shouldn't change
# things that affect the config.
instance.config_to_view()
def sync_module_view_with_logic(self, instance):
"""Interface method that can be used by clients to transfer config
information from the underlying module logic (model) to the view.
At the moment used by standard ECASH handlers.
"""
try:
instance.logic_to_config()
# we only do the view transfer if DeVIDE is in the correct mode
if self._devide_app.view_mode:
instance.config_to_view()
except Exception, e:
# we are directly reporting the error, as this is used by
# a utility function that is too compact to handle an
# exception by itself. Might change in the future.
self._devide_app.log_error_with_exception(str(e))
syncModuleViewWithLogic = sync_module_view_with_logic
def blockmodule(self, meta_module):
meta_module.blocked = True
def unblockmodule(self, meta_module):
meta_module.blocked = False
def log_error(self, message):
"""Convenience method that can be used by modules.
"""
self._devide_app.log_error(message)
def log_error_list(self, message_list):
self._devide_app.log_error_list(message_list)
def log_error_with_exception(self, message):
"""Convenience method that can be used by modules.
"""
self._devide_app.log_error_with_exception(message)
def log_info(self, message):
"""Convenience method that can be used by modules.
"""
self._devide_app.log_info(message)
def log_message(self, message):
"""Convenience method that can be used by modules.
"""
self._devide_app.log_message(message)
def log_warning(self, message):
"""Convenience method that can be used by modules.
"""
self._devide_app.log_warning(message)
def scan_modules(self):
"""(Re)Check the modules directory for *.py files and put them in
the list self.module_files.
"""
# this is a dict mapping from full module name to the classes as
# found in the module_index.py files
self._available_modules = {}
appDir = self._devide_app.get_appdir()
# module path without trailing slash
modulePath = self.get_modules_dir()
# search through modules hierarchy and pick up all module_index files
####################################################################
module_indices = []
def miwFunc(arg, dirname, fnames):
"""arg is top-level module path.
"""
module_path = arg
for fname in fnames:
mi_full_name = os.path.join(dirname, fname)
if not fnmatch.fnmatch(fname, 'module_index.py'):
continue
# e.g. /viewers/module_index
mi2 = os.path.splitext(
mi_full_name.replace(module_path, ''))[0]
# e.g. .viewers.module_index
mim = mi2.replace(os.path.sep, '.')
# remove . before
if mim.startswith('.'):
mim = mim[1:]
# special case: modules in the central devide
# module dir should be modules.viewers.module_index
# this is mostly for backward compatibility
if module_path == modulePath:
mim = 'modules.%s' % (mim)
module_indices.append(mim)
os.path.walk(modulePath, miwFunc, arg=modulePath)
for emp in self.get_app_main_config().extra_module_paths:
# make sure there are no extra spaces at the ends, as well
# as normalize and absolutize path (haha) for this
# platform
emp = os.path.abspath(emp.strip())
if emp and os.path.exists(emp):
# make doubly sure we only process an EMP if it's
# really there
if emp not in sys.path:
sys.path.insert(0,emp)
os.path.walk(emp, miwFunc, arg=emp)
# iterate through the moduleIndices, building up the available
# modules list.
import module_kits # we'll need this to check available kits
failed_mis = {}
for mim in module_indices:
# mim is importable module_index spec, e.g.
# modules.viewers.module_index
# if this thing was imported before, we have to remove it, else
# classes that have been removed from the module_index file
# will still appear after the reload.
if mim in sys.modules:
del sys.modules[mim]
try:
# now we can import
__import__(mim, globals(), locals())
except Exception, e:
# make a list of all failed moduleIndices
failed_mis[mim] = sys.exc_info()
msgs = gen_utils.exceptionToMsgs()
# and log them as mesages
self._devide_app.log_info(
'Error loading %s: %s.' % (mim, str(e)))
for m in msgs:
self._devide_app.log_info(m.strip(), timeStamp=False)
# we don't want to throw an exception here, as that would
# mean that a singe misconfigured module_index file can
# prevent the whole scan_modules process from completing
# so we'll report on errors here and at the end
else:
# reload, as this could be a run-time rescan
m = sys.modules[mim]
reload(m)
# find all classes in the imported module
cs = [a for a in dir(m)
if type(getattr(m,a)) == types.ClassType]
# stuff these classes, keyed on the module name that they
# represent, into the modules list.
for a in cs:
# a is the name of the class
c = getattr(m,a)
module_deps = True
for kit in c.kits:
if kit not in module_kits.module_kit_list:
module_deps = False
break
if module_deps:
module_name = mim.replace('module_index', a)
self._available_modules[module_name] = c
# we should move this functionality to the graphEditor. "segments"
# are _probably_ only valid there... alternatively, we should move
# the concept here
segmentList = []
def swFunc(arg, dirname, fnames):
segmentList.extend([os.path.join(dirname, fname)
for fname in fnames
if fnmatch.fnmatch(fname, '*.dvn')])
os.path.walk(os.path.join(appDir, 'segments'), swFunc, arg=None)
# this is purely a list of segment filenames
self.availableSegmentsList = segmentList
# self._available_modules is a dict keyed on module_name with
# module description class as value
self.module_search.build_search_index(self._available_modules,
self.availableSegmentsList)
# report on accumulated errors - this is still a non-critical error
# so we don't throw an exception.
if len(failed_mis) > 0:
failed_indices = '\n'.join(failed_mis.keys())
self._devide_app.log_error(
'The following module indices failed to load '
'(see message log for details): \n%s' \
% (failed_indices,))
self._devide_app.log_info(
'%d modules and %d segments scanned.' %
(len(self._available_modules), len(self.availableSegmentsList)))
########################################################################
def get_appdir(self):
return self._devide_app.get_appdir()
def get_app_main_config(self):
return self._devide_app.main_config
def get_available_modules(self):
"""Return the available_modules, a dictionary keyed on fully qualified
module name (e.g. modules.Readers.vtiRDR) with values the classes
defined in module_index files.
"""
return self._available_modules
def get_instance(self, instance_name):
"""Given the unique instance name, return the instance itself.
If the module doesn't exist, return None.
"""
found = False
for instance, mModule in self._module_dict.items():
if mModule.instance_name == instance_name:
found = True
break
if found:
return mModule.instance
else:
return None
def get_instance_name(self, instance):
"""Given the actual instance, return its unique instance. If the
instance doesn't exist in self._module_dict, return the currently
halfborn instance.
"""
try:
return self._module_dict[instance].instance_name
except Exception:
return self._halfBornInstanceName
def get_meta_module(self, instance):
"""Given an instance, return the corresponding meta_module.
@param instance: the instance whose meta_module should be returned.
@return: meta_module corresponding to instance.
@raise KeyError: this instance doesn't exist in the module_dict.
"""
return self._module_dict[instance]
def get_modules_dir(self):
return self._modules_dir
def get_module_view_parent_window(self):
# this could change
return self.get_module_view_parent_window()
def get_module_spec(self, module_instance):
"""Given a module instance, return the full module spec.
"""
return 'module:%s' % (module_instance.__class__.__module__,)
def get_module_view_parent_window(self):
"""Get parent window for module windows.
THIS METHOD WILL BE DEPRECATED. The ModuleManager and view-less
(back-end) modules shouldn't know ANYTHING about windows or UI
aspects.
"""
try:
return self._devide_app.get_interface().get_main_window()
except AttributeError:
# the interface has no main_window
return None
def create_module(self, fullName, instance_name=None):
"""Try and create module fullName.
@param fullName: The complete module spec below application directory,
e.g. modules.Readers.hdfRDR.
@return: module_instance if successful.
@raises ModuleManagerException: if there is a problem creating the
module.
"""
if fullName not in self._available_modules:
raise ModuleManagerException(
'%s is not available in the current Module Manager / '
'Kit configuration.' % (fullName,))
try:
# think up name for this module (we have to think this up now
# as the module might want to know about it whilst it's being
# constructed
instance_name = self._make_unique_instance_name(instance_name)
self._halfBornInstanceName = instance_name
# perform the conditional import/reload
self.import_reload(fullName)
# import_reload requires this afterwards for safety reasons
exec('import %s' % fullName)
# in THIS case, there is a McMillan hook which'll tell the
# installer about all the devide modules. :)
ae = self.auto_execute
self.auto_execute = False
try:
# then instantiate the requested class
module_instance = None
exec(
'module_instance = %s.%s(self)' % (fullName,
fullName.split('.')[-1]))
finally:
# do the following in all cases:
self.auto_execute = ae
# if there was an exception, it will now be re-raised
if hasattr(module_instance, 'PARTS_TO_INPUTS'):
pti = module_instance.PARTS_TO_INPUTS
else:
pti = None
if hasattr(module_instance, 'PARTS_TO_OUTPUTS'):
pto = module_instance.PARTS_TO_OUTPUTS
else:
pto = None
# and store it in our internal structures
self._module_dict[module_instance] = MetaModule(
module_instance, instance_name, fullName, pti, pto)
# it's now fully born ;)
self._halfBornInstanceName = None
except ImportError, e:
# we re-raise with the three argument form to retain full
# trace information.
es = "Unable to import module %s: %s" % (fullName, str(e))
raise ModuleManagerException, es, sys.exc_info()[2]
except Exception, e:
es = "Unable to instantiate module %s: %s" % (fullName, str(e))
raise ModuleManagerException, es, sys.exc_info()[2]
# return the instance
return module_instance
def import_reload(self, fullName):
"""This will import and reload a module if necessary. Use this only
for things in modules or userModules.
If we're NOT running installed, this will run import on the module.
If it's not the first time this module is imported, a reload will
be run straight after.
If we're running installed, reloading only makes sense for things in
userModules, so it's only done for these modules. At the moment,
the stock Installer reload() is broken. Even with my fixes, it doesn't
recover memory used by old modules, see:
http://trixie.triqs.com/pipermail/installer/2003-May/000303.html
This is one of the reasons we try to avoid unnecessary reloads.
You should use this as follows:
ModuleManager.import_reloadModule('full.path.to.my.module')
import full.path.to.my.module
so that the module is actually brought into the calling namespace.
import_reload used to return the modulePrefix object, but this has
been changed to force module writers to use a conventional import
afterwards so that the McMillan installer will know about dependencies.
"""
# this should yield modules or userModules
modulePrefix = fullName.split('.')[0]
# determine whether this is a new import
if not sys.modules.has_key(fullName):
newModule = True
else:
newModule = False
# import the correct module - we have to do this in anycase to
# get the thing into our local namespace
exec('import ' + fullName)
# there can only be a reload if this is not a newModule
if not newModule:
exec('reload(' + fullName + ')')
# we need to inject the import into the calling dictionary...
# importing my.module results in "my" in the dictionary, so we
# split at '.' and return the object bound to that name
# return locals()[modulePrefix]
# we DON'T do this anymore, so that module writers are forced to
# use an import statement straight after calling import_reload (or
# somewhere else in the module)
def isInstalled(self):
"""Returns True if devide is running from an Installed state.
Installed of course refers to being installed with Gordon McMillan's
Installer. This can be used by devide modules to determine whether
they should use reload or not.
"""
return hasattr(modules, '__importsub__')
def execute_module(self, meta_module, part=0, streaming=False):
"""Execute module instance.
Important: this method does not result in data being transferred
after the execution, it JUST performs the module execution. This
method is called by the scheduler during network execution. No
other call should be used to execute a single module!
@param instance: module instance to be executed.
@raise ModuleManagerException: this exception is raised with an
informative error string if a module fails to execute.
@return: Nothing.
"""
try:
# this goes via the MetaModule so that time stamps and the
# like are correctly reported
meta_module.execute_module(part, streaming)
except Exception, e:
# get details about the errored module
instance_name = meta_module.instance_name
module_name = meta_module.instance.__class__.__name__
# and raise the relevant exception
es = 'Unable to execute part %d of module %s (%s): %s' \
% (part, instance_name, module_name, str(e))
# we use the three argument form so that we can add a new
# message to the exception but we get to see the old traceback
# see: http://docs.python.org/ref/raise.html
raise ModuleManagerException, es, sys.exc_info()[2]
def execute_network(self, startingModule=None):
"""Execute local network in order, starting from startingModule.
This is a utility method used by module_utils to bind to the Execute
control found on must module UIs. We are still in the process
of formalising the concepts of networks vs. groups of modules.
Eventually, networks will be grouped by process node and whatnot.
@todo: integrate concept of startingModule.
"""
try:
self._devide_app.network_manager.execute_network(
self._module_dict.values())
except Exception, e:
# if an error occurred, but progress is not at 100% yet,
# we have to put it there, else app remains in visually
# busy state.
if self._devide_app.get_progress() < 100.0:
self._devide_app.set_progress(
100.0, 'Error during network execution.')
# we are directly reporting the error, as this is used by
# a utility function that is too compact to handle an
# exception by itself. Might change in the future.
self._devide_app.log_error_with_exception(str(e))
def view_module(self, instance):
instance.view()
def delete_module(self, instance):
"""Destroy module.
This will disconnect all module inputs and outputs and call the
close() method. This method is used by the graphEditor and by
the close() method of the ModuleManager.
@raise ModuleManagerException: if an error occurs during module
deletion.
"""
# get details about the module (we might need this later)
meta_module = self._module_dict[instance]
instance_name = meta_module.instance_name
module_name = meta_module.instance.__class__.__name__
# first disconnect all outgoing connections
inputs = self._module_dict[instance].inputs
outputs = self._module_dict[instance].outputs
# outputs is a list of lists of tuples, each tuple containing
# module_instance and input_idx of the consumer module
for output in outputs:
if output:
# we just want to walk through the dictionary tuples
for consumer in output:
# disconnect all consumers
self.disconnect_modules(consumer[0], consumer[1])
# inputs is a list of tuples, each tuple containing module_instance
# and output_idx of the producer/supplier module
for input_idx in range(len(inputs)):
try:
# also make sure we fully disconnect ourselves from
# our producers
self.disconnect_modules(instance, input_idx)
except Exception, e:
# we can't allow this to prevent a destruction, just log
self.log_error_with_exception(
'Module %s (%s) errored during disconnect of input %d. '
'Continuing with deletion.' % \
(instance_name, module_name, input_idx))
# set supplier to None - so we know it's nuked
inputs[input_idx] = None
# we've disconnected completely - let's reset all lists
self._module_dict[instance].reset_inputsOutputs()
# store autoexecute, then disable
ae = self.auto_execute
self.auto_execute = False
try:
try:
# now we can finally call close on the instance
instance.close()
finally:
# do the following in all cases:
# 1. remove module from our dict
del self._module_dict[instance]
# 2. reset auto_execute mode
self.auto_execute = ae
# the exception will now be re-raised if there was one
# to begin with.
except Exception, e:
# we're going to re-raise the exception: this method could be
# called by other parties that need to do alternative error
# handling
# create new exception message
es = 'Error calling close() on module %s (%s): %s' \
% (instance_name, module_name, str(e))
# we use the three argument form so that we can add a new
# message to the exception but we get to see the old traceback
# see: http://docs.python.org/ref/raise.html
raise ModuleManagerException, es, sys.exc_info()[2]
def connect_modules(self, output_module, output_idx,
input_module, input_idx):
"""Connect output_idx'th output of provider output_module to
input_idx'th input of consumer input_module. If an error occurs
during connection, an exception will be raised.
@param output_module: This is a module instance.
"""
# record connection (this will raise an exception if the input
# is already occupied)
self._module_dict[input_module].connectInput(
input_idx, output_module, output_idx)
# record connection on the output of the producer module
# this will also initialise the transfer times
self._module_dict[output_module].connectOutput(
output_idx, input_module, input_idx)
def disconnect_modules(self, input_module, input_idx):
"""Disconnect a consumer module from its provider.
This method will disconnect input_module from its provider by
disconnecting the link between the provider and input_module at
the input_idx'th input port of input_module.
All errors will be handled internally in this function, i.e. no
exceptions will be raised.
@todo: factor parts of this out into the MetaModule.
FIXME: continue here... (we can start converting some of
the modules to shallow copy their data; especially the slice3dVWR
is a problem child.)
"""
meta_module = self._module_dict[input_module]
instance_name = meta_module.instance_name
module_name = meta_module.instance.__class__.__name__
try:
input_module.set_input(input_idx, None)
except Exception, e:
# if the module errors during disconnect, we have no choice
# but to continue with deleting it from our metadata
# at least this way, no data transfers will be attempted during
# later network executions.
self._devide_app.log_error_with_exception(
'Module %s (%s) errored during disconnect of input %d. '
'Removing link anyway.' % \
(instance_name, module_name, input_idx))
# trace it back to our supplier, and tell it that it has one
# less consumer (if we even HAVE a supplier on this port)
s = self._module_dict[input_module].inputs[input_idx]
if s:
supp = s[0]
suppOutIdx = s[1]
self._module_dict[supp].disconnectOutput(
suppOutIdx, input_module, input_idx)
# indicate to the meta data that this module doesn't have an input
# anymore
self._module_dict[input_module].disconnectInput(input_idx)
def deserialise_module_instances(self, pmsDict, connectionList):
"""Given a pickled stream, this method will recreate all modules,
configure them and connect them up.
@returns: (newModulesDict, connectionList) - newModulesDict maps from
serialised/OLD instance name to newly created instance; newConnections
is a connectionList of the connections taht really were made during
the deserialisation.
@TODO: this should go to NetworkManager and should return meta_modules
in the dictionary, not module instances.
"""
# store and deactivate auto-execute
ae = self.auto_execute
self.auto_execute = False
# newModulesDict will act as translator between pickled instance_name
# and new instance!
newModulesDict = {}
failed_modules_dict = []
for pmsTuple in pmsDict.items():
# each pmsTuple == (instance_name, pms)
# we're only going to try to create a module if the module_man
# says it's available!
try:
newModule = self.create_module(pmsTuple[1].module_name)
except ModuleManagerException, e:
self._devide_app.log_error_with_exception(
'Could not create module %s:\n%s.' %
(pmsTuple[1].module_name, str(e)))
# make sure
newModule = None
if newModule:
# set its config!
try:
# we need to DEEP COPY the config, else it could easily
# happen that objects have bindings to the same configs!
# to see this go wrong, switch off the deepcopy, create
# a network by copying/pasting a vtkPolyData, load
# two datasets into a slice viewer... now save the whole
# thing and load it: note that the two readers are now
# reading the same file!
configCopy = copy.deepcopy(pmsTuple[1].module_config)
# the API says we have to call get_config() first,
# so that the module has another place where it
# could lazy prepare the thing (slice3dVWR does
# this)
cfg = newModule.get_config()
# now we merge the stored config with the new
# module config
cfg.__dict__.update(configCopy.__dict__)
# and then we set it back with set_config
newModule.set_config(cfg)
except Exception, e:
# it could be a module with no defined config logic
self._devide_app.log_warning(
'Could not restore state/config to module %s: %s' %
(newModule.__class__.__name__, e))
# try to rename the module to the pickled unique instance name
# if this name is already taken, use the generated unique instance
# name
self.rename_module(newModule,pmsTuple[1].instance_name)
# and record that it's been recreated (once again keyed
# on the OLD unique instance name)
newModulesDict[pmsTuple[1].instance_name] = newModule
# now we're going to connect all of the successfully created
# modules together; we iterate DOWNWARDS through the different
# consumerTypes
newConnections = []
for connection_type in range(max(self.consumerTypeTable.values()) + 1):
typeConnections = [connection for connection in connectionList
if connection.connection_type == connection_type]
for connection in typeConnections:
if newModulesDict.has_key(connection.source_instance_name) and \
newModulesDict.has_key(connection.target_instance_name):
sourceM = newModulesDict[connection.source_instance_name]
targetM = newModulesDict[connection.target_instance_name]
# attempt connecting them
print "connecting %s:%d to %s:%d..." % \
(sourceM.__class__.__name__, connection.output_idx,
targetM.__class__.__name__, connection.input_idx)
try:
self.connect_modules(sourceM, connection.output_idx,
targetM, connection.input_idx)
except:
pass
else:
newConnections.append(connection)
# now do the POST connection module config!
for oldInstanceName,newModuleInstance in newModulesDict.items():
# retrieve the pickled module state
pms = pmsDict[oldInstanceName]
# take care to deep copy the config
configCopy = copy.deepcopy(pms.module_config)
# now try to call set_configPostConnect
try:
newModuleInstance.set_configPostConnect(configCopy)
except AttributeError:
pass
except Exception, e:
# it could be a module with no defined config logic
self._devide_app.log_warning(
'Could not restore post connect state/config to module '
'%s: %s' % (newModuleInstance.__class__.__name__, e))
# reset auto_execute
self.auto_execute = ae
# we return a dictionary, keyed on OLD pickled name with value
# the newly created module-instance and a list with the connections
return (newModulesDict, newConnections)
def request_auto_execute_network(self, module_instance):
"""Method that can be called by an interaction/view module to
indicate that some action by the user should result in a network
update. The execution will only be performed if the
AutoExecute mode is active.
"""
if self.auto_execute:
print "auto_execute ##### #####"
self.execute_network()
def serialise_module_instances(self, module_instances):
"""Given
"""
# dictionary of pickled module instances keyed on unique module
# instance name
pmsDict = {}
# we'll use this list internally to check later (during connection
# pickling) which modules are being written away
pickledModuleInstances = []
for module_instance in module_instances:
if self._module_dict.has_key(module_instance):
# first get the MetaModule
mModule = self._module_dict[module_instance]
# create a picklable thingy
pms = PickledModuleState()
try:
print "SERIALISE: %s - %s" % \
(str(module_instance),
str(module_instance.get_config()))
pms.module_config = module_instance.get_config()
except AttributeError, e:
self._devide_app.log_warning(
'Could not extract state (config) from module %s: %s' \
% (module_instance.__class__.__name__, str(e)))
# if we can't get a config, we pickle a default
pms.module_config = DefaultConfigClass()
#pms.module_name = module_instance.__class__.__name__
# we need to store the complete module name
# we could also get this from meta_module.module_name
pms.module_name = module_instance.__class__.__module__
# this will only be used for uniqueness purposes
pms.instance_name = mModule.instance_name
pmsDict[pms.instance_name] = pms
pickledModuleInstances.append(module_instance)
# now iterate through all the actually pickled module instances
# and store all connections in a connections list
# three different types of connections:
# 0. connections with source modules with no inputs
# 1. normal connections
# 2. connections with targets that are exceptions, e.g. sliceViewer
connectionList = []
for module_instance in pickledModuleInstances:
mModule = self._module_dict[module_instance]
# we only have to iterate through all outputs
for output_idx in range(len(mModule.outputs)):
outputConnections = mModule.outputs[output_idx]
# each output can of course have multiple outputConnections
# each outputConnection is a tuple:
# (consumerModule, consumerInputIdx)
for outputConnection in outputConnections:
if outputConnection[0] in pickledModuleInstances:
# this means the consumerModule is also one of the
# modules to be pickled and so this connection
# should be stored
# find the type of connection (1, 2, 3), work from
# the back...
moduleClassName = \
outputConnection[0].__class__.__name__
if moduleClassName in self.consumerTypeTable:
connection_type = self.consumerTypeTable[
moduleClassName]
else:
connection_type = 1
# FIXME: we still have to check for 0: iterate
# through all inputs, check that none of the
# supplier modules are in the list that we're
# going to pickle
print '%s has connection type %d' % \
(outputConnection[0].__class__.__name__,
connection_type)
connection = PickledConnection(
mModule.instance_name, output_idx,
self._module_dict[outputConnection[0]].instance_name,
outputConnection[1],
connection_type)
connectionList.append(connection)
return (pmsDict, connectionList)
def generic_progress_callback(self, progressObject,
progressObjectName, progress, progressText):
"""progress between 0.0 and 1.0.
"""
if self._inProgressCallback.testandset():
# first check if execution has been disabled
# the following bit of code is risky: the ITK to VTK bridges
# seem to be causing segfaults when we abort too soon
# if not self._executionEnabled:
# try:
# progressObject.SetAbortExecute(1)
# except Exception:
# pass
# try:
# progressObject.SetAbortGenerateData(1)
# except Exception:
# pass
# progress = 1.0
# progressText = 'Execution ABORTED.'
progressP = progress * 100.0
fullText = '%s: %s' % (progressObjectName, progressText)
if abs(progressP - 100.0) < 0.01:
# difference smaller than a hundredth
fullText += ' [DONE]'
self.setProgress(progressP, fullText)
self._inProgressCallback.unlock()
def get_consumers(self, meta_module):
"""Determine meta modules that are connected to the outputs of
meta_module.
This method is called by: scheduler, self.recreate_module_in_place.
@todo: this should be part of the MetaModule code, as soon as
the MetaModule inputs and outputs are of type MetaModule and not
instance.
@param instance: module instance of which the consumers should be
determined.
@return: list of tuples, each consisting of (this module's output
index, the consumer meta module, the consumer input index)
"""
consumers = []
# get outputs from MetaModule: this is a list of list of tuples
# outer list has number of outputs elements
# inner lists store consumer modules for that output
# tuple contains (consumerModuleInstance, consumerInputIdx)
outputs = meta_module.outputs
for output_idx in range(len(outputs)):
output = outputs[output_idx]
for consumerInstance, consumerInputIdx in output:
consumerMetaModule = self._module_dict[consumerInstance]
consumers.append(
(output_idx, consumerMetaModule, consumerInputIdx))
return consumers
def get_producers(self, meta_module):
"""Return a list of meta modules, output indices and the input
index through which they supply 'meta_module' with data.
@todo: this should be part of the MetaModule code, as soon as
the MetaModule inputs and outputs are of type MetaModule and not
instance.
@param meta_module: consumer meta module.
@return: list of tuples, each tuple consists of producer meta module
and output index as well as input index of the instance input that
they connect to.
"""
# inputs is a list of tuples, each tuple containing module_instance
# and output_idx of the producer/supplier module; if the port is
# not connected, that position in inputs contains "None"
inputs = meta_module.inputs
producers = []
for i in range(len(inputs)):
pTuple = inputs[i]
if pTuple is not None:
# unpack
pInstance, pOutputIdx = pTuple
pMetaModule = self._module_dict[pInstance]
# and store
producers.append((pMetaModule, pOutputIdx, i))
return producers
def setModified_DEPRECATED(self, module_instance):
"""Changed modified ivar in MetaModule.
This ivar is used to determine whether module_instance needs to be
executed to become up to date. It should be set whenever changes
are made that dirty the module state, for example parameter changes
or topology changes.
@param module_instance: the instance whose modified state sbould be
changed.
@param value: the new value of the modified ivar, True or False.
"""
self._module_dict[module_instance].modified = True
def set_progress(self, progress, message, noTime=False):
"""Progress is in percent.
"""
self._devide_app.set_progress(progress, message, noTime)
setProgress = set_progress
def _make_unique_instance_name(self, instance_name=None):
"""Ensure that instance_name is unique or create a new unique
instance_name.
If instance_name is None, a unique one will be created. An
instance_name (whether created or passed) will be permuted until it
unique and then returned.
"""
# first we make sure we have a unique instance name
if not instance_name:
instance_name = "dvm%d" % (len(self._module_dict),)
# now make sure that instance_name is unique
uniqueName = False
while not uniqueName:
# first check that this doesn't exist in the module dictionary
uniqueName = True
for mmt in self._module_dict.items():
if mmt[1].instance_name == instance_name:
uniqueName = False
break
if not uniqueName:
# this means that this exists already!
# create a random 3 character string
chars = 'abcdefghijklmnopqrstuvwxyz'
tl = ""
for i in range(3):
tl += choice(chars)
instance_name = "%s%s%d" % (instance_name, tl,
len(self._module_dict))
return instance_name
def rename_module(self, instance, name):
"""Rename a module in the module dictionary
"""
# if we get a duplicate name, we either add (%d) after, or replace
# the existing %d with something that makes it all unique...
mo = re.match('(.*)\s+\(([1-9]+)\)', name)
if mo:
basename = mo.group(1)
i = int(mo.group(2)) + 1
else:
basename = name
i = 1
while (self.get_instance(name) != None):
# add a number (%d) until the name is unique
name = '%s (%d)' % (basename, i)
i += 1
try:
# get the MetaModule and rename it.
self._module_dict[instance].instance_name = name
except Exception:
return False
# some modules and mixins support the rename call and use it
# to change their window titles. Neat.
# this was added on 20090322, so it's not supported
# everywhere.
try:
instance.rename(name)
except AttributeError:
pass
# everything proceeded according to plan.
# so return the new name
return name
def modify_module(self, module_instance, part=0):
"""Call this whenever module state has changed in such a way that
necessitates a re-execution, for instance when parameters have been
changed or when new input data has been transferred.
"""
self._module_dict[module_instance].modify(part)
modify_module = modify_module
def recreate_module_in_place(self, meta_module):
"""Destroy, create and reconnect a module in place.
This function works but is not being used at the moment. It was
intended for graphEditor-driven module reloading, but it turned out
that implementing that in the graphEditor was easier. I'm keeping
this here for reference purposes.
@param meta_module: The module that will be destroyed.
@returns: new meta_module.
"""
# 1. store input and output connections, module name, module state
#################################################################
# prod_tuple contains a list of (prod_meta_module, output_idx,
# input_idx) tuples
prod_tuples = self.get_producers(meta_module)
# cons_tuples contains a list of (output_index, consumer_meta_module,
# consumer input index)
cons_tuples = self.get_consumers(meta_module)
# store the instance name
instance_name = meta_module.instance_name
# and the full module spec name
full_name = meta_module.module_name
# and get the module state (we make a deep copy just in case)
module_config = copy.deepcopy(meta_module.instance.get_config())
# 2. instantiate a new one and give it its old config
###############################################################
# because we instantiate the new one first, if this instantiation
# breaks, an exception will be raised and no harm will be done,
# we still have the old one lying around
# instantiate
new_instance = self.create_module(full_name, instance_name)
# and give it its old config back
new_instance.set_config(module_config)
# 3. delete the old module
#############################################################
self.delete_module(meta_module.instance)
# 4. now rename the new module
#############################################################
# find the corresponding new meta_module
meta_module = self._module_dict[new_instance]
# give it its old name back
meta_module.instance_name = instance_name
# 5. connect it up
#############################################################
for producer_meta_module, output_idx, input_idx in prod_tuples:
self.connect_modules(
producer_meta_module.instance, output_idx,
new_instance, input_idx)
for output_idx, consumer_meta_module, input_idx in cons_tuples:
self.connect_modules(
new_instance, output_idx,
consumer_meta_module.instance, input_idx)
# we should be done now
return meta_module
def should_execute_module(self, meta_module, part=0):
"""Determine whether module_instance requires execution to become
up to date.
Execution is required when the module is new or when the user has made
parameter or introspection changes. All of these conditions should be
indicated by calling L{ModuleManager.modify(instance)}.
@return: True if execution required, False if not.
"""
return meta_module.shouldExecute(part)
def should_transfer_output(
self,
meta_module, output_idx, consumer_meta_module,
consumer_input_idx, streaming=False):
"""Determine whether output data has to be transferred from
module_instance via output outputIndex to module consumerInstance.
Output needs to be transferred if:
- module_instance has new or changed output (i.e. it has
executed after the previous transfer)
- consumerInstance does not have the data yet
Both of these cases are handled with a transfer timestamp per
output connection (defined by output idx, consumer module, and
consumer input idx)
This method is used by the scheduler.
@return: True if output should be transferred, False if not.
"""
return meta_module.should_transfer_output(
output_idx, consumer_meta_module, consumer_input_idx,
streaming)
def transfer_output(
self,
meta_module, output_idx, consumer_meta_module,
consumer_input_idx, streaming=False):
"""Transfer output data from module_instance to the consumer modules
connected to its specified output indexes.
This will be called by the scheduler right before execution to
transfer the given output from module_instance instance to the correct
input on the consumerInstance. In general, this is only done if
should_transfer_output is true, so the number of unnecessary transfers
should be minimised.
This method is in ModuleManager and not in MetaModule because it
involves more than one MetaModule.
@param module_instance: producer module whose output data must be
transferred.
@param outputIndex: only output data produced by this output will
be transferred.
@param consumerInstance: only data going to this instance will be
transferred.
@param consumerInputIdx: data enters consumerInstance via this input
port.
@raise ModuleManagerException: if an error occurs getting the data
from or transferring it to a new module.
"""
#print 'transferring data %s:%d' % (module_instance.__class__.__name__,
# outputIndex)
# double check that this connection already exists
consumer_instance = consumer_meta_module.instance
if meta_module.findConsumerInOutputConnections(
output_idx, consumer_instance, consumer_input_idx) == -1:
raise Exception, 'ModuleManager.transfer_output called for ' \
'connection that does not exist.'
try:
# get data from producerModule output
od = meta_module.instance.get_output(output_idx)
except Exception, e:
# get details about the errored module
instance_name = meta_module.instance_name
module_name = meta_module.instance.__class__.__name__
# and raise the relevant exception
es = 'Faulty transfer_output (get_output on module %s (%s)): %s' \
% (instance_name, module_name, str(e))
# we use the three argument form so that we can add a new
# message to the exception but we get to see the old traceback
# see: http://docs.python.org/ref/raise.html
raise ModuleManagerException, es, sys.exc_info()[2]
# we only disconnect if we're NOT streaming!
if not streaming:
# experiment here with making shallowcopies if we're working with
# VTK data. I've double-checked (20071027): calling update on
# a shallowcopy is not able to get a VTK pipeline to execute.
# TODO: somehow this should be part of one of the moduleKits
# or some other module-related pluggable logic.
if od and hasattr(od, 'GetClassName') and hasattr(od, 'ShallowCopy'):
nod = od.__class__()
nod.ShallowCopy(od)
od = nod
try:
# set on consumerInstance input
consumer_meta_module.instance.set_input(consumer_input_idx, od)
except Exception, e:
# get details about the errored module
instance_name = consumer_meta_module.instance_name
module_name = consumer_meta_module.instance.__class__.__name__
# and raise the relevant exception
es = 'Faulty transfer_output (set_input on module %s (%s)): %s' \
% (instance_name, module_name, str(e))
# we use the three argument form so that we can add a new
# message to the exception but we get to see the old traceback
# see: http://docs.python.org/ref/raise.html
raise ModuleManagerException, es, sys.exc_info()[2]
# record that the transfer has just happened
meta_module.timeStampTransferTime(
output_idx, consumer_instance, consumer_input_idx,
streaming)
# also invalidate the consumerModule: it should re-execute when
# a transfer has been made. We only invalidate the part that
# takes responsibility for that input.
part = consumer_meta_module.getPartForInput(consumer_input_idx)
consumer_meta_module.modify(part)
#print "modified", consumer_meta_module.instance.__class__.__name__
# execute on change
# we probably shouldn't automatically execute here... transfers
# mean that some sort of network execution is already running
| Python |
class canvasSubject:
def __init__(self):
self._observers = {}
def addObserver(self, eventName, observer):
"""Add an observer for a particular event.
eventName can be one of 'enter', 'exit', 'drag', 'buttonDown'
or 'buttonUp'. observer is a callable object that will be
invoked at event time with parameters canvas object,
eventName, and event.
"""
self._observers[eventName].append(observer)
def notifyObservers(self, eventName, event):
for observer in self._observers[eventName]:
observer(self, eventName, event)
| Python |
from canvasObject import *
from canvas import *
| Python |
from wxPython import wx
from canvasSubject import canvasSubject
#############################################################################
class canvasObject(canvasSubject):
def __init__(self, position):
# call parent ctor
canvasSubject.__init__(self)
self._position = position
self._canvas = None
self._observers = {'enter' : [],
'exit' : [],
'drag' : [],
'buttonDown' : [],
'buttonUp' : [],
'buttonDClick' : [],
'motion' : []}
def close(self):
"""Take care of any cleanup here.
"""
pass
def draw(self, dc):
pass
def getBounds(self):
raise NotImplementedError
def getPosition(self):
return self._position
def setPosition(self, destination):
self._position = destination
def getCanvas(self):
return self._canvas
def hitTest(self, x, y):
return False
def isInsideRect(self, x, y, width, height):
return False
def setCanvas(self, canvas):
self._canvas = canvas
#############################################################################
class coRectangle(canvasObject):
def __init__(self, position, size):
canvasObject.__init__(self, position)
self._size = size
def draw(self, dc):
# drawing rectangle!
dc.SetBrush(wx.wxBrush(wx.wxColour(192,192,192), wx.wxSOLID))
dc.DrawRectangle(self._position[0], self._position[1],
self._size[0], self._size[1])
def getBounds(self):
return (self._size)
def getTopLeftBottomRight(self):
return ((self._position[0], self._position[1]),
(self._position[0] + self._size[0] - 1,
self._position[1] + self._size[1] - 1))
def hitTest(self, x, y):
# think carefully about the size of the rectangle...
# e.g. from 0 to 2 is size 2 (spaces between vertices)
return x >= self._position[0] and \
x <= self._position[0] + self._size[0] and \
y >= self._position[1] and \
y <= self._position[1] + self._size[1]
def isInsideRect(self, x, y, width, height):
x0 = (self._position[0] - x)
y0 = (self._position[1] - y)
return x0 >= 0 and x0 <= width and \
y0 >= 0 and y0 <= height and \
x0 + self._size[0] <= width and \
y0 + self._size[1] <= height
#############################################################################
class coLine(canvasObject):
# this is used by the routing algorithm to route lines around glyphs
# with a certain border; this is also used by updateEndPoints to bring
# the connection out of the connection port initially
routingOvershoot = 10
def __init__(self, fromGlyph, fromOutputIdx, toGlyph, toInputIdx):
"""A line object for the canvas.
linePoints is just a list of python tuples, each representing a
coordinate of a node in the line. The position is assumed to be
the first point.
"""
self.fromGlyph = fromGlyph
self.fromOutputIdx = fromOutputIdx
self.toGlyph = toGlyph
self.toInputIdx = toInputIdx
# 'BLACK' removed
colourNames = ['BLUE', 'BROWN', 'MEDIUM FOREST GREEN',
'DARKORANGE1']
self.lineColourName = colourNames[self.toInputIdx % (len(colourNames))]
# any line begins with 4 (four) points
self.updateEndPoints()
canvasObject.__init__(self, self._linePoints[0])
def close(self):
# delete things that shouldn't be left hanging around
del self.fromGlyph
del self.toGlyph
def draw(self, dc):
# lines are 2 pixels thick
dc.SetPen(wx.wxPen(self.lineColourName, 2, wx.wxSOLID))
# simple mode: just the lines thanks.
#dc.DrawLines(self._linePoints)
# spline mode for N points:
# 1. Only 4 points: drawlines. DONE
# 2. Draw line from 0 to 1
# 3. Draw line from N-2 to N-1 (second last to last)
# 4. Draw spline from 1 to N-2 (second to second last)
# if len(self._linePoints) > 4:
# dc.DrawLines(self._linePoints[0:2]) # 0 - 1
# dc.DrawLines(self._linePoints[-2:]) # second last to last
# dc.DrawSpline(self._linePoints[1:-1])
# else:
# dc.DrawLines(self._linePoints)
dc.SetPen(wx.wxPen('BLACK', 4, wx.wxSOLID))
dc.DrawSpline(self._linePoints)
dc.SetPen(wx.wxPen(self.lineColourName, 2, wx.wxSOLID))
dc.DrawSpline(self._linePoints)
def getBounds(self):
# totally hokey: for now we just return the bounding box surrounding
# the first two points - ideally we should iterate through the lines,
# find extents and pick a position and bounds accordingly
return (self._linePoints[-1][0] - self._linePoints[0][0],
self._linePoints[-1][1] - self._linePoints[0][1])
def getUpperLeftWidthHeight(self):
"""This returns the upperLeft coordinate and the width and height of
the bounding box enclosing the third-last and second-last points.
This is used for fast intersection checking with rectangles.
"""
p3 = self._linePoints[-3]
p2 = self._linePoints[-2]
upperLeftX = [p3[0], p2[0]][bool(p2[0] < p3[0])]
upperLeftY = [p3[1], p2[1]][bool(p2[1] < p3[1])]
width = abs(p2[0] - p3[0])
height = abs(p2[1] - p3[1])
return ((upperLeftX, upperLeftY), (width, height))
def getThirdLastSecondLast(self):
return (self._linePoints[-3], self._linePoints[-2])
def hitTest(self, x, y):
# maybe one day we will make the hitTest work, not tonight
# I don't need it
return False
def insertRoutingPoint(self, x, y):
"""Insert new point x,y before second-last point, i.e. the new point
becomes the third-last point.
"""
if (x,y) not in self._linePoints:
self._linePoints.insert(len(self._linePoints) - 2, (x, y))
return True
else:
return False
def updateEndPoints(self):
# first get us just out of the port, then create margin between
# us and glyph
boostFromPort = coGlyph._pHeight / 2 + coLine.routingOvershoot
self._linePoints = [(), (), (), ()]
self._linePoints[0] = self.fromGlyph.getCenterOfPort(
1, self.fromOutputIdx)
self._linePoints[1] = (self._linePoints[0][0],
self._linePoints[0][1] + boostFromPort)
self._linePoints[-1] = self.toGlyph.getCenterOfPort(
0, self.toInputIdx)
self._linePoints[-2] = (self._linePoints[-1][0],
self._linePoints[-1][1] - boostFromPort)
#############################################################################
class coGlyph(coRectangle):
# at start and end of glyph
_horizBorder = 5
# between ports
_horizSpacing = 5
# at top and bottom of glyph
_vertBorder = 15
_pWidth = 10
_pHeight = 10
def __init__(self, position, numInputs, numOutputs,
labelList, module_instance):
# parent constructor
coRectangle.__init__(self, position, (0,0))
# we'll fill this out later
self._size = (0,0)
self._numInputs = numInputs
self.inputLines = [None] * self._numInputs
self._numOutputs = numOutputs
# be careful with list concatenation!
self.outputLines = [[] for i in range(self._numOutputs)]
self._labelList = labelList
self.module_instance = module_instance
self.draggedPort = None
self.enteredPort = None
self.selected = False
self.blocked = False
def close(self):
del self.module_instance
del self.inputLines
del self.outputLines
def draw(self, dc):
normal_colour = (192, 192, 192)
selected_colour = (255, 0, 246)
blocked_colour = (16, 16, 16)
colour = normal_colour
if self.selected:
colour = [selected_colour[i] * 0.5 + colour[i] * 0.5
for i in range(3)]
if self.blocked:
colour = [blocked_colour[i] * 0.5 + colour[i] * 0.5
for i in range(3)]
colour = tuple([int(i) for i in colour])
blockFillColour = wx.wxColour(*colour)
# # we're going to alpha blend a purplish sheen if this glyph is active
# if self.selected:
# # sheen: 255, 0, 246
# # alpha-blend with 192, 192, 192 with alpha 0.5 yields
# # 224, 96, 219
# blockFillColour = wx.wxColour(224, 96, 219)
# else:
# blockFillColour = wx.wxColour(192, 192, 192)
# default pen and font
dc.SetBrush(wx.wxBrush(blockFillColour, wx.wxSOLID))
dc.SetPen(wx.wxPen('BLACK', 1, wx.wxSOLID))
dc.SetFont(wx.wxNORMAL_FONT)
# calculate our size
# the width is the maximum(textWidth + twice the horizontal border,
# all ports, horizontal borders and inter-port borders added up)
maxPorts = max(self._numInputs, self._numOutputs)
portsWidth = 2 * coGlyph._horizBorder + \
maxPorts * coGlyph._pWidth + \
(maxPorts - 1 ) * coGlyph._horizSpacing
# determine maximum textwidth and height
tex = 0
tey = 0
for l in self._labelList:
temptx, tempty = dc.GetTextExtent(l)
if temptx > tex:
tex = temptx
if tempty > tey:
tey = tempty
# this will be calculated with the max width, so fine
textWidth = tex + 2 * coGlyph._horizBorder
self._size = (max(textWidth, portsWidth),
tey * len(self._labelList) + 2 * coGlyph._vertBorder)
# draw the main rectangle
dc.DrawRectangle(self._position[0], self._position[1],
self._size[0], self._size[1])
#dc.DrawRoundedRectangle(self._position[0], self._position[1],
# self._size[0], self._size[1], radius=5)
initY = self._position[1] + coGlyph._vertBorder
for l in self._labelList:
dc.DrawText(l,
self._position[0] + coGlyph._horizSpacing,
initY)
initY += tey
# then the inputs
horizOffset = self._position[0] + coGlyph._horizBorder
horizStep = coGlyph._pWidth + coGlyph._horizSpacing
connBrush = wx.wxBrush("GREEN")
disconnBrush = wx.wxBrush("RED")
for i in range(self._numInputs):
brush = [disconnBrush, connBrush][bool(self.inputLines[i])]
self.drawPort(dc, brush,
(horizOffset + i * horizStep,
self._position[1]))
lx = self._position[1] + self._size[1] - coGlyph._pHeight
for i in range(self._numOutputs):
brush = [disconnBrush, connBrush][bool(self.outputLines[i])]
self.drawPort(dc, brush,
(horizOffset + i * horizStep,
lx))
def drawPort(self, dc, brush, pos):
dc.SetBrush(brush)
dc.DrawRectangle(pos[0], pos[1], coGlyph._pWidth, coGlyph._pHeight)
#dc.DrawEllipse(pos[0], pos[1], coGlyph._pWidth, coGlyph._pHeight)
def findPortContainingMouse(self, x, y):
"""Find port that contains the mouse pointer. Returns tuple
containing inOut and port index.
"""
horizOffset = self._position[0] + coGlyph._horizBorder
horizStep = coGlyph._pWidth + coGlyph._horizSpacing
bx = horizOffset
by = self._position[1]
for i in range(self._numInputs):
if x >= bx and x <= bx + self._pWidth and \
y >= by and y < by + self._pHeight:
return (0, i)
bx += horizStep
bx = horizOffset
by = self._position[1] + self._size[1] - coGlyph._pHeight
for i in range(self._numOutputs):
if x >= bx and x <= bx + self._pWidth and \
y >= by and y < by + self._pHeight:
return (1, i)
bx += horizStep
return None
def getCenterOfPort(self, inOrOut, idx):
horizOffset = self._position[0] + coGlyph._horizBorder
horizStep = coGlyph._pWidth + coGlyph._horizSpacing
cy = self._position[1] + coGlyph._pHeight / 2
if inOrOut:
cy += self._size[1] - coGlyph._pHeight
cx = horizOffset + idx * horizStep + coGlyph._pWidth / 2
return (cx, cy)
def getLabel(self):
return ' '.join(self._labelList)
def setLabelList(self,labelList):
self._labelList = labelList
| Python |
import wx
from canvasSubject import canvasSubject
from canvasObject import *
class canvas(wx.wxScrolledWindow, canvasSubject):
def __init__(self, parent, id = -1, size = wx.wxDefaultSize):
# parent 1 ctor
wx.wxScrolledWindow.__init__(self, parent, id, wx.wxPoint(0, 0), size,
wx.wxSUNKEN_BORDER)
# parent 2 ctor
canvasSubject.__init__(self)
self._cobjects = []
self._previousRealCoords = None
self._mouseDelta = (0,0)
self._potentiallyDraggedObject = None
self._draggedObject = None
self._observers = {'drag' : [],
'buttonDown' : [],
'buttonUp' : []}
self.SetBackgroundColour("WHITE")
wx.EVT_MOUSE_EVENTS(self, self.OnMouseEvent)
wx.EVT_PAINT(self, self.OnPaint)
self.virtualWidth = 2048
self.virtualHeight = 2048
self._buffer = None
self._buffer = wx.wxEmptyBitmap(self.virtualWidth, self.virtualHeight)
# we're only going to draw into the buffer, so no real client DC
dc = wx.wxBufferedDC(None, self._buffer)
dc.SetBackground(wx.wxBrush(self.GetBackgroundColour()))
dc.Clear()
self.doDrawing(dc)
self.SetVirtualSize((self.virtualWidth, self.virtualHeight))
self.SetScrollRate(20,20)
def eventToRealCoords(self, ex, ey):
"""Convert window event coordinates to canvas relative coordinates.
"""
# get canvas parameters
vsx, vsy = self.GetViewStart()
dx, dy = self.GetScrollPixelsPerUnit()
# calculate REAL coords
rx = ex + vsx * dx
ry = ey + vsy * dy
return (rx, ry)
def getDC(self):
"""Returns DC which can be used by the outside to draw to our buffer.
As soon as dc dies (and it will at the end of the calling function)
the contents of self._buffer will be blitted to the screen.
"""
cdc = wx.wxClientDC(self)
# set device origin according to scroll position
self.PrepareDC(cdc)
dc = wx.wxBufferedDC(cdc, self._buffer)
return dc
def get_glyph_on_coords(self, rx, ry):
"""If rx,ry falls on a glyph, return that glyph, else return
None.
"""
for cobject in self._cobjects:
if cobject.hitTest(rx, ry) and isinstance(cobject,
coGlyph):
return cobject
return None
def OnMouseEvent(self, event):
# this seems to work fine under windows. If we don't do this, and the
# mouse leaves the canvas, the rubber band remains and no selection
# is made.
if event.ButtonDown():
if not self.HasCapture():
self.CaptureMouse()
elif event.ButtonUp():
if self.HasCapture():
self.ReleaseMouse()
# these coordinates are relative to the visible part of the canvas
ex, ey = event.GetX(), event.GetY()
rx, ry = self.eventToRealCoords(ex, ey)
# add the "real" coords to the event structure
event.realX = rx
event.realY = ry
if self._previousRealCoords:
self._mouseDelta = (rx - self._previousRealCoords[0],
ry - self._previousRealCoords[1])
else:
self._mouseDelta = (0,0)
# FIXME: store binding to object which "has" the mouse
# on subsequent tries, we DON'T have to check all objects, only the
# one which had the mouse on the previous try... only if it "loses"
# the mouse, do we enter the mean loop again.
mouseOnObject = False
# the following three clauses, i.e. the hitTest, mouseOnObject and
# draggedObject should be kept in this order, unless you know
# EXACTLY what you're doing. If you're going to change anything, test
# that connects, disconnects (of all kinds) and rubber-banding still
# work.
# we need to do this expensive hit test every time, because the user
# wants to know when he mouses over the input port of a destination
# module
for cobject in self._cobjects:
if cobject.hitTest(rx, ry):
mouseOnObject = True
cobject.notifyObservers('motion', event)
if not cobject.__hasMouse:
cobject.__hasMouse = True
cobject.notifyObservers('enter', event)
if event.Dragging():
if not self._draggedObject:
if self._potentiallyDraggedObject == cobject:
# the user is dragging inside an object inside
# of which he has previously clicked... this
# definitely means he's dragging the object
mouseOnObject = True
self._draggedObject = cobject
else:
# this means the user has dragged the mouse
# over an object... which means mouseOnObject
# is technically true, but because we want the
# canvas to get this kind of dragEvent, we
# set it to false
mouseOnObject = False
elif event.ButtonUp():
cobject.notifyObservers('buttonUp', event)
elif event.ButtonDown():
if event.LeftDown():
# this means EVERY buttonDown in an object classifies
# as a potential drag. if the user now drags, we
# have a winner
self._potentiallyDraggedObject = cobject
cobject.notifyObservers('buttonDown', event)
elif event.ButtonDClick():
cobject.notifyObservers('buttonDClick', event)
# ends if cobject.hitTest(ex, ey)
else:
if cobject.__hasMouse:
cobject.__hasMouse = False
cobject.notifyObservers('exit', event)
if not mouseOnObject:
# we only get here if the mouse is not inside any canvasObject
# (but it could be dragging a canvasObject!)
if event.Dragging():
self.notifyObservers('drag', event)
elif event.ButtonUp():
self.notifyObservers('buttonUp', event)
elif event.ButtonDown():
self.notifyObservers('buttonDown', event)
if self._draggedObject:
# dragging locks onto an object, even if the mouse pointer
# is not inside that object - it will keep receiving drag
# events!
draggedObject = self._draggedObject
if event.ButtonUp():
# a button up anywhere cancels any drag
self._draggedObject = None
# so, the object can query canvas.getDraggedObject: if it's
# none, it means the drag has ended; if not, the drag is
# ongoing
draggedObject.notifyObservers('drag', event)
if event.ButtonUp():
# each and every ButtonUp cancels the current potential drag object
self._potentiallyDraggedObject = None
# store the previous real coordinates for mouse deltas
self._previousRealCoords = (rx, ry)
def OnPaint(self, event):
# as soon as dc is unbound and destroyed, buffer is blit
# BUFFER_VIRTUAL_AREA indicates that the buffer bitmap is for the
# whole virtual area, not just the client area of the window
dc = wx.wxBufferedPaintDC(self, self._buffer,
style=wx.wxBUFFER_VIRTUAL_AREA)
def doDrawing(self, dc):
"""This function actually draws the complete shebang to the passed
dc.
"""
dc.BeginDrawing()
# clear the whole shebang to background
dc.SetBackground(wx.wxBrush(self.GetBackgroundColour(), wx.wxSOLID))
dc.Clear()
# draw glyphs last (always)
glyphs = []
theRest = []
for i in self._cobjects:
if isinstance(i, coGlyph):
glyphs.append(i)
else:
theRest.append(i)
for cobj in theRest:
cobj.draw(dc)
for cobj in glyphs:
cobj.draw(dc)
# draw all objects
#for cobj in self._cobjects:
# cobj.draw(dc)
dc.EndDrawing()
def addObject(self, cobj):
if cobj and cobj not in self._cobjects:
cobj.setCanvas(self)
self._cobjects.append(cobj)
cobj.__hasMouse = False
def drawObject(self, cobj):
"""Use this if you want to redraw a single canvas object.
"""
dc = self.getDC()
cobj.draw(dc)
def redraw(self):
"""Redraw the whole scene.
"""
dc = self.getDC()
self.doDrawing(dc)
def removeObject(self, cobj):
if cobj and cobj in self._cobjects:
cobj.setCanvas(None)
if self._draggedObject == cobj:
self._draggedObject = None
del self._cobjects[self._cobjects.index(cobj)]
def getMouseDelta(self):
return self._mouseDelta
def getDraggedObject(self):
return self._draggedObject
def getObjectsOfClass(self, classt):
return [i for i in self._cobjects if isinstance(i, classt)]
def getObjectWithMouse(self):
"""Return object currently containing mouse, None if no object has
the mouse.
"""
for cobject in self._cobjects:
if cobject.__hasMouse:
return cobject
return None
def dragObject(self, cobj, delta):
if abs(delta[0]) > 0 or abs(delta[1]) > 0:
# calculate new position
cpos = cobj.getPosition()
npos = (cpos[0] + delta[0], cpos[1] + delta[1])
cobj.setPosition(npos)
# setup DC
dc = self.getDC()
dc.BeginDrawing()
# we're only going to draw a dotted outline
dc.SetBrush(wx.wxBrush('WHITE', wx.wxTRANSPARENT))
dc.SetPen(wx.wxPen('BLACK', 1, wx.wxDOT))
dc.SetLogicalFunction(wx.wxINVERT)
bounds = cobj.getBounds()
# first delete the old rectangle
dc.DrawRectangle(cpos[0], cpos[1], bounds[0], bounds[1])
# then draw the new one
dc.DrawRectangle(npos[0], npos[1], bounds[0], bounds[1])
# thar she goes
dc.EndDrawing()
#############################################################################
| Python |
# dummy
| Python |
# dummy
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
from module_kits.misc_kit.mixins import SubjectMixin
import vtk
# z-coord of RBB box
# when this is 1.0, the box does not appear until a canvas reset has
# been done...
RBBOX_HEIGHT = 0.9
class UnfilledBlock:
"""Create block outline.
"""
def __init__(self):
self.polydata = lp = vtk.vtkPolyData()
pts = vtk.vtkPoints()
pts.InsertPoint(0, 0, 0, 0)
pts.InsertPoint(1, 1, 0, 0)
pts.InsertPoint(2, 1, 1, 0)
pts.InsertPoint(3, 0, 1, 0)
lp.SetPoints(pts)
cells = vtk.vtkCellArray()
cells.InsertNextCell(5)
cells.InsertCellPoint(0)
cells.InsertCellPoint(1)
cells.InsertCellPoint(2)
cells.InsertCellPoint(3)
cells.InsertCellPoint(0)
lp.SetLines(cells)
def update_geometry(self, width, height, z):
lp = self.polydata
pts = lp.GetPoints()
pts.SetPoint(0, 0,0,z)
pts.SetPoint(1, width, 0, z)
pts.SetPoint(2, width, height, z)
pts.SetPoint(3, 0, height, c)
# FIXME: is there no cleaner way of explaining to the polydata
# that it has been updated?
lp.SetPoints(None)
lp.SetPoints(pts)
class FilledBlock:
"""Create filled block.
"""
def __init__(self):
self.polydata = lp = vtk.vtkPolyData()
pts = vtk.vtkPoints()
pts.InsertPoint(0, 0, 0, 0)
pts.InsertPoint(1, 1, 0, 0)
pts.InsertPoint(2, 1, 1, 0)
pts.InsertPoint(3, 0, 1, 0)
lp.SetPoints(pts)
cells = vtk.vtkCellArray()
cells.InsertNextCell(4)
cells.InsertCellPoint(0)
cells.InsertCellPoint(1)
cells.InsertCellPoint(2)
cells.InsertCellPoint(3)
lp.SetPolys(cells)
def update_geometry(self, width, height, z):
lp = self.polydata
pts = lp.GetPoints()
pts.SetPoint(0, 0,0,z)
pts.SetPoint(1, width, 0, z)
pts.SetPoint(2, width, height, z)
pts.SetPoint(3, 0, height, z)
# FIXME: is there no cleaner way of explaining to the polydata
# that it has been updated?
lp.SetPoints(None)
lp.SetPoints(pts)
class BeveledEdgeBlock:
"""Create PolyData beveled edge block.
"""
def __init__(self):
"""Create all required geometry according to default size.
Call update_geometry to update this to new specifications.
"""
self.polydata = vtk.vtkPolyData()
# width of the edge
self.edge = edge = 5
# how much higher is inside rectangle than the outside (this
# is what creates the beveled effect)
self.eps = eps = 1.0/100.0
# dummy variable for now
width = 1
# create points defining the geometry
pts = vtk.vtkPoints()
# InsertPoint takes care of memory allocation
pts.InsertPoint(0, 0, 0, 0)
pts.InsertPoint(1, width, 0, 0)
pts.InsertPoint(2, width, 1, 0)
pts.InsertPoint(3, 0, 1, 0)
pts.InsertPoint(4, 0+edge, 0+edge, eps)
pts.InsertPoint(5, width-edge, 0+edge, eps)
pts.InsertPoint(6, width-edge, 1-edge, eps)
pts.InsertPoint(7, 0+edge, 1-edge, eps)
self.polydata.SetPoints(pts) # assign to the polydata
self.pts = pts
# create cells connecting points to each other
cells = vtk.vtkCellArray()
cells.InsertNextCell(4)
cells.InsertCellPoint(0)
cells.InsertCellPoint(1)
cells.InsertCellPoint(2)
cells.InsertCellPoint(3)
cells.InsertNextCell(4)
cells.InsertCellPoint(4)
cells.InsertCellPoint(5)
cells.InsertCellPoint(6)
cells.InsertCellPoint(7)
self.polydata.SetPolys(cells) # assign to the polydata
# create pointdata
arr = vtk.vtkUnsignedCharArray()
arr.SetNumberOfComponents(4)
arr.SetNumberOfTuples(8)
arr.SetTuple4(0, 92,92,92,255)
arr.SetTuple4(1, 130,130,130,255)
arr.SetTuple4(2, 92,92,92,255)
arr.SetTuple4(3, 0,0,0,255)
arr.SetTuple4(4, 92,92,92,255)
arr.SetTuple4(5, 0,0,0,255)
arr.SetTuple4(6, 92,92,92,255)
arr.SetTuple4(7, 192,192,192,255)
arr.SetName('my_array')
# and assign it as "scalars"
self.polydata.GetPointData().SetScalars(arr)
def update_geometry(self, width, height, z):
"""Update the geometry to the given specs. self.polydata will
be modified so that any downstream logic knows to update.
"""
pts = self.pts
edge = self.edge
eps = self.eps
# outer rectangle
pts.SetPoint(0, 0,0,z)
pts.SetPoint(1, width, 0, z)
pts.SetPoint(2, width, height, z)
pts.SetPoint(3, 0, height, z)
# inner rectangle
pts.SetPoint(4, 0+edge, 0+edge, z+eps)
pts.SetPoint(5, width-edge, 0+edge, z+eps)
pts.SetPoint(6, width-edge, height-edge, z+eps)
pts.SetPoint(7, 0+edge, height-edge, z+eps)
self.polydata.SetPoints(None)
self.polydata.SetPoints(pts)
#############################################################################
class DeVIDECanvasObject(SubjectMixin):
def __init__(self, canvas, position):
# call parent ctor
SubjectMixin.__init__(self)
self.canvas = canvas
self._position = position
self._observers = {'enter' : [],
'exit' : [],
'drag' : [],
'buttonDown' : [],
'buttonUp' : [],
'buttonDClick' : [],
'motion' : []}
# all canvas objects have a vtk prop that can be added to a
# vtk renderer.
self.props = []
def close(self):
"""Take care of any cleanup here.
"""
SubjectMixin.close(self)
def get_bounds(self):
raise NotImplementedError
def get_position(self):
return self._position
def set_position(self, destination):
self._position = destination
def hit_test(self, x, y):
return False
def is_inside_rect(self, x, y, width, height):
return False
class DeVIDECanvasRBBox(DeVIDECanvasObject):
"""Rubber-band box that can be used to give feedback rubber-band
selection interaction. Thingy.
"""
def __init__(self, canvas, corner_bl, (width, height)):
"""ctor. corner_bl is the bottom-left corner and corner_tr
the top-right corner of the rbbox in world coords.
"""
self.corner_bl = corner_bl
self.width, self.height = width, height
DeVIDECanvasObject.__init__(self, canvas, corner_bl)
self._create_geometry()
self.update_geometry()
def _create_geometry(self):
self._plane_source = vtk.vtkPlaneSource()
self._plane_source.SetNormal((0.0,0.0,1.0))
self._plane_source.SetXResolution(1)
self._plane_source.SetYResolution(1)
m = vtk.vtkPolyDataMapper()
m.SetInput(self._plane_source.GetOutput())
a = vtk.vtkActor()
a.SetMapper(m)
a.GetProperty().SetOpacity(0.3)
a.GetProperty().SetColor(0.0, 0.0, 0.7)
self.props = [a]
def update_geometry(self):
# bring everything up to the correct height (it should be in
# front of all other objects)
corner_bl = tuple(self.corner_bl[0:2]) + (RBBOX_HEIGHT,)
self._plane_source.SetOrigin(corner_bl)
if self.width == 0:
self.width = 0.1
if self.height == 0:
self.height = 0.1
pos1 = [i+j for i,j in zip(corner_bl, (0.0, self.height, 0.0))]
pos2 = [i+j for i,j in zip(corner_bl, (self.width, 0.0, 0.0))]
self._plane_source.SetPoint1(pos1)
self._plane_source.SetPoint2(pos2)
#############################################################################
class DeVIDECanvasSimpleLine(DeVIDECanvasObject):
def __init__(self, canvas, src, dst):
"""src and dst are 3D world space coordinates.
"""
self.src = src
self.dst = dst
# call parent CTOR
DeVIDECanvasObject.__init__(self, canvas, src)
self._create_geometry()
self.update_geometry()
def _create_geometry(self):
self._line_source = vtk.vtkLineSource()
m = vtk.vtkPolyDataMapper()
m.SetInput(self._line_source.GetOutput())
a = vtk.vtkActor()
a.SetMapper(m)
a.GetProperty().SetColor(0.0, 0.0, 0.0)
self.props = [a]
def update_geometry(self):
self._line_source.SetPoint1(self.src)
self._line_source.SetPoint2(self.dst)
self._line_source.Update()
#############################################################################
class DeVIDECanvasLine(DeVIDECanvasObject):
# this is used by the routing algorithm to route lines around glyphs
# with a certain border; this is also used by updateEndPoints to bring
# the connection out of the connection port initially
routingOvershoot = 5
_normal_width = 2
_highlight_width = 2
def __init__(self, canvas, fromGlyph, fromOutputIdx, toGlyph, toInputIdx):
"""A line object for the canvas.
linePoints is just a list of python tuples, each representing a
coordinate of a node in the line. The position is assumed to be
the first point.
"""
self.fromGlyph = fromGlyph
self.fromOutputIdx = fromOutputIdx
self.toGlyph = toGlyph
self.toInputIdx = toInputIdx
colours = [(0, 0, 255), # blue
(128, 64, 0), # brown
(0, 128, 0), # green
(255, 128, 64), # orange
(128, 0, 255), # purple
(128, 128, 64)] # mustard
col = colours[self.toInputIdx % (len(colours))]
self.line_colour = [i / 255.0 for i in col]
# any line begins with 4 (four) points
self.updateEndPoints()
# now we call the parent ctor
DeVIDECanvasObject.__init__(self, canvas, self._line_points[0])
self._create_geometry()
self.update_geometry()
def close(self):
# delete things that shouldn't be left hanging around
del self.fromGlyph
del self.toGlyph
def _create_geometry(self):
self._spline_source = vtk.vtkParametricFunctionSource()
s = vtk.vtkParametricSpline()
if False:
# these are quite ugly...
# later: factor this out into method, so that we can
# experiment live with different spline params. For now
# the vtkCardinal spline that is used is muuuch prettier.
ksplines = []
for i in range(3):
ksplines.append(vtk.vtkKochanekSpline())
ksplines[-1].SetDefaultTension(0)
ksplines[-1].SetDefaultContinuity(0)
ksplines[-1].SetDefaultBias(0)
s.SetXSpline(ksplines[0])
s.SetYSpline(ksplines[1])
s.SetZSpline(ksplines[2])
pts = vtk.vtkPoints()
s.SetPoints(pts)
self._spline_source.SetParametricFunction(s)
m = vtk.vtkPolyDataMapper()
m.SetInput(self._spline_source.GetOutput())
a = vtk.vtkActor()
a.SetMapper(m)
a.GetProperty().SetColor(self.line_colour)
a.GetProperty().SetLineWidth(self._normal_width)
self.props = [a]
def update_geometry(self):
pts = vtk.vtkPoints()
for p in self._line_points:
pts.InsertNextPoint(p + (0.0,))
self._spline_source.GetParametricFunction().SetPoints(pts)
self._spline_source.Update()
def get_bounds(self):
# totally hokey: for now we just return the bounding box surrounding
# the first two points - ideally we should iterate through the lines,
# find extents and pick a position and bounds accordingly
return (self._line_points[-1][0] - self._line_points[0][0],
self._line_points[-1][1] - self._line_points[0][1])
def getUpperLeftWidthHeight(self):
"""This returns the upperLeft coordinate and the width and height of
the bounding box enclosing the third-last and second-last points.
This is used for fast intersection checking with rectangles.
"""
p3 = self._line_points[-3]
p2 = self._line_points[-2]
upperLeftX = [p3[0], p2[0]][bool(p2[0] < p3[0])]
upperLeftY = [p3[1], p2[1]][bool(p2[1] < p3[1])]
width = abs(p2[0] - p3[0])
height = abs(p2[1] - p3[1])
return ((upperLeftX, upperLeftY), (width, height))
def getThirdLastSecondLast(self):
return (self._line_points[-3], self._line_points[-2])
def hitTest(self, x, y):
# maybe one day we will make the hitTest work, not tonight
# I don't need it
return False
def insertRoutingPoint(self, x, y):
"""Insert new point x,y before second-last point, i.e. the new point
becomes the third-last point.
"""
if (x,y) not in self._line_points:
self._line_points.insert(len(self._line_points) - 2, (x, y))
return True
else:
return False
def set_highlight(self):
prop = self.props[0].GetProperty()
# for more stipple patterns, see:
# http://fly.cc.fer.hr/~unreal/theredbook/chapter02.html
prop.SetLineStipplePattern(0xAAAA)
prop.SetLineStippleRepeatFactor(2)
prop.SetLineWidth(self._highlight_width)
def set_normal(self):
prop = self.props[0].GetProperty()
prop.SetLineStipplePattern(0xFFFF)
prop.SetLineStippleRepeatFactor(1)
prop.SetLineWidth(self._normal_width)
def updateEndPoints(self):
# first get us just out of the port, then create margin between
# us and glyph
dcg = DeVIDECanvasGlyph
boostFromPort = dcg._pHeight / 2 + self.routingOvershoot
self._line_points = [(), (), (), ()]
self._line_points[0] = self.fromGlyph.get_centre_of_port(
1, self.fromOutputIdx)[0:2]
self._line_points[1] = (self._line_points[0][0],
self._line_points[0][1] - boostFromPort)
self._line_points[-1] = self.toGlyph.get_centre_of_port(
0, self.toInputIdx)[0:2]
self._line_points[-2] = (self._line_points[-1][0],
self._line_points[-1][1] + boostFromPort)
#############################################################################
class DeVIDECanvasGlyph(DeVIDECanvasObject):
"""Object representing glyph on canvas.
@ivar inputLines: list of self._numInputs DeVIDECanvasLine
instances that connect to this glyph's inputs.
@ivar outputLines: list of self._numOutputs lists of
DeVIDECanvasLine instances that originate from this glyphs
outputs.
@ivar position: this is the position of the bottom left corner of
the glyph in world space. Remember that (0,0) is also bottom left
of the canvas.
"""
# at start and end of glyph
# this has to take into account the bevel edge too
_horizBorder = 12
# between ports
_horizSpacing = 10
# at top and bottom of glyph
_vertBorder = 20
_pWidth = 20
_pHeight = 20
_glyph_bevel_edge = 7
_glyph_z = 0.1
_glyph_outline_z = 0.15
_glyph_selection_z = 0.6
_glyph_blocked_z = 0.7
_port_z = 0.8
_text_z = 0.4
_glyph_normal_col = (0.75, 0.75, 0.75)
_glyph_selected_col = (0.2, 0.367, 0.656)
_glyph_blocked_col = (0.06, 0.06, 0.06)
_text_normal_col = (0.0, 0.0, 0.0)
# text_selected_col used to be white, but the vtkTextActor3D()
# has broken aliasing that is more visible on a darker
# background.
#text_selected_col = (1.0, 1.0, 1.0)
_text_selected_col = (0.0, 0.0, 0.0)
# dark green to light green
_port_conn_col = (0.0, 218 / 255.0, 25 / 255.0)
_port_disconn_col = (0, 93 / 255.0, 11 / 255.0)
def __init__(self, canvas, position, numInputs, numOutputs,
labelList, module_instance):
# parent constructor
DeVIDECanvasObject.__init__(self, canvas, position)
# we'll fill this out later
self._size = (0,0)
self._numInputs = numInputs
self.inputLines = [None] * self._numInputs
self._numOutputs = numOutputs
# be careful with list concatenation!
self.outputLines = [[] for i in range(self._numOutputs)]
self._labelList = labelList
self.module_instance = module_instance
# usually 2-element list. elem0 is 0 for input port and 1 for
# output port. elem1 is the index.
self.draggedPort = None
self.enteredPort = None
self.selected = False
self.blocked = False
# we'll collect the glyph and its ports in this assembly
self.prop1 = vtk.vtkAssembly()
# the main body glyph
self._beb = BeveledEdgeBlock()
self._selection_block = FilledBlock()
self._blocked_block = FilledBlock()
self._rbsa = vtk.vtkActor()
# and of course the label
self._tsa = vtk.vtkTextActor3D()
self._iportssa = \
[(vtk.vtkCubeSource(),vtk.vtkActor()) for _ in
range(self._numInputs)]
self._oportssa = \
[(vtk.vtkCubeSource(),vtk.vtkActor()) for _ in
range(self._numOutputs)]
self._create_geometry()
self.update_geometry()
def close(self):
del self.module_instance
del self.inputLines
del self.outputLines
def _create_geometry(self):
# TEXT LABEL ##############################################
tprop = self._tsa.GetTextProperty()
tprop.SetFontFamilyToArial()
tprop.SetFontSize(24)
tprop.SetBold(0)
tprop.SetItalic(0)
tprop.SetShadow(0)
tprop.SetColor((0,0,0))
# GLYPH BLOCK ##############################################
# remember this depth, others things have to be 'above' this
# to be visible (such as the text!)
m = vtk.vtkPolyDataMapper()
m.SetInput(self._beb.polydata)
self._rbsa.SetMapper(m)
# we need Phong shading for the gradients
p = self._rbsa.GetProperty()
p.SetInterpolationToPhong()
# Ka, background lighting coefficient
p.SetAmbient(0.1)
# light reflectance
p.SetDiffuse(0.6)
# the higher Ks, the more intense the highlights
p.SetSpecular(0.4)
# the higher the power, the more localised the
# highlights
p.SetSpecularPower(100)
self.prop1.AddPart(self._rbsa)
# GLYPH SELECTION OVERLAY #######################################
m = vtk.vtkPolyDataMapper()
m.SetInput(self._selection_block.polydata)
a = vtk.vtkActor()
a.SetMapper(m)
a.GetProperty().SetOpacity(0.3)
a.GetProperty().SetColor(self._glyph_selected_col)
self.prop1.AddPart(a)
self._selection_actor = a
# GLYPH BLOCKED OVERLAY #######################################
m = vtk.vtkPolyDataMapper()
m.SetInput(self._blocked_block.polydata)
a = vtk.vtkActor()
a.SetMapper(m)
a.GetProperty().SetOpacity(0.3)
a.GetProperty().SetColor(self._glyph_blocked_col)
self.prop1.AddPart(a)
self._blocked_actor = a
# you should really turn this into a class
# let's make a line from scratch
#m = vtk.vtkPolyDataMapper()
#m.SetInput(lp)
#a = vtk.vtkActor()
#a.SetMapper(m)
#self.prop1.AddPart(a)
#prop = a.GetProperty()
#prop.SetColor(0.1,0.1,0.1)
#prop.SetLineWidth(1)
#self._glyph_outline_polydata = lp
# INPUTS ####################################################
for i in range(self._numInputs):
s,a = self._iportssa[i]
s.SetYLength(self._pHeight)
s.SetXLength(self._pWidth)
m = vtk.vtkPolyDataMapper()
m.SetInput(s.GetOutput())
a.SetMapper(m)
self.prop1.AddPart(a)
for i in range(self._numOutputs):
s,a = self._oportssa[i]
s.SetYLength(self._pHeight)
s.SetXLength(self._pWidth)
m = vtk.vtkPolyDataMapper()
m.SetInput(s.GetOutput())
a.SetMapper(m)
self.prop1.AddPart(a)
self.prop1.SetPosition(self._position + (0.0,))
self.props = [self.prop1, self._tsa]
def update_geometry(self):
# update text label ###################################
# update the text caption
# experiments with inserting spaces in front of text were not
# successful (sizing still screws up)
#nll = [' %s' % (l,) for l in self._labelList]
nll = self._labelList
self._tsa.SetInput('\n'.join(nll))
# self._position is the bottom left corner of the button face
ap = self._position[0] + self._horizBorder, \
self._position[1] + self._vertBorder, self._text_z
self._tsa.SetPosition(ap)
tprop = self._tsa.GetTextProperty()
tcol = [self._text_normal_col, self._text_selected_col]\
[self.selected]
tprop.SetColor(tcol)
# also get the text dimensions
bb = [0,0,0,0]
self._tsa.GetBoundingBox(bb)
text_width, text_height = bb[1] - bb[0], bb[3] - bb[2]
# update glyph position and size ######################
self.props[0].SetPosition(self._position + (0.0,))
# calculate our size
# the width is the maximum(textWidth + twice the horizontal border,
# all ports, horizontal borders and inter-port borders added up)
maxPorts = max(self._numInputs, self._numOutputs)
portsWidth = 2 * self._horizBorder + \
maxPorts * self._pWidth + \
(maxPorts - 1 ) * self._horizSpacing
label_and_borders = text_width + 2 * self._horizBorder
self._size = max(portsWidth, label_and_borders), \
text_height + \
2 * self._vertBorder
# usually the position is the CENTRE of the button, so we
# adjust so that the bottom left corner ends up at 0,0
# (this is all relative to the Assembly)
self._beb.update_geometry(
self._size[0], self._size[1], self._glyph_z)
self._selection_block.update_geometry(
self._size[0], self._size[1], self._glyph_selection_z)
self._blocked_block.update_geometry(
self._size[0], self._size[1], self._glyph_blocked_z)
# calc and update glyph colour ########################
self._selection_actor.SetVisibility(self.selected)
self._blocked_actor.SetVisibility(self.blocked)
# position and colour all the inputs and outputs #####
horizOffset = self._horizBorder
horizStep = self._pWidth + self._horizSpacing
for i in range(self._numInputs):
col = [self._port_disconn_col,
self._port_conn_col][bool(self.inputLines[i])]
s,a = self._iportssa[i]
a.GetProperty().SetColor(col)
a.SetPosition(
(horizOffset + i * horizStep + 0.5 * self._pWidth,
self._size[1], self._port_z))
for i in range(self._numOutputs):
col = [self._port_disconn_col,
self._port_conn_col][bool(self.outputLines[i])]
s,a = self._oportssa[i]
a.GetProperty().SetColor(col)
a.SetPosition(
(horizOffset + i * horizStep + 0.5 * self._pWidth,
0, self._port_z))
def get_port_containing_mouse(self):
"""Given the current has_mouse and has_mouse_sub_prop
information in canvas.event, determine the port side (input,
output) and index of the port represented by the sub_prop.
gah.
@returns: tuple (inout, idx), where inout is 0 for input (top)
and 1 for output (bottom). Returns (-1,-1) if nothing was
found.
"""
if not self.canvas.event.picked_cobject is self:
return (-1, -1)
sp = self.canvas.event.picked_sub_prop
if not sp:
return (-1, -1)
for i in range(len(self._iportssa)):
s, a = self._iportssa[i]
if sp is a:
return (0,i)
for i in range(len(self._oportssa)):
s, a = self._oportssa[i]
if sp is a:
return (1,i)
return (-1, -1)
def get_bounds(self):
return self._size
def get_centre_of_port(self, inOrOut, idx):
"""Given the side of the module and the index of the port,
return the centre of the port in 3-D world coordinates.
@param inOrOut: 0 is input side (top), 1 is output side
(bottom).
@param idx: zero-based index of the port.
"""
horizOffset = self._position[0] + self._horizBorder
horizStep = self._pWidth + self._horizSpacing
cy = self._position[1] #+ self._pHeight / 2
# remember, in world-space, y=0 is at the bottom!
if inOrOut == 0:
cy += self._size[1]
cx = horizOffset + idx * horizStep + self._pWidth / 2
return (cx, cy, 0.0)
def get_bottom_left_top_right(self):
return ((self._position[0],
self._position[1]),
(self._position[0] + self._size[0] - 1,
self._position[1] + self._size[1] - 1))
def getLabel(self):
return ' '.join(self._labelList)
def is_inside_rect(self, bottom_left, w, h):
"""Given world coordinates for the bottom left corner and a
width and a height, determine if the complete glyph is inside.
This method will ensure that bottom-left is bottom-left by
swapping coordinates around
"""
bl = list(bottom_left)
tr = list((bl[0] + w, bl[1] + h))
if bl[0] > tr[0]:
# swap!
bl[0],tr[0] = tr[0],bl[0]
if bl[1] > tr[1]:
bl[1],tr[1] = tr[1],bl[1]
inside = True
if self._position[0] < bl[0] or self._position[1] < bl[1]:
inside = False
elif (self._position[0] + self._size[0]) > tr[0] or \
(self._position[1] + self._size[1]) > tr[1]:
inside = False
return inside
def is_origin_inside_rect(self, bottom_left, w, h):
"""Only check origin (bottom-left) of glyph for containtment
in specified rectangle.
"""
bl = list(bottom_left)
tr = list((bl[0] + w, bl[1] + h))
if bl[0] > tr[0]:
# swap!
bl[0],tr[0] = tr[0],bl[0]
if bl[1] > tr[1]:
bl[1],tr[1] = tr[1],bl[1]
inside = True
if self._position[0] < bl[0] or self._position[1] < bl[1]:
inside = False
return inside
def setLabelList(self,labelList):
self._labelList = labelList
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
import vtk
from module_kits.misc_kit.mixins import SubjectMixin
from devide_canvas_object import DeVIDECanvasGlyph
import operator
import wx # we're going to use this for event handling
from module_kits.misc_kit import dprint
# think about turning this into a singleton.
class DeVIDECanvasEvent:
def __init__(self):
# last event information ############
self.wx_event = None
self.name = None
# pos is in wx-coords, i.e. top-left is 0,0
self.pos = (0,0)
# last_pos and pos_delta follow same convention
self.last_pos = (0,0)
self.pos_delta = (0,0)
# disp_pos is in VTK display coords: bottom-left is 0,0
self.disp_pos = (0,0)
self.world_pos = (0,0,0)
# state information #################
self.left_button = False
self.middle_button = False
self.right_button = False
self.clicked_object = None
# which cobject has the mouse
self.picked_cobject = None
self.picked_sub_prop = None
class DeVIDECanvas(SubjectMixin):
"""Give me a vtkRenderWindowInteractor with a Renderer, and I'll
do the rest. YEAH.
"""
def __init__(self, renderwindowinteractor, renderer):
self._rwi = renderwindowinteractor
self._ren = renderer
# need this to do same mouse capturing as original RWI under Win
self._rwi_use_capture = \
vtk.wx.wxVTKRenderWindowInteractor._useCapture
# we can't switch on Line/Point/Polygon smoothing here,
# because the renderwindow has already been initialised
# we do it in main_frame.py right after we create the RWI
# parent 2 ctor
SubjectMixin.__init__(self)
self._cobjects = []
# dict for mapping from prop back to cobject
self.prop_to_glyph = {}
self._previousRealCoords = None
self._potentiallyDraggedObject = None
self._draggedObject = None
self._ren.SetBackground(1.0,1.0,1.0)
self._ren.GetActiveCamera().SetParallelProjection(1)
# set a sensible initial zoom
self._zoom(0.004)
istyle = vtk.vtkInteractorStyleUser()
#istyle = vtk.vtkInteractorStyleImage()
self._rwi.SetInteractorStyle(istyle)
self._rwi.Bind(wx.EVT_RIGHT_DOWN, self._handler_rd)
self._rwi.Bind(wx.EVT_RIGHT_UP, self._handler_ru)
self._rwi.Bind(wx.EVT_LEFT_DOWN, self._handler_ld)
self._rwi.Bind(wx.EVT_LEFT_UP, self._handler_lu)
self._rwi.Bind(wx.EVT_MIDDLE_DOWN, self._handler_md)
self._rwi.Bind(wx.EVT_MIDDLE_UP, self._handler_mu)
self._rwi.Bind(wx.EVT_MOUSEWHEEL, self._handler_wheel)
self._rwi.Bind(wx.EVT_MOTION, self._handler_motion)
self._rwi.Bind(wx.EVT_LEFT_DCLICK, self._handler_ldc)
#self._rwi.Bind(wx.EVT_ENTER_WINDOW, self.OnEnter)
#self._rwi.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave)
# If we use EVT_KEY_DOWN instead of EVT_CHAR, capital versions
# of all characters are always returned. EVT_CHAR also performs
# other necessary keyboard-dependent translations.
# * we unbind the char handler added by the wxRWI (else alt-w
# for example gets interpreted as w for wireframe e.g.)
self._rwi.Unbind(wx.EVT_CHAR)
self._rwi.Bind(wx.EVT_CHAR, self._handler_char)
#self._rwi.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
self._observer_ids = []
self.event = DeVIDECanvasEvent()
# do initial drawing here.
def close(self):
# first remove all objects
# (we could do this more quickly, but we're opting for neatly)
for i in range(len(self._cobjects)-1,-1,-1):
cobj = self._cobjects[i]
self.remove_object(cobj)
for i in self._observer_ids:
self._rwi.RemoveObserver(i)
del self._rwi
del self._ren
# nuke this function, replace with display_to_world.
# events are in display, everything else in world.
# go back to graph_editor
def eventToRealCoords_DEPRECATED(self, ex, ey):
"""Convert window event coordinates to canvas relative coordinates.
"""
# get canvas parameters
vsx, vsy = self.GetViewStart()
dx, dy = self.GetScrollPixelsPerUnit()
# calculate REAL coords
rx = ex + vsx * dx
ry = ey + vsy * dy
return (rx, ry)
def display_to_world(self, dpt):
"""Takes 3-D display point as input, returns 3-D world point.
"""
# make sure we have 3 elements
if len(dpt) < 3:
dpt = tuple(dpt) + (0.0,)
elif len(dpt) > 3:
dpt = tuple(dpt[0:3])
self._ren.SetDisplayPoint(dpt)
self._ren.DisplayToWorld()
return self._ren.GetWorldPoint()[0:3]
def world_to_display(self, wpt):
"""Takes 3-D world point as input, returns 3-D display point.
"""
self._ren.SetWorldPoint(tuple(wpt) + (0.0,)) # this takes 4-vec
self._ren.WorldToDisplay()
return self._ren.GetDisplayPoint()
def flip_y(self, y):
return self._rwi.GetSize()[1] - y - 1
def wx_to_world(self, wx_x, wx_y):
disp_x = wx_x
disp_y = self.flip_y(wx_y)
world_depth = 0.0
disp_z = self.world_to_display((0.0,0.0, world_depth))[2]
wex, wey, wez = self.display_to_world((disp_x,disp_y,disp_z))
return (wex, wey, wez)
def _helper_handler_capture_release(self, button):
"""Helper method to be called directly after preamble
helper in button up handlers in order to release mouse.
@param button Text description of which button was pressed,
e.g. 'left'
"""
# if the same button is released that captured the mouse,
# and we have the mouse, release it. (we need to get rid
# of this as soon as possible; if we don't and one of the
# event handlers raises an exception, mouse is never
# released.)
if self._rwi_use_capture and self._rwi._own_mouse and \
button==self._rwi._mouse_capture_button:
self._rwi.ReleaseMouse()
self._rwi._own_mouse = False
def _helper_handler_capture(self, button):
"""Helper method to be called at end after button down
helpers.
@param button Text description of button that was pressed,
e.g. 'left'.
"""
# save the button and capture mouse until the button is
# released we only capture the mouse if it hasn't already
# been captured
if self._rwi_use_capture and not self._rwi._own_mouse:
self._rwi._own_mouse = True
self._rwi._mouse_capture_button = button
self._rwi.CaptureMouse()
def _helper_handler_preamble(self, e, focus=True):
e.Skip(False)
# Skip(False) won't search for other event
# handlers
self.event.wx_event = e
if focus:
# we need to take focus... else some other subwindow keeps it
# once we've been there to select a module for example
self._rwi.SetFocus()
def _helper_glyph_button_down(self, event_name):
ex, ey = self.event.disp_pos
ret = self._pick_glyph(ex,ey)
if ret:
pc, psp = ret
self.event.clicked_object = pc
self.event.name = event_name
pc.notify(event_name)
else:
self.event.clicked_object = None
# we only give the canvas the event if the glyph didn't
# take it
self.event.name = event_name
self.notify(event_name)
def _helper_glyph_button_up(self, event_name):
ex, ey = self.event.disp_pos
ret = self._pick_glyph(ex,ey)
if ret:
pc, psp = ret
self.event.name = event_name
pc.notify(event_name)
else:
self.event.name = event_name
self.notify(event_name)
# button goes up, object is not clicked anymore
self.event.clicked_object = None
def _handler_char(self, e):
# we're disabling all VTK. if we don't, the standard
# VTK keys such as 'r' (reset), '3' (stereo) and especially
# 'f' (fly to) can screw up things quite badly.
# if ctrl, shift or alt is involved, we should pass it on to
# wx (could be menu keys for example).
# if not, we just eat up the event.
if e.ControlDown() or e.ShiftDown() or e.AltDown():
e.Skip()
def _handler_ld(self, e):
self._helper_handler_preamble(e)
#ctrl, shift = event.ControlDown(), event.ShiftDown()
#self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),
# ctrl, shift, chr(0), 0, None)
self.event.left_button = True
self._helper_glyph_button_down('left_button_down')
self._helper_handler_capture('l')
def _handler_lu(self, e):
dprint("_handler_lu::")
self._helper_handler_preamble(e, focus=False)
self._helper_handler_capture_release('l')
self.event.left_button = False
self._helper_glyph_button_up('left_button_up')
def _handler_ldc(self, e):
self._helper_handler_preamble(e)
self._helper_glyph_button_down('left_button_dclick')
def _handler_md(self, e):
self._helper_handler_preamble(e)
self.event.middle_button = True
self._helper_glyph_button_down('middle_button_down')
def _handler_mu(self, e):
self._helper_handler_preamble(e, focus=False)
self.event.middle_button = False
self._helper_glyph_button_up('middle_button_up')
def _handler_rd(self, e):
self._helper_handler_preamble(e)
if e.Dragging():
return
self.event.right_button = True
self._helper_glyph_button_down('right_button_down')
def _handler_ru(self, e):
self._helper_handler_preamble(e, focus=False)
if e.Dragging():
return
self.event.right_button = False
self._helper_glyph_button_up('right_button_up')
def _pick_glyph(self, ex, ey):
"""Give current VTK display position.
"""
p = vtk.vtkPicker()
p.SetTolerance(0.00001) # this is perhaps still too large
for i in self._cobjects:
if isinstance(i, DeVIDECanvasGlyph):
for prop in i.props:
p.AddPickList(prop)
p.PickFromListOn()
ret = p.Pick((ex, ey, 0), self._ren)
if ret:
#pc = p.GetProp3Ds()
#pc.InitTraversal()
#prop = pc.GetNextItemAsObject()
prop = p.GetAssembly() # for now we only want this.
try:
picked_cobject = self.prop_to_glyph[prop]
except KeyError:
dprint("_pick_glyph:: couldn't find prop in p2g dict")
return None
else:
# need to find out WHICH sub-actor was picked.
if p.GetPath().GetNumberOfItems() == 2:
sub_prop = \
p.GetPath().GetItemAsObject(1).GetViewProp()
else:
sub_prop = None
# our assembly is one level deep, so 1 is the one we
# want (actor at leaf node)
return (picked_cobject, sub_prop)
return None
def _zoom(self, amount):
cam = self._ren.GetActiveCamera()
if cam.GetParallelProjection():
cam.SetParallelScale(cam.GetParallelScale() / amount)
else:
self._ren.GetActiveCamera().Dolly(amount)
self._ren.ResetCameraClippingRange()
self._ren.UpdateLightsGeometryToFollowCamera()
self.redraw()
def _handler_wheel(self, event):
# wheel forward = zoom in
# wheel backward = zoom out
factor = [-2.0, 2.0][event.GetWheelRotation() > 0.0]
self._zoom(1.1 ** factor)
#event.GetWheelDelta()
def get_top_left_world(self):
"""Return top-left of canvas (0,0 in wx) in world coords.
In world coordinates, top_y > bottom_y.
"""
return self.wx_to_world(0,0)
def get_bottom_right_world(self):
"""Return bottom-right of canvas (sizex, sizey in wx) in world
coords.
In world coordinates, bottom_y < top_y.
"""
x,y = self._rwi.GetSize()
return self.wx_to_world(x-1, y-1)
def get_wh_world(self):
"""Return width and height of visible canvas in world
coordinates.
"""
tl = self.get_top_left_world()
br = self.get_bottom_right_world()
return br[0] - tl[0], tl[1] - br[1]
def get_motion_vector_world(self, world_depth):
"""Calculate motion vector in world space represented by last
mouse delta.
"""
c = self._ren.GetActiveCamera()
display_depth = self.world_to_display((0.0,0.0, world_depth))[2]
new_pick_pt = self.display_to_world(self.event.disp_pos +
(display_depth,))
fy = self.flip_y(self.event.last_pos[1])
old_pick_pt = self.display_to_world((self.event.last_pos[0], fy,
display_depth))
# old_pick_pt - new_pick_pt (reverse of camera!)
motion_vector = map(operator.sub, new_pick_pt,
old_pick_pt)
return motion_vector
def _handler_motion(self, event):
"""MouseMoveEvent observer for RWI.
o contains a binding to the RWI.
"""
#self._helper_handler_preamble(event)
self.event.wx_event = event
# event position is viewport relative (i.e. in pixels,
# top-left is 0,0)
ex, ey = event.GetX(), event.GetY()
# we need to flip Y to get VTK display coords
self.event.disp_pos = ex, self._rwi.GetSize()[1] - ey - 1
# before setting the new pos, record the delta
self.event.pos_delta = (ex - self.event.pos[0],
ey - self.event.pos[1])
self.event.last_pos = self.event.pos
self.event.pos = ex, ey
wex, wey, wez = self.display_to_world(self.event.disp_pos)
self.event.world_pos = wex, wey, wez
# add the "real" coords to the event structure
self.event.realX = wex
self.event.realY = wey
self.event.realZ = wez
# dragging gets preference...
if event.Dragging() and event.MiddleIsDown() and event.ShiftDown():
centre = self._ren.GetCenter()
# drag up = zoom in
# drag down = zoom out
dyf = - 10.0 * self.event.pos_delta[1] / centre[1]
self._zoom(1.1 ** dyf)
elif event.Dragging() and event.MiddleIsDown():
# move camera, according to self.event.pos_delta
c = self._ren.GetActiveCamera()
cfp = list(c.GetFocalPoint())
cp = list(c.GetPosition())
focal_depth = self.world_to_display(cfp)[2]
new_pick_pt = self.display_to_world(self.event.disp_pos +
(focal_depth,))
fy = self.flip_y(self.event.last_pos[1])
old_pick_pt = self.display_to_world((self.event.last_pos[0], fy,
focal_depth))
# old_pick_pt - new_pick_pt (reverse of camera!)
motion_vector = map(operator.sub, old_pick_pt,
new_pick_pt)
new_cfp = map(operator.add, cfp, motion_vector)
new_cp = map(operator.add, cp, motion_vector)
c.SetFocalPoint(new_cfp)
c.SetPosition(new_cp)
self.redraw()
else: # none of the preference events want this...
pg_ret = self._pick_glyph(ex, self.flip_y(ey))
if pg_ret:
picked_cobject, self.event.picked_sub_prop = pg_ret
if self.event.left_button and event.Dragging() and \
self.event.clicked_object == picked_cobject:
# left dragging on a glyph only works if THAT
# glyph was clicked (and the mouse button is still
# down)
self.event.name = 'dragging'
if self._draggedObject is None:
self._draggedObject = picked_cobject
# the actual event will be fired further below
if not picked_cobject is self.event.picked_cobject:
self.event.picked_cobject = picked_cobject
self.event.name = 'enter'
picked_cobject.notify('enter')
else:
self.event.name = 'motion'
picked_cobject.notify('motion')
else:
# nothing under the mouse...
if self.event.picked_cobject:
self.event.name = 'exit'
self.event.picked_cobject.notify('exit')
self.event.picked_cobject = None
if event.Dragging() and self._draggedObject:
# so we are Dragging() and there is a draggedObject...
# whether draggedObject was set above, or in a
# previous call of this event handler, we have to keep
# on firing these drag events until draggedObject is
# canceled.
self.event.name = 'dragging'
self._draggedObject.notify('dragging')
if event.Dragging and not self._draggedObject:
# user is dragging on canvas (no draggedObject!)
self.event.name = 'dragging'
self.notify(self.event.name)
if not event.Dragging():
# when user stops dragging the mouse, lose the object
if not self._draggedObject is None:
dprint("_handler_motion:: dragging -> off")
self._draggedObject.draggedPort = None
self._draggedObject = None
def add_object(self, cobj):
if cobj and cobj not in self._cobjects:
cobj.canvas = self
self._cobjects.append(cobj)
for prop in cobj.props:
self._ren.AddViewProp(prop)
# we only add prop to cobject if it's a glyph
if isinstance(cobj, DeVIDECanvasGlyph):
self.prop_to_glyph[prop] = cobj
cobj.__hasMouse = False
def redraw(self):
"""Redraw the whole scene.
"""
self._rwi.Render()
def update_all_geometry(self):
"""Update all geometry.
This is useful if many of the objects states have been changed
(e.g. new connections) and the connection visual states have
to be updated.
"""
for o in self._cobjects:
o.update_geometry()
def update_picked_cobject_at_drop(self, ex, ey):
"""Method to be used in the GraphEditor DropTarget
(geCanvasDropTarget) to make sure that the correct glyph is
selected.
Problem is that the application gets blocked during
wxDropSource.DoDragDrop(), so that if the user drags things
from for example the DICOMBrowser to a DICOMReader on the
canvas, the canvas doesn't know that the DICOMReader has been
picked.
If this method is called at drop time, all is well.
"""
pg_ret = self._pick_glyph(ex, self.flip_y(ey))
if pg_ret:
self.event.picked_cobject, self.event.picked_sub_prop = pg_ret
def remove_object(self, cobj):
if cobj and cobj in self._cobjects:
for prop in cobj.props:
self._ren.RemoveViewProp(prop)
# it's only in here if it's a glyph
if isinstance(cobj, DeVIDECanvasGlyph):
del self.prop_to_glyph[prop]
cobj.canvas = None
if self._draggedObject == cobj:
self._draggedObject = None
del self._cobjects[self._cobjects.index(cobj)]
def reset_view(self):
"""Make sure that all actors (glyphs, connections, etc.) are
visible.
"""
self._ren.ResetCamera()
self.redraw()
def getDraggedObject(self):
return self._draggedObject
def getObjectsOfClass(self, classt):
return [i for i in self._cobjects if isinstance(i, classt)]
def getObjectWithMouse(self):
"""Return object currently containing mouse, None if no object has
the mouse.
"""
for cobject in self._cobjects:
if cobject.__hasMouse:
return cobject
return None
def drag_object(self, cobj, delta):
"""Move object with delta in world space.
"""
cpos = cobj.get_position() # this gives us 2D in world space
npos = (cpos[0] + delta[0], cpos[1] + delta[1])
cobj.set_position(npos)
cobj.update_geometry()
def pan_canvas_world(self, delta_x, delta_y):
c = self._ren.GetActiveCamera()
cfp = list(c.GetFocalPoint())
cfp[0] += delta_x
cfp[1] += delta_y
c.SetFocalPoint(cfp)
cp = list(c.GetPosition())
cp[0] += delta_x
cp[1] += delta_y
c.SetPosition(cp)
self.redraw()
| Python |
# dummy
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
# I could have done this with just a module variable, but I found this
# Borg thingy too nice not to use. See:
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531
class CounterBorg:
"""Borg-pattern (similar to a Singleton) for maintaining a
monotonically increasing counter.
Instantiate this anywhere, and call get() to return and increment
the increasing counter. DeVIDE uses this to stamp modified and
execute times of modules.
"""
# we start with 1, so that client code can init to 0 and guarantee
# an initial invalid state. The counter is explicitly long, this
# gives us unlimited precision (up to your memory limits, YEAH!)
__shared_state = {'counter' : 1L}
def __init__(self):
self.__dict__ = self.__shared_state
def get(self):
c = self.counter
self.counter += 1
return c
def counter():
return CounterBorg().get()
| Python |
"""Module to test basic DeVIDE functionality.
"""
import unittest
class BasicVTKTest(unittest.TestCase):
def test_vtk_exceptions(self):
"""Test if VTK has been patched with our VTK error to Python exception
patch.
"""
import vtk
a = vtk.vtkXMLImageDataReader()
a.SetFileName('blata22 hello')
b = vtk.vtkMarchingCubes()
b.SetInput(a.GetOutput())
try:
b.Update()
except RuntimeError, e:
self.failUnless(str(e).startswith('ERROR'))
else:
self.fail('VTK object did not raise Python exception.')
def test_vtk_progress_exception_masking(self):
"""Ensure progress events are not masking exceptions.
"""
import vtk
import vtkdevide
def observer_progress(o, e):
print "DICOM progress %s." % (str(o.GetProgress() * 100.0),)
r = vtkdevide.vtkDICOMVolumeReader()
r.AddObserver("ProgressEvent", observer_progress)
try:
r.Update()
except RuntimeError, e:
pass
else:
self.fail('ProgressEvent handler masked RuntimeError.')
def test_vtk_pyexception_deadlock(self):
"""Test if VTK has been patched to release the GIL during all
VTK method calls.
"""
import vtk
# this gives floats by default
s = vtk.vtkImageGridSource()
c1 = vtk.vtkImageCast()
c1.SetOutputScalarTypeToShort()
c1.SetInput(s.GetOutput())
c2 = vtk.vtkImageCast()
c2.SetOutputScalarTypeToFloat()
c2.SetInput(s.GetOutput())
m = vtk.vtkImageMathematics()
# make sure we are multi-threaded
if m.GetNumberOfThreads() < 2:
m.SetNumberOfThreads(2)
m.SetInput1(c1.GetOutput())
m.SetInput2(c2.GetOutput())
# without the patch, this call will deadlock forever
try:
# with the patch this should generate a RuntimeError
m.Update()
except RuntimeError:
pass
else:
self.fail(
'Multi-threaded error vtkImageMathematics did not raise '
'exception.')
def get_suite(devide_testing):
devide_app = devide_testing.devide_app
mm = devide_app.get_module_manager()
basic_vtk_suite = unittest.TestSuite()
if 'vtk_kit' not in mm.module_kits.module_kit_list:
return basic_vtk_suite
t = BasicVTKTest('test_vtk_exceptions')
basic_vtk_suite.addTest(t)
t = BasicVTKTest('test_vtk_progress_exception_masking')
basic_vtk_suite.addTest(t)
t = BasicVTKTest('test_vtk_pyexception_deadlock')
basic_vtk_suite.addTest(t)
return basic_vtk_suite
| Python |
from module_kits.vtk_kit.mixins import SimpleVTKClassModuleBase
import vtk
class emp_test(SimpleVTKClassModuleBase):
"""This is the minimum you need to wrap a single VTK object. This
__doc__ string will be replaced by the __doc__ string of the encapsulated
VTK object, i.e. vtkStripper in this case.
With these few lines, we have error handling, progress reporting, module
help and also: the complete state of the underlying VTK object is also
pickled, i.e. when you save and restore a network, any changes you've
made to the vtkObject will be restored.
"""
def __init__(self, module_manager):
SimpleVTKClassModuleBase.__init__(
self, module_manager,
vtk.vtkStripper(), 'Stripping polydata.',
('vtkPolyData',), ('Stripped vtkPolyData',))
| Python |
# $Id: module_index.py 2790 2008-02-29 08:33:14Z cpbotha $
class emp_test:
kits = ['vtk_kit']
cats = ['Tests']
keywords = ['test', 'tests', 'testing']
help = \
"""Module to test DeVIDE extra-module-paths functionality.
"""
| Python |
"""Module to test basic DeVIDE functionality.
"""
import unittest
class PythonShellTest(unittest.TestCase):
def test_python_shell(self):
"""Test if PythonShell can be opened successfully.
"""
iface = self._devide_app.get_interface()
iface._handler_menu_python_shell(None)
self.failUnless(iface._python_shell._frame.IsShown())
iface._python_shell._frame.Show(False)
class HelpContentsTest(unittest.TestCase):
def test_help_contents(self):
"""Test if Help Contents can be opened successfully.
"""
import webbrowser
try:
self._devide_app.get_interface()._handlerHelpContents(None)
except webbrowser.Error:
self.fail()
def get_suite(devide_testing):
devide_app = devide_testing.devide_app
# both of these tests require wx
mm = devide_app.get_module_manager()
basic_suite = unittest.TestSuite()
if 'wx_kit' in mm.module_kits.module_kit_list:
t = PythonShellTest('test_python_shell')
t._devide_app = devide_app
basic_suite.addTest(t)
t = HelpContentsTest('test_help_contents')
t._devide_app = devide_app
basic_suite.addTest(t)
return basic_suite
| Python |
"""Module to test basic matplotlib functionality.
"""
import os
import unittest
import tempfile
class MPLTest(unittest.TestCase):
def test_figure_output(self):
"""Test if matplotlib figure can be generated and wrote to disc.
"""
# make sure the pythonshell is running
self._devide_app.get_interface()._handler_menu_python_shell(None)
# create new figure
python_shell = self._devide_app.get_interface()._python_shell
f = python_shell.mpl_new_figure()
import pylab
# unfortunately, it's almost impossible to get pixel-identical
# rendering on all platforms, so we can only check that the plot
# itself is correct (all font-rendering is disabled)
# make sure we hardcode the font! (previous experiment)
#pylab.rcParams['font.sans-serif'] = ['Bitstream Vera Sans']
#pylab.rc('font', family='sans-serif')
from pylab import arange, plot, sin, cos, legend, grid, xlabel, ylabel
a = arange(-30, 30, 0.01)
plot(a, sin(a) / a, label='sinc(x)')
plot(a, cos(a), label='cos(x)')
#legend()
grid()
#xlabel('x')
#ylabel('f(x)')
# disable x and y ticks (no fonts allowed, remember)
pylab.xticks([])
pylab.yticks([])
# width and height in inches
f.set_figwidth(7.9)
f.set_figheight(5.28)
# and save it to disc
filename1 = tempfile.mktemp(suffix='.png', prefix='tmp', dir=None)
f.savefig(filename1, dpi=100)
# get rid of the figure
python_shell.mpl_close_figure(f)
# now compare the bugger
test_fn = os.path.join(self._devide_testing.get_images_dir(),
'mpl_test_figure_output.png')
err = self._devide_testing.compare_png_images(test_fn, filename1)
self.failUnless(err == 0, '%s differs from %s, err = %.2f' %
(filename1, test_fn, err))
def get_suite(devide_testing):
devide_app = devide_testing.devide_app
# both of these tests require wx
mm = devide_app.get_module_manager()
mpl_suite = unittest.TestSuite()
if 'matplotlib_kit' in mm.module_kits.module_kit_list:
t = MPLTest('test_figure_output')
t._devide_app = devide_app
t._devide_testing = devide_testing
mpl_suite.addTest(t)
return mpl_suite
| Python |
"""Module to test graph_editor functionality.
"""
import os
import time
import unittest
import wx
class GraphEditorTestBase(unittest.TestCase):
def setUp(self):
self._iface = self._devide_app.get_interface()
self._ge = self._iface._graph_editor
# the graph editor frame is now the main frame of the interface
self._ge_frame = self._iface._main_frame
# make sure the graphEditor is running
self._iface._handlerMenuGraphEditor(None)
# make sure we begin with a clean slate, so we can do
# some module counting
self._ge.clear_all_glyphs_from_canvas()
def tearDown(self):
self._ge.clear_all_glyphs_from_canvas()
del self._ge
del self._iface
del self._ge_frame
class GraphEditorVolumeTestBase(GraphEditorTestBase):
"""Uses superQuadric, implicitToVolume and doubleThreshold to create
a volume that we can run some tests on.
"""
def setUp(self):
# call parent setUp method
GraphEditorTestBase.setUp(self)
# now let's build a volume we can play with
# first the three modules
(sqmod, sqglyph) = self._ge.create_module_and_glyph(
10, 10, 'modules.misc.superQuadric')
self.failUnless(sqmod and sqglyph)
(ivmod, ivglyph) = self._ge.create_module_and_glyph(
10, 70, 'modules.misc.implicitToVolume')
self.failUnless(ivmod and ivglyph)
(dtmod, dtglyph) = self._ge.create_module_and_glyph(
10, 130, 'modules.filters.doubleThreshold')
self.failUnless(dtmod and dtglyph)
# configure the implicitToVolume to have somewhat tighter bounds
cfg = ivmod.get_config()
cfg.modelBounds = (-1.0, 1.0, -0.25, 0.25, 0.0, 0.75)
ivmod.set_config(cfg)
# then configure the doubleThreshold with the correct thresholds
cfg = dtmod.get_config()
cfg.lowerThreshold = -99999.00
cfg.upperThreshold = 0.0
dtmod.set_config(cfg)
# now connect them all
ret = self._ge._connect(sqglyph, 0, ivglyph, 0)
ret = self._ge._connect(ivglyph, 0, dtglyph, 0)
# redraw
self._ge.canvas.redraw()
# run the network
self._ge._handler_execute_network(None)
self.dtglyph = dtglyph
self.dtmod = dtmod
self.sqglyph = sqglyph
self.sqmod = sqmod
# ----------------------------------------------------------------------------
class GraphEditorBasic(GraphEditorTestBase):
def test_startup(self):
"""graphEditor startup.
"""
self.failUnless(
self._ge_frame.IsShown())
def test_module_creation_deletion(self):
"""Creation of simple module and glyph.
"""
(mod, glyph) = self._ge.create_module_and_glyph(
10, 10, 'modules.misc.superQuadric')
self.failUnless(mod and glyph)
ret = self._ge._delete_module(glyph)
self.failUnless(ret)
def test_module_help(self):
"""See if module specific help can be called up for a module.
"""
module_name = 'modules.writers.vtiWRT'
(mod, glyph) = self._ge.create_module_and_glyph(
10, 10, module_name)
self.failUnless(mod and glyph)
self._ge.show_module_help_from_glyph(glyph)
# DURNIT! We can't read back the help HTML from the HtmlWindow!
# make sure that the help is actually displayed in the doc window
#mm = self._devide_app.get_module_manager()
#ht = mm._available_modules[module_name].help
#p = self._ge_frame.doc_window.GetPage()
# fail if it's not there
#self.failUnless(p == self._ge._module_doc_to_html(module_name, ht))
# take it away
ret = self._ge._delete_module(glyph)
self.failUnless(ret)
def test_module_search(self):
import wx
class DummyKeyEvent:
def __init__(self, key_code):
self._key_code = key_code
def GetKeyCode(self):
return self._key_code
# type some text in the module search box
self._ge_frame.search.SetValue('fillholes')
# now place the module by pressing RETURN (simulated)
evt = DummyKeyEvent(wx.WXK_RETURN)
self._ge._handler_search_char(evt)
# check that the imageFillHoles module has been placed
ag = self._ge._get_all_glyphs()
module_name = str(ag[0].module_instance.__class__.__name__)
expected_name = 'imageFillHoles'
self.failUnless(module_name == expected_name, '%s != %s' %
(module_name, expected_name))
def test_simple_network(self):
"""Creation, connection and execution of superQuadric source and
slice3dVWR.
"""
(sqmod, sqglyph) = self._ge.create_module_and_glyph(
10, 10, 'modules.misc.superQuadric')
(svmod, svglyph) = self._ge.create_module_and_glyph(
10, 90, 'modules.viewers.slice3dVWR')
ret = self._ge._connect(sqglyph, 1, svglyph, 0)
self._ge.canvas.redraw()
self.failUnless(ret)
# now run the network
self._ge._handler_execute_network(None)
# the slice viewer should now have an extra object
self.failUnless(svmod._tdObjects.findObjectByName('obj0'))
def test_config_vtk_obj(self):
"""See if the ConfigVtkObj is available and working.
"""
# first create superQuadric
(sqmod, sqglyph) = self._ge.create_module_and_glyph(
10, 10, 'modules.misc.superQuadric')
self.failUnless(sqmod and sqglyph)
self._ge._view_conf_module(sqmod)
# superQuadric is a standard ScriptedConfigModuleMixin, so it has
# a _viewFrame ivar
self.failUnless(sqmod._view_frame.IsShown())
# start up the vtkObjectConfigure window for that object
sqmod.vtkObjectConfigure(sqmod._view_frame, None, sqmod._superquadric)
# check that it's visible
# sqmod._vtk_obj_cfs[sqmod._superquadric] is the ConfigVtkObj instance
self.failUnless(
sqmod._vtk_obj_cfs[sqmod._superquadric]._frame.IsShown())
# end by closing them all (so now all we're left with is the
# module view itself)
sqmod.closeVtkObjectConfigure()
# remove the module as well
ret = self._ge._delete_module(sqglyph)
self.failUnless(ret)
# ----------------------------------------------------------------------------
class TestReadersWriters(GraphEditorVolumeTestBase):
def test_vti(self):
"""Testing basic readers/writers.
"""
self.failUnless(1 == 1)
class TestModulesMisc(GraphEditorTestBase):
def get_sorted_core_module_list(self):
"""Utility function to get a sorted list of all core module names.
"""
mm = self._devide_app.get_module_manager()
# we tested all the vtk_basic modules once with VTK5.0
# but this causes trouble on Weendows.
ml = mm.get_available_modules().keys()
ml = [i for i in ml
if not i.startswith('modules.vtk_basic') and
not i.startswith('modules.user')]
ml.sort()
return ml
def test_create_destroy(self):
"""See if we can create and destroy all core modules, without invoking
up the view window..
"""
ml = self.get_sorted_core_module_list()
for module_name in ml:
print 'About to create %s.' % (module_name,)
(cmod, cglyph) = self._ge.\
create_module_and_glyph(
10, 10, module_name)
print 'Created %s.' % (module_name,)
self.failUnless(cmod and cglyph,
'Error creating %s' % (module_name,))
# destroy
ret = self._ge._delete_module(
cglyph)
print 'Destroyed %s.' % (module_name,)
self.failUnless(ret,
'Error destroying %s' % (module_name,))
# so wx can take a breath and catch up
wx.Yield()
def test_create_view_destroy(self):
"""Create and destroy all core modules, also invoke view window.
"""
ml = self.get_sorted_core_module_list()
for module_name in ml:
print 'About to create %s.' % (module_name,)
(cmod, cglyph) = self._ge.\
create_module_and_glyph(
10, 10, module_name)
print 'Created %s.' % (module_name,)
self.failUnless(cmod and cglyph,
'Error creating %s' % (module_name,))
# call up view window
print 'About to bring up view-conf window'
try:
self._ge._view_conf_module(cmod)
except Exception, e:
self.fail(
'Error invoking view of %s (%s)' % (module_name,str(e)))
# destroy
ret = self._ge._delete_module(
cglyph)
print 'Destroyed %s.' % (module_name,)
self.failUnless(ret,
'Error destroying %s' % (module_name,))
# so wx can take a breath and catch up
wx.Yield()
# ----------------------------------------------------------------------------
class TestVTKBasic(GraphEditorTestBase):
def test_seedconnect(self):
"""Test whether we can load and run a full network, select a point and
do a region growing. This broke with the introduction of vtk 5.6.1 due
to more strict casting.
"""
# load our little test network #####
self._ge._load_and_realise_network(
os.path.join(self._devide_testing.get_networks_dir(),
'seedconnect.dvn'))
# run the network once
self._ge._handler_execute_network(None)
self._ge.canvas.redraw()
# now find the slice3dVWR #####
mm = self._devide_app.get_module_manager()
svmod = mm.get_instance("svmod")
# let's show the control frame
svmod._handlerShowControls(None)
if True:
# we're doing this the long way to test more code paths
svmod.sliceDirections.setCurrentCursor([20.0, 20.0, 20.0, 1.0])
# this handler should result in the whole network being auto-executed
# but somehow it blocks execution (the vktImageSeedConnect sticks at 0.0)
svmod.selectedPoints._handlerStoreCursorAsPoint(None)
else:
# it seems to block here as well: the whole network is linked up,
# so it tries to execute when the storeCursor is called, and that
# blocks everything. WHY?!
#svmod.selectedPoints._storeCursor((20.0,20.0,20.0,1.0))
#self.failUnless(len(svmod.selectedPoints._pointsList) == 1)
# execute the network
self._ge._handler_execute_network(None)
# now count the number of voxels in the segmented result
import vtk
via = vtk.vtkImageAccumulate()
scmod = mm.get_instance("scmod")
via.SetInput(scmod.get_output(0))
via.Update()
# get second bin of output histogram: that should be the
# number of voxels
s = via.GetOutput().GetPointData().GetScalars()
print s.GetTuple1(1)
self.failUnless(s.GetTuple1(1) == 26728)
via.SetInput(None)
del via
# ----------------------------------------------------------------------------
class TestITKBasic(GraphEditorVolumeTestBase):
def test_vtktoitk_types(self):
"""Do quick test on vtk -> itk -> vtk + type conversion.
"""
# create VTKtoITK, set it to cast to float (we're going to
# test signed short and unsigned long as well)
(v2imod, v2iglyph) = self._ge.create_module_and_glyph(
200, 10, 'modules.insight.VTKtoITK')
self.failUnless(v2imod, v2iglyph)
(i2vmod, i2vglyph) = self._ge.create_module_and_glyph(
200, 130, 'modules.insight.ITKtoVTK')
self.failUnless(i2vmod and i2vglyph)
ret = self._ge._connect(self.dtglyph, 0, v2iglyph, 0)
self.failUnless(ret)
ret = self._ge._connect(v2iglyph, 0, i2vglyph, 0)
self.failUnless(ret)
# redraw the canvas
self._ge.canvas.redraw()
for t in (('float', 'float'), ('signed short', 'short'),
('unsigned long', 'unsigned long')):
c = v2imod.get_config()
c.autotype = False
c.type = t[0]
v2imod.set_config(c) # this will modify the module
# execute the network
self._ge._handler_execute_network(None)
# each time make sure that the effective data type at the
# output of the ITKtoVTK is what we expect.
id = i2vmod.get_output(0)
self.failUnless(id.GetScalarTypeAsString() == t[1])
# this is quite nasty: if the next loop is entered too
# quickly and the VTKtoITK module is modified before the
# ticker has reached the next decisecond, the network
# thinks that it has not been modified, and so it won't be
# executed.
time.sleep(0.01)
def test_confidence_seed_connect(self):
"""Test confidenceSeedConnect and VTK<->ITK interconnect.
"""
# this will be the last big created thingy... from now on we'll
# do DVNs. This simulates the user's actions creating the network
# though.
# create a slice3dVWR
(svmod, svglyph) = self._ge.create_module_and_glyph(
200, 190, 'modules.viewers.slice3dVWR')
self.failUnless(svmod and svglyph)
# connect up the created volume and redraw
ret = self._ge._connect(self.dtglyph, 0, svglyph, 0)
# make sure it can connect
self.failUnless(ret)
# we need to execute before storeCursor can work
self._ge._handler_execute_network(None)
# storeCursor wants a 4-tuple and value - we know what these should be
svmod.selectedPoints._storeCursor((20,20,0,1))
self.failUnless(len(svmod.selectedPoints._pointsList) == 1)
# connect up the insight bits
(v2imod, v2iglyph) = self._ge.create_module_and_glyph(
200, 10, 'modules.insight.VTKtoITK')
self.failUnless(v2imod and v2iglyph)
# make sure VTKtoITK will cast to float (because it's getting
# double at the input!)
c = v2imod.get_config()
c.autotype = False
c.type = 'float'
v2imod.set_config(c)
(cscmod, cscglyph) = self._ge.create_module_and_glyph(
200, 70, 'modules.insight.confidenceSeedConnect')
self.failUnless(cscmod and cscglyph)
(i2vmod, i2vglyph) = self._ge.create_module_and_glyph(
200, 130, 'modules.insight.ITKtoVTK')
self.failUnless(i2vmod and i2vglyph)
ret = self._ge._connect(self.dtglyph, 0, v2iglyph, 0)
self.failUnless(ret)
ret = self._ge._connect(v2iglyph, 0, cscglyph, 0)
self.failUnless(ret)
ret = self._ge._connect(cscglyph, 0, i2vglyph, 0)
self.failUnless(ret)
# there's already something on the 0'th input of the slice3dVWR
ret = self._ge._connect(i2vglyph, 0, svglyph, 1)
self.failUnless(ret)
# connect up the selected points
ret = self._ge._connect(svglyph, 0, cscglyph, 1)
self.failUnless(ret)
# redraw the canvas
self._ge.canvas.redraw()
# execute the network
self._ge._handler_execute_network(None)
# now count the number of voxels in the segmented result
import vtk
via = vtk.vtkImageAccumulate()
via.SetInput(i2vmod.get_output(0))
via.Update()
# get second bin of output histogram: that should be the
# number of voxels
s = via.GetOutput().GetPointData().GetScalars()
print s.GetTuple1(1)
self.failUnless(s.GetTuple1(1) == 26728)
via.SetInput(None)
del via
def create_geb_test(name, devide_app):
"""Utility function to create GraphEditorBasic test and stuff all the
data in there that we'd like.
"""
t = GraphEditorBasic(name)
t._devide_app = devide_app
return t
def get_some_suite(devide_testing):
devide_app = devide_testing.devide_app
some_suite = unittest.TestSuite()
t = TestITKBasic('test_confidence_seed_connect')
t._devide_app = devide_app
t._devide_testing = devide_testing # need for networks path
some_suite.addTest(t)
return some_suite
def get_suite(devide_testing):
devide_app = devide_testing.devide_app
mm = devide_app.get_module_manager()
graph_editor_suite = unittest.TestSuite()
# all of these tests require the wx_kit
if 'wx_kit' not in mm.module_kits.module_kit_list:
return graph_editor_suite
graph_editor_suite.addTest(create_geb_test('test_startup', devide_app))
graph_editor_suite.addTest(
create_geb_test('test_module_creation_deletion', devide_app))
graph_editor_suite.addTest(
create_geb_test('test_module_help', devide_app))
graph_editor_suite.addTest(
create_geb_test('test_module_search', devide_app))
graph_editor_suite.addTest(
create_geb_test('test_simple_network', devide_app))
graph_editor_suite.addTest(
create_geb_test('test_config_vtk_obj', devide_app))
t = TestModulesMisc('test_create_destroy')
t._devide_app = devide_app
graph_editor_suite.addTest(t)
t = TestModulesMisc('test_create_view_destroy')
t._devide_app = devide_app
graph_editor_suite.addTest(t)
t = TestVTKBasic('test_seedconnect')
t._devide_app = devide_app
t._devide_testing = devide_testing # need for networks path
graph_editor_suite.addTest(t)
# module_kit_list is up to date with the actual module_kits that
# were imported
if 'itk_kit' in mm.module_kits.module_kit_list:
t = TestITKBasic('test_confidence_seed_connect')
t._devide_app = devide_app
graph_editor_suite.addTest(t)
t = TestITKBasic('test_vtktoitk_types')
t._devide_app = devide_app
graph_editor_suite.addTest(t)
return graph_editor_suite
| Python |
# testing.__init__.py copyright 2006 by Charl P. Botha http://cpbotha.net/
# $Id$
# this drives the devide unit testing. neat huh?
import os
import time
import unittest
from testing import misc
from testing import basic_vtk
from testing import basic_wx
from testing import graph_editor
from testing import numpy_tests
from testing import matplotlib_tests
module_list = [misc, basic_vtk, basic_wx, graph_editor,
numpy_tests, matplotlib_tests]
for m in module_list:
reload(m)
# ----------------------------------------------------------------------------
class DeVIDETesting:
def __init__(self, devide_app):
self.devide_app = devide_app
suite_list = [misc.get_suite(self),
basic_vtk.get_suite(self),
basic_wx.get_suite(self),
graph_editor.get_suite(self),
numpy_tests.get_suite(self),
matplotlib_tests.get_suite(self)
]
self.main_suite = unittest.TestSuite(tuple(suite_list))
def runAllTests(self):
runner = unittest.TextTestRunner(verbosity=2)
runner.run(self.main_suite)
print "Complete suite consists of 19 (multi-part) tests on "
print "lin32, lin64, win32, win64."
def runSomeTest(self):
#some_suite = misc.get_suite(self)
#some_suite = basic_vtk.get_suite(self)
#some_suite = basic_wx.get_suite(self)
some_suite = graph_editor.get_some_suite(self)
#some_suite = numpy_tests.get_suite(self)
#some_suite = matplotlib_tests.get_suite(self)
runner = unittest.TextTestRunner()
runner.run(some_suite)
def get_images_dir(self):
"""Return full path of directory with test images.
"""
return os.path.join(os.path.dirname(__file__), 'images')
def get_networks_dir(self):
"""Return full path of directory with test networks.
"""
return os.path.join(os.path.dirname(__file__), 'networks')
def compare_png_images(self, image1_filename, image2_filename,
threshold=16, allow_shift=False):
"""Compare two PNG images on disc. No two pixels may differ with more
than the default threshold.
"""
import vtk
r1 = vtk.vtkPNGReader()
r1.SetFileName(image1_filename)
r1.Update()
r2 = vtk.vtkPNGReader()
r2.SetFileName(image2_filename)
r2.Update()
# there's a bug in VTK 5.0.1 where input images of unequal size
# (depending on which input is larger) will cause a segfault
# see http://www.vtk.org/Bug/bug.php?op=show&bugid=3586
# se we check for that situation and bail if it's the case
if r1.GetOutput().GetDimensions() != r2.GetOutput().GetDimensions():
em = 'Input images %s and %s are not of equal size.' % \
(image1_filename, image2_filename)
raise RuntimeError, em
# sometimes PNG files have an ALPHA component we have to chuck away
# do this for both images
ec1 = vtk.vtkImageExtractComponents()
ec1.SetComponents(0,1,2)
ec1.SetInput(r1.GetOutput())
ec2 = vtk.vtkImageExtractComponents()
ec2.SetComponents(0,1,2)
ec2.SetInput(r2.GetOutput())
idiff = vtk.vtkImageDifference()
idiff.SetThreshold(threshold)
if allow_shift:
idiff.AllowShiftOn()
else:
idiff.AllowShiftOff()
idiff.SetImage(ec1.GetOutput())
idiff.SetInputConnection(ec2.GetOutputPort())
idiff.Update()
return idiff.GetThresholdedError()
| Python |
import sys
import unittest
class NumPyTest(unittest.TestCase):
def test_import_mixing(self):
"""Test for bug where packaged numpy and installed numpy would
conflict, causing errors.
"""
import numpy
try:
na = numpy.array([0,0,0])
print na
except Exception, e:
self.fail('numpy.array() cast raises exception: %s' %
(str(e),))
else:
pass
def get_suite(devide_testing):
devide_app = devide_testing.devide_app
# both of these tests require wx
mm = devide_app.get_module_manager()
numpy_suite = unittest.TestSuite()
if 'numpy_kit' in mm.module_kits.module_kit_list:
t = NumPyTest('test_import_mixing')
t._devide_app = devide_app
t._devide_testing = devide_testing
numpy_suite.addTest(t)
return numpy_suite
| Python |
"""Module to test basic DeVIDE functionality.
"""
import unittest
class BasicMiscTest(unittest.TestCase):
def test_sqlite3(self):
"""Test if sqlite3 is available.
"""
import sqlite3
v = sqlite3.version
conn = sqlite3.connect(':memory:')
cur = conn.cursor()
cur.execute('create table stuff (some text)')
cur.execute('insert into stuff values (?)', (v,))
cur.close()
cur = conn.cursor()
cur.execute('select some from stuff')
# cur.fetchall() returns a list of tuples: we get the first
# item in the list, then the first element in that tuple, this
# should be the version we inserted.
self.failUnless(cur.fetchall()[0][0] == v)
def get_suite(devide_testing):
devide_app = devide_testing.devide_app
mm = devide_app.get_module_manager()
misc_suite = unittest.TestSuite()
t = BasicMiscTest('test_sqlite3')
misc_suite.addTest(t)
return misc_suite
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
import wx # todo: this should go away...
import string
import sys
import traceback
# todo: remove all VTK dependencies from this file!!
def clampVariable(v, min, max):
"""Make sure variable is on the range [min,max]. Return clamped variable.
"""
if v < min:
v = min
elif v > max:
v = max
return v
def exceptionToMsgs():
# create nice formatted string with tracebacks and all
ei = sys.exc_info()
#dmsg = \
# string.join(traceback.format_exception(ei[0],
# ei[1],
# ei[2]))
dmsgs = traceback.format_exception(ei[0], ei[1], ei[2])
return dmsgs
def logError_DEPRECATED(msg):
"""DEPRECATED. Rather use devide_app.log_error().
"""
# create nice formatted string with tracebacks and all
ei = sys.exc_info()
#dmsg = \
# string.join(traceback.format_exception(ei[0],
# ei[1],
# ei[2]))
dmsgs = traceback.format_exception(ei[0], ei[1], ei[2])
# we can't disable the timestamp yet
# wxLog_SetTimestamp()
# set the detail message
for dmsg in dmsgs:
wx.LogError(dmsg)
# then the most recent
wx.LogError(msg)
print msg
# and flush... the last message will be the actual error
# message, what we did before will add to it to become the
# detail message
wx.Log_FlushActive()
def logWarning_DEPRECATED(msg):
"""DEPRECATED. Rather use devide_app.logWarning().
"""
# create nice formatted string with tracebacks and all
ei = sys.exc_info()
#dmsg = \
# string.join(traceback.format_exception(ei[0],
# ei[1],
# ei[2]))
dmsgs = traceback.format_exception(ei[0], ei[1], ei[2])
# we can't disable the timestamp yet
# wxLog_SetTimestamp()
# set the detail message
for dmsg in dmsgs:
wx.LogWarning(dmsg)
# then the most recent
wx.LogWarning(msg)
# and flush... the last message will be the actual error
# message, what we did before will add to it to become the
# detail message
wx.Log_FlushActive()
def setGridCellYesNo(grid, row, col, yes=True):
if yes:
colour = wx.Colour(0,255,0)
text = '1'
else:
colour = wx.Colour(255,0,0)
text = '0'
grid.SetCellValue(row, col, text)
grid.SetCellBackgroundColour(row, col, colour)
def textToFloat(text, defaultFloat):
"""Converts text to a float by using an eval and returns the float.
If something goes wrong, returns defaultFloat.
"""
try:
returnFloat = float(text)
except Exception:
returnFloat = defaultFloat
return returnFloat
def textToInt(text, defaultInt):
"""Converts text to an integer by using an eval and returns the integer.
If something goes wrong, returns default Int.
"""
try:
returnInt = int(text)
except Exception:
returnInt = defaultInt
return returnInt
def textToTuple(text, defaultTuple):
"""This will convert the text representation of a tuple into a real
tuple. No checking for type or number of elements is done. See
textToTypeTuple for that.
"""
# first make sure that the text starts and ends with brackets
text = text.strip()
if text[0] != '(':
text = '(%s' % (text,)
if text[-1] != ')':
text = '%s)' % (text,)
try:
returnTuple = eval('tuple(%s)' % (text,))
except Exception:
returnTuple = defaultTuple
return returnTuple
def textToTypeTuple(text, defaultTuple, numberOfElements, aType):
"""This will convert the text representation of a tuple into a real
tuple with numberOfElements elements, all of type aType. If the required
number of elements isn't available, or they can't all be casted to the
correct type, the defaultTuple will be returned.
"""
aTuple = textToTuple(text, defaultTuple)
if len(aTuple) != numberOfElements:
returnTuple = defaultTuple
else:
try:
returnTuple = tuple([aType(e) for e in aTuple])
except ValueError:
returnTuple = defaultTuple
return returnTuple
| Python |
#! /usr/bin/env python
'''Helper script for bundling up a game in a ZIP file.
This script will bundle all game files into a ZIP file which is named as
per the argument given on the command-line. The ZIP file will unpack into a
directory of the same name.
The script ignores:
- CVS or SVN subdirectories
- any dotfiles (files starting with ".")
- .pyc and .pyo files
'''
import sys
import os
import zipfile
if len(sys.argv) != 2:
print '''Usage: python %s <release filename-version>
eg. python %s my_cool_game-1.0'''%(sys.argv[0], sys.argv[0])
sys.exit()
base = sys.argv[1]
zipname = base + '.zip'
try:
package = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)
except RuntimeError:
package = zipfile.ZipFile(zipname, 'w')
# core files
for name in 'README.txt LICENSE.txt run_game.py config.json level_editor.py'.split():
package.write(name, os.path.join(base, name))
package.write('run_game.py', os.path.join(base, 'run_game.pyw'))
# utility for adding subdirectories
def add_files(generator):
for dirpath, dirnames, filenames in generator:
for name in list(dirnames):
if name == 'CVS' or name.startswith('.'):
dirnames.remove(name)
if name in ('SVGs','docs','design'):
dirnames.remove(name)
for name in filenames:
if name.startswith('.'): continue
suffix = os.path.splitext(name)[1]
if suffix in ('.pyc', '.pyo'): continue
if name[0] == '.': continue
if '.svg' in name: continue
if 'Base' in name: continue
if '~' in name: continue
if '.tmp' in name: continue
filename = os.path.join(dirpath, name)
package.write(filename, os.path.join(base, filename))
# add the lib and data directories
add_files(os.walk('lib'))
add_files(os.walk('data'))
# calculate MD5
import hashlib
d = hashlib.md5()
d.update(file(zipname, 'rb').read())
print 'Created', zipname
print 'MD5 hash:', d.hexdigest()
| Python |
#! /usr/bin/env python
'''Helper script for bundling up a game in a ZIP file.
This script will bundle all game files into a ZIP file which is named as
per the argument given on the command-line. The ZIP file will unpack into a
directory of the same name.
The script ignores:
- CVS or SVN subdirectories
- any dotfiles (files starting with ".")
- .pyc and .pyo files
'''
import sys
import os
import zipfile
if len(sys.argv) != 2:
print '''Usage: python %s <release filename-version>
eg. python %s my_cool_game-1.0'''%(sys.argv[0], sys.argv[0])
sys.exit()
base = sys.argv[1]
zipname = base + '.zip'
try:
package = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)
except RuntimeError:
package = zipfile.ZipFile(zipname, 'w')
# core files
for name in 'README.txt LICENSE.txt run_game.py config.json level_editor.py'.split():
package.write(name, os.path.join(base, name))
package.write('run_game.py', os.path.join(base, 'run_game.pyw'))
# utility for adding subdirectories
def add_files(generator):
for dirpath, dirnames, filenames in generator:
for name in list(dirnames):
if name == 'CVS' or name.startswith('.'):
dirnames.remove(name)
if name in ('SVGs','docs','design'):
dirnames.remove(name)
for name in filenames:
if name.startswith('.'): continue
suffix = os.path.splitext(name)[1]
if suffix in ('.pyc', '.pyo'): continue
if name[0] == '.': continue
if '.svg' in name: continue
if 'Base' in name: continue
if '~' in name: continue
if '.tmp' in name: continue
filename = os.path.join(dirpath, name)
package.write(filename, os.path.join(base, filename))
# add the lib and data directories
add_files(os.walk('lib'))
add_files(os.walk('data'))
# calculate MD5
import hashlib
d = hashlib.md5()
d.update(file(zipname, 'rb').read())
print 'Created', zipname
print 'MD5 hash:', d.hexdigest()
| Python |
import pygame
from pygame.locals import *
pygame.init()
import lib
import os
import json
GROUPS = ('Solid','Background','Foreground')
TILE_NAMES = {'Solid':('Center','Left-Side','Right-Side','Top',
'Bottom','Left-Top-Outside-Corner',
'Right-Top-Outside-Corner',
'Left-Bottom-Outside-Corner',
'Right-Bottom-Outside-Corner',
'Left-Top-Inside-Corner',
'Right-Top-Inside-Corner',
'Left-Bottom-Inside-Corner',
'Right-Bottom-Inside-Corner')}
class LevelEditor:
def __init__(self):
self.screen = pygame.display.set_mode([720,520],0,32)
pygame.display.set_caption('Foxen - Level Editor')
self.screen_pos = [0,35]
self.level_name = ''
self.current_group = 0
self.current_tile_name = 0
self.placement_mode = 'Place Terrain'
self.level_data = {}
self.images = {}
self.load_level('test')
if len(self.level_data.keys()) == 0:
self.new_level()
self.status_message = 'Started; Editing Level ' + str(self.level_name)
self.timer = pygame.time.Clock()
def add_empty_cell(self):
new_cell = {'Terrain':{'Solid': [],
'Background':[],
'Foreground':[]},
'Baddies':[],
'Widgets':[]}
for column in range(25):
new_cell['Terrain']['Solid'].append({'Name':'Top','Position':[column,46]})
for row in range(47,50):
new_cell['Terrain']['Solid'].append({'Name':'Center','Position':[column,row]})
self.level_data['Cells'].append(new_cell)
def refresh_images(self):
self.images = {'Player':lib.data.load_player_images('Trixie'),
'Baddies':[],'Items':[],
'Terrain':lib.data.load_terrain_images(self.level_data['Metadata']['Tileset'])}
def new_level(self,name=None):
if str(self.level_name) != '':
self.save_level()
if name != None:
self.level_name = name
elif str(self.level_name) == '':
self.level_name = 'test'
self.level_data = {'Metadata':{'Name':str(self.level_name),'Length':10,
'Tileset':'grass','Player Start':[0,[0,0]]},
'Cells':[]}
self.refresh_images()
self.screen_pos = [0,36]
for cell in range(10):
self.add_empty_cell()
self.status_message = 'New Level Named ' + str(self.level_name)
def load_level(self,name):
self.save_level()
self.level_name = name
self.reload_level()
if len(self.level_data.keys()) == 0:
self.new_level(name)
self.status_message = ('Level ' + str(name) + ' does not exist! Creating new level...')
def reload_level(self):
try:
file_path = os.path.relpath(os.path.join(__file__,'..','data'))
file_path = os.path.join(file_path,'level',(str(self.level_name)+'.lvl'))
lvl_file = open(file_path,'r')
self.level_data = json.load(lvl_file)
lvl_file.close()
self.refresh_images()
self.screen_pos = [0,36]
self.status_message = 'Reloaded Level from File'
except Exception:
self.level_data = {}
self.status_message = 'Error Reloading Level'
def save_level(self):
try:
file_path = os.path.relpath(os.path.join(__file__,'..','data'))
file_path = os.path.join(file_path,'level',(str(self.level_name)+'.lvl'))
lvl_file = open(file_path,'w')
json.dump(self.level_data,lvl_file,indent=2)
lvl_file.close()
self.status_message = 'Level ' + str(self.level_name) + ' Saved'
except IOError:
self.status_message = 'Error Saving Level'
def go(self):
while True:
self.timer.tick(10)
self.step()
def get_terrain_at(self,group,cell,coords):
if group in self.level_data['Cells'][cell]['Terrain'].keys():
for block in self.level_data['Cells'][cell]['Terrain'][group]:
bl_coords = block['Position']
if bl_coords[0] == coords[0] and bl_coords[1] == coords[1]:
return block
return None
def remove_terrain_at(self,group,cell,coords):
current_tile = self.get_terrain_at(group,cell,coords)
if current_tile:
self.level_data['Cells'][cell]['Terrain'][group].remove(current_tile)
def set_terrain_at(self,group,name,cell,coords):
self.remove_terrain_at(group,cell,coords)
new_tile = {'Position':tuple(coords),'Name':name}
self.level_data['Cells'][cell]['Terrain'][group].append(new_tile)
def group_name(self):
return GROUPS[self.current_group]
def tile_name(self):
return TILE_NAMES[self.group_name()][self.current_tile_name]
def step(self):
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
exit()
elif event.key == K_F2:
self.current_group -= 1
if self.current_group == -1:
self.current_group = (len(GROUPS) - 1)
###--- GROUP CHANGES ---###
if event.key == K_F2:
self.current_group -= 1
if self.current_group == -1:
self.current_group = (len(GROUPS) - 1)
elif event.key == K_F1:
self.current_group -= 2
if self.current_group == -1:
self.current_group = (len(GROUPS) - 1)
if self.current_group == -2:
self.current_group = (len(GROUPS) - 2)
elif event.key == K_F3:
self.current_group += 1
if self.current_group == len(GROUPS):
self.current_group = 0
elif event.key == K_F4:
self.current_group += 2
if self.current_group == len(GROUPS):
self.current_group = 0
if self.current_group == (len(GROUPS) + 1):
self.current_group = 1
if event.key in (K_F1,K_F2,K_F3,K_F4):
self.status_message = "Changed tile group to " + self.group_name()
###--- TILE NAME CHANGES ---###
if event.key == K_F7:
self.current_tile_name -= 1
if self.current_tile_name == -1:
self.current_tile_name = len(TILE_NAMES[self.group_name()])-1
elif event.key == K_F6:
self.current_tile_name -= 2
if self.current_tile_name == -1:
self.current_tile_name = len(TILE_NAMES[self.group_name()])-1
if self.current_tile_name == -2:
self.current_tile_name = len(TILE_NAMES[self.group_name()])-2
elif event.key == K_F8:
self.current_tile_name += 1
if self.current_tile_name == len(TILE_NAMES[self.group_name()]):
self.current_tile_name = 0
elif event.key == K_F9:
self.current_tile_name += 2
if self.current_tile_name == len(TILE_NAMES[self.group_name()]):
self.current_tile_name = 0
if self.current_tile_name == len(TILE_NAMES[self.group_name()]) + 1:
self.current_tile_name = 1
if event.key in (K_F6,K_F7,K_F8,K_F9):
self.status_message = 'Now Placing Tile: ' + self.tile_name()
###--- PLACEMENT MODES ---###
if event.key == K_1:
self.status_message = 'Now Placing Terrain'
self.placement_mode = 'Place Terrain'
elif event.key == K_2:
self.placement_mode = 'Place Baddie'
elif event.key == K_3:
self.placement_mode = 'Place Item'
elif event.key == K_4:
self.placement_mode = 'Place Prop'
elif event.key == K_5:
self.status_message = 'Now Placing Player Start Point'
self.placement_mode = 'Place Player Start'
###--- FILE COMMANDS ---###
if event.key == K_s and event.mod & KMOD_LCTRL:
self.save_level()
elif event.key == K_r and event.mod & KMOD_LCTRL:
self.reload_level()
elif event.key == K_n and event.mod * KMOD_LCTRL:
self.new_level()
###--- SCROLLING ---###
if event.key == K_LEFT:
self.screen_pos[0] -= 1
elif event.key == K_RIGHT:
self.screen_pos[0] += 1
elif event.key == K_UP:
self.screen_pos[1] -= 1
elif event.key == K_DOWN:
self.screen_pos[1] += 1
keys_pressed = pygame.key.get_pressed()
if keys_pressed[K_LEFT]:
self.screen_pos[0] -= 1
if keys_pressed[K_RIGHT]:
self.screen_pos[0] += 1
if keys_pressed[K_UP]:
self.screen_pos[1] -= 1
if keys_pressed[K_DOWN]:
self.screen_pos[1] += 1
self.screen.fill((0,160,200))
base_cell = (self.screen_pos[0] + 9) // 25
camera_pos = list(self.screen_pos)
camera_pos[0] -= (base_cell*25)
self.screen.fill((0,140,210))
player_image = self.images['Player']['Normal']['Idle']
blit_rect = player_image.get_rect()
blit_rect.centerx = self.level_data['Metadata']['Player Start'][1][0]
blit_rect.bottom = self.level_data['Metadata']['Player Start'][1][1]
blit_rect.centerx += self.level_data['Metadata']['Player Start'][0] * 1000
print blit_rect.topleft
blit_rect.left -= self.screen_pos[0] * 40
blit_rect.top -= self.screen_pos[1] * 40
self.screen.blit(player_image,blit_rect)
for cell_number in range(base_cell-3,base_cell+4):
if cell_number < 0 or cell_number >= len(self.level_data['Cells']):
continue
for block in self.level_data['Cells'][cell_number]['Terrain']['Solid']:
image = self.images['Terrain']['Solid'][block['Name']][0]
blit_coords = list(block['Position'])
blit_coords[0] -= camera_pos[0]
blit_coords[1] -= camera_pos[1]
blit_coords[0] -= ((base_cell - cell_number)*25)
blit_coords[0] *= 40
blit_coords[1] *= 40
self.screen.blit(image,blit_coords)
mouse_btns = pygame.mouse.get_pressed()
mouse_pos = list(pygame.mouse.get_pos())
mouse_pos[0] += self.screen_pos[0]
mouse_pos[1] += self.screen_pos[1]
if self.placement_mode == 'Place Terrain':
place_pos = [0,0]
for column in range(18):
for row in range(13):
if pygame.Rect(column*40,row*40,40,40).collidepoint(pygame.mouse.get_pos()):
place_pos = [column,row]
preview_tile = self.images['Terrain'][self.group_name()][self.tile_name()][0]
preview_img = pygame.Surface(preview_tile.get_size(),0,32)
preview_img.fill((0,220,0))
preview_img.blit(preview_tile,(0,0))
preview_img.set_alpha(200)
self.screen.blit(preview_img,[place_pos[0]*40,place_pos[1]*40])
place_cell = (self.screen_pos[0] + 9) // 25
place_pos[0] += (self.screen_pos[0] - (place_cell * 25))
place_pos[1] += self.screen_pos[1]
if mouse_btns[0]:
self.set_terrain_at(self.group_name(),self.tile_name(),place_cell,place_pos)
elif mouse_btns[2]:
self.remove_terrain_at(self.group_name(),place_cell,place_pos)
# END if self.placement_mode == 'Place Terrain'
elif self.placement_mode == 'Place Player Start':
preview_sprite = self.images['Player']['Normal']['Idle']
preview_rect = preview_sprite.get_rect()
preview_rect.centerx = pygame.mouse.get_pos()[0]
preview_rect.bottom = pygame.mouse.get_pos()[1]
self.screen.blit(preview_sprite,preview_rect.topleft)
if mouse_btns[0]:
place_pos = list(pygame.mouse.get_pos())
place_cell = (self.screen_pos[0] + 9) // 25
place_pos[0] += (self.screen_pos[0] - (place_cell * 25)) * 40
place_pos[1] += self.screen_pos[1] * 40
place_cell = (self.screen_pos[0] + 9) // 25
print place_cell
self.level_data['Metadata']['Player Start'] = [place_cell,place_pos]
message_font = pygame.font.SysFont('FreeSans,Arial',20,False,False)
message_img = message_font.render(self.status_message,True,(255,255,255,180))
self.screen.blit(message_img,(20,20))
pygame.display.update()
if __name__.lower() == '__main__':
LevelEditor().go()
| Python |
import pygame
def draw_game_screen(screen,world):
screen_area = screen.get_rect()
screen_area.center = world.player.rect.center
screen_area.clamp_ip(world.area)
screen.fill((0,140,210))
image,blit_rect = world.player.get_blit_info()
blit_rect.left -= screen_area.left
blit_rect.top -= screen_area.top
screen.blit(image,blit_rect.topleft)
for block in world.terrain['Solid']:
image,blit_rect = block.get_blit_info()
if blit_rect.colliderect(screen_area):
blit_rect.left -= screen_area.left
blit_rect.top -= screen_area.top
screen.blit(image,blit_rect.topleft)
| Python |
import pygame
class WorldCell:
def __init__(self,index,player,terrain,baddies,widgets):
pass
class GameWorld:
def __init__(self,player,factory,cells):
self.cells = cells
self.factory = factory
self.player = player
self.current_cell = 0
| Python |
import pygame
import entities
from config import CONFIG
from constants import UP,DOWN,LEFT,RIGHT
class Player(entities.Agent):
def __init__(self,pos,size,image_set,sound_set):
entities.Agent.__init__(self,pos,size,2,
CONFIG['Player Stats']['Speed'],
image_set,sound_set)
self.normal_speed = CONFIG['Player Stats']['Speed']
self.kit_speed = self.normal_speed // 2
self.jump_vel = list(CONFIG['Player Stats']['Jump'])
v0 = 0
v = 0
h = 0
while h < self.jump_vel[1]:
v0 += 1
v = v0
h = 0
while v > 0:
h += v
v -= 1
self.jump_vel[1] = v0
def get_image(self):
image = None
form = 'Normal'
if self.health == 1:
form = 'Kit'
if not self.collisions[DOWN]:
if self.velocity[1] <= 0:
image = self.image_set[form]['Jump']
else:
image = self.image_set[form]['Fall']
elif self.status in ('Walk','Run'):
image = self.image_set[form][self.status][self.frame]
else:
image = self.image_set[form][self.status]
if self.left:
image = pygame.transform.flip(image,True,False)
return image
def update_velocity(self):
if self.collisions[DOWN]:
if self.status == 'Walk':
if self.left:
if self.velocity[0] > self.speed // -2:
self.velocity[0] -= 1
elif self.velocity[0] < self.speed // -2:
self.velocity[0] += 1
else:
if self.velocity[0] < self.speed // 2:
self.velocity[0] += 1
elif self.velocity[0] > self.speed // 2:
self.velocity[0] -= 1
# END if self.status == 'Walk'
elif self.status == 'Run':
if self.left:
if self.velocity[0] > -(self.speed):
self.velocity[0] -= 4
elif self.velocity[0] < -(self.speed):
self.velocity[0] += 1
else:
if self.velocity[0] < self.speed:
self.velocity[0] += 4
elif self.velocity[0] > self.speed:
self.velocity[0] -= 1
# END elif self.status == 'Run'
else:
if self.velocity[0] < 0:
self.velocity[0] += 1
elif self.velocity[0] > 0:
self.velocity[0] -= 1
# END else (Meaning self.status != 'Walk' and self.status != 'Run')
# END if self.collisions[DOWN]
else:
if self.status in ('Walk','Run'):
if self.left:
if self.velocity[0] > self.speed // -3:
self.velocity[0] -= 1
else:
if self.velocity[0] < self.speed // 3:
self.velocity[0] += 1
entities.Entity.update_velocity(self)
def update(self,controls,solids,baddies,items,widgets):
if controls['Left'] or controls['Right']:
self.left = controls['Left']
if controls['Run']:
self.status = 'Run'
else:
self.status = 'Walk'
else:
self.status = 'Idle'
if self.health == 1:
self.speed = self.kit_speed
if self.rect.width > 30:
bottom = self.rect.bottom
centerx = self.rect.centerx
self.rect = pygame.Rect(0,0,30,30)
self.rect.bottom = bottom
self.rect.centerx = centerx
else:
self.speed = self.normal_speed
if self.rect.width < 70:
bottom = self.rect.bottom
centerx = self.rect.centerx
self.rect = pygame.Rect(0,0,70,70)
self.rect.bottom = bottom
self.rect.centerx = centerx
if controls['Jump']:
if self.collisions[DOWN]:
self.velocity[1] = -(self.jump_vel[1])
if self.health == 1:
self.jump_vel[0] /= 2
if self.left:
self.velocity[0] -= self.jump_vel[0]
else:
self.velocity[0] += self.jump_vel[0]
if self.health == 1:
self.jump_vel[0] *= 2
if self.status in ('Walk','Run'):
self.frame_timer += 1
if ((self.status == 'Walk' and self.frame_timer >= 3) or
(self.status == 'Run' and self.frame_timer >= 1)):
self.frame += 1
self.frame_timer = 0
if self.frame >= 8:
self.frame = 0
entities.Agent.update(self,solids)
if all(self.collisions):
self.health -= 1
| Python |
import pygame
import player
import baddies
import items
import world
import terrain
import menu
import hud
import music
import data
from constants import *
from config import CONFIG
import random
class GeneralFactory:
def __init__(self):
self.images = {}
self.sounds = {}
self.images['Player'] = data.load_player_images('trixie')
self.images['Terrain'] = data.load_terrain_images('grass')
def make_player(self,pos,name):
del self.images['Player']
self.images['Player'] = data.load_player_images(name)
return player.Player(pos,(10,10),self.images['Player'],{})
def make_terrain_tile(self,pos,category,name):
tile = None
if random.random() < 0.75:
tile = terrain.TerrainTile(pos,self.images['Terrain'][category][name][0])
else:
tile = terrain.TerrainTile(pos,self.images['Terrain'][category][name][random.randint(0,5)])
return tile
def inflate_world_segment(self,data):
random.seed(23)
| Python |
import pygame
import constants
class TerrainTile:
def __init__(self,pos,image):
self.rect = pygame.Rect(pos,(1,1))
self.rect.left *= constants.TILE_SIZE[0]
self.rect.top *= constants.TILE_SIZE[1]
self.rect.width *= constants.TILE_SIZE[0]
self.rect.height *= constants.TILE_SIZE[1]
self.image = image
def get_blit_info(self):
return self.image,pygame.Rect(self.rect)
| Python |
UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3
TILE_SIZE = [40,40]
| Python |
import pygame
import os
import json
DATA_DIR = os.path.relpath(os.path.join(__file__,'..','..','data'))
def load_image(img_path):
img_path = os.path.join(DATA_DIR,'media','images',img_path+'.png')
return pygame.image.load(img_path)
def load_player_images(name):
base_dir = os.path.join('player',name.lower())
images = {}
for form in ('Kit','Normal'):
images[form] = {}
form_imgs = images[form]
work_dir = os.path.join(base_dir,form.lower())
for static_pose in ('Idle','Fall','Jump'):
form_imgs[static_pose] = load_image(os.path.join(work_dir,static_pose+'-0'))
form_imgs['Run'] = []
form_imgs['Walk'] = []
for frame in range(8):
img_name = os.path.join(work_dir,'Foo-'+str(frame))
form_imgs['Run'].append( load_image(img_name.replace('Foo','Run')))
form_imgs['Walk'].append(load_image(img_name.replace('Foo','Walk')))
return images
def load_terrain_tile(tileset,group,name):
base_path = os.path.join('terrain',tileset.lower(),group.lower())
images = []
for variant in 'ABCDEF':
img_path = os.path.join(base_path,(name+'-'+variant))
images.append(load_image(img_path))
return images
def load_terrain_images(tileset):
images = {}
images['Solid'] = {}
centered_pieces = ('Center','Top','Bottom')
side_pieces = ['Side','Top-Inside-Corner','Bottom-Inside-Corner',
'Top-Outside-Corner','Bottom-Outside-Corner']
for name in centered_pieces:
images['Solid'][name] = load_terrain_tile(tileset,'Solid',name)
for name in side_pieces:
base_imgs = load_terrain_tile(tileset,'Solid',name)
images['Solid'][ 'Left-'+name] = base_imgs
images['Solid']['Right-'+name] = [pygame.transform.flip(img,True,False) for img in base_imgs]
return images
def load_level_file(name):
file_path = os.path.join(DATA_DIR,'level',str(name)+'.lvl')
lvl_file = open(file_path,'r')
level_data = json.load(lvl_file)
lvl_file.close()
return level_data
| Python |
import pygame
from pygame.locals import *
pygame.mixer.pre_init(22050,-16,2,2048)
pygame.init()
import factories
import display
from config import CONFIG
class MainLoop:
def __init__(self):
self.screen = pygame.display.set_mode((800,500),HWSURFACE|DOUBLEBUF,32)
pygame.display.set_caption('Foxen - v0.0.0')
self.factory = factories.GeneralFactory()
self.level = self.factory.load_level('test')
self.player = self.level.player
self.controls = {'Left':False,'Right':False,'Run':False,
'Jump':False,'Close':False}
self.status = 'Game'
self.timer = pygame.time.Clock()
def go(self):
while True:
self.timer.tick(30)
self.step()
def step(self):
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
elif event.type == KEYDOWN:
if event.key == K_r:
if self.player.health == 2:
self.player.health = 1
elif self.player.health == 1:
self.player.health = 2
for ctrl_name in self.controls.keys():
ctrl_keys = CONFIG['Controls']['Keyboard']
if ctrl_keys[ctrl_name] == pygame.key.name(event.key):
self.controls[ctrl_name] = True
elif event.type == KEYUP:
for ctrl_name in self.controls.keys():
ctrl_keys = CONFIG['Controls']['Keyboard']
if ctrl_keys[ctrl_name] == pygame.key.name(event.key):
self.controls[ctrl_name] = False
if self.controls['Close']:
pygame.quit()
exit()
if self.status == 'Game':
self.level.update(self.controls)
display.draw_game_screen(self.screen,self.level)
pygame.display.flip()
if __name__.lower() == '__main__':
MainLoop().go()
| Python |
import pygame
from pygame import Rect
from constants import LEFT,RIGHT,UP,DOWN
class Entity:
def __init__(self,pos,size,image_set):
self.rect = Rect((0,0),size)
self.rect.centerx = pos[0]
self.rect.bottom = pos[1]
self.image_set = image_set
self.velocity = [0,0]
self.collisions = [False,False,False,False]
def move_and_collide(self,solids):
self.collisions[0] = False
self.collisions[1] = False
self.collisions[2] = False
self.collisions[3] = False
self.rect.left += self.velocity[0]
for block in solids:
if self.rect.colliderect(block.rect):
my_r = self.rect
bl_r = block.rect
if my_r.centerx > bl_r.centerx and my_r.left < bl_r.right:
my_r.left = bl_r.right
self.collisions[LEFT] = True
if my_r.centerx < bl_r.centerx and my_r.right > bl_r.left:
my_r.right = bl_r.left
self.collisions[RIGHT] = True
self.rect.top += self.velocity[1]
for block in solids:
if self.rect.colliderect(block.rect):
my_r = self.rect
bl_r = block.rect
if my_r.centery > bl_r.centery and my_r.top < bl_r.bottom:
my_r.top = bl_r.bottom
self.collisions[UP] = True
if my_r.centery < bl_r.centery and my_r.bottom > bl_r.top:
my_r.bottom = bl_r.top
self.collisions[DOWN] = True
def update_velocity(self):
if self.velocity[0] < -35:
self.velocity[0] = -35
if self.velocity[0] > 35:
self.velocity[0] = 35
if self.velocity[1] < -35:
self.velocity[1] = -35
if self.velocity[1] > 35:
self.velocity[1] = 35
if self.collisions[RIGHT] or self.collisions[LEFT]:
self.velocity[0] = 0
if self.collisions[DOWN] or self.collisions[UP]:
self.velocity[1] = 0
self.velocity[1] += 1
def get_image(self):
return self.image_set['Only']
def get_blit_info(self):
image = self.get_image()
blit_rect = image.get_rect()
blit_rect.centerx = self.rect.centerx
blit_rect.bottom = self.rect.bottom
return image,blit_rect
class Agent(Entity):
def __init__(self,pos,size,health,speed,image_set,sound_set):
Entity.__init__(self,pos,size,image_set)
self.sound_set = sound_set
self.health = health
self.speed = speed
self.status = 'Idle'
self.frame = 0
self.frame_timer = 0
self.left = False
def update(self,solids):
self.move_and_collide(solids)
self.update_velocity()
| Python |
import json
import os
config_path = os.path.relpath(os.path.join(__file__,'..','..','config.json'))
config_file = open(config_path,'r')
CONFIG = json.load(config_file)
config_file.close()
del config_file
del config_path
| Python |
import lib
def main():
lib.MainLoop().go()
if __name__.lower() == '__main__':
try:
import psyco
psyco.full()
except ImportError:
pass
main()
| Python |
'''
Upload script specifically engineered for the PyWeek challenge.
Handles authentication and gives upload progress feedback.
'''
import sys, os, httplib, cStringIO, socket, time, getopt
class Upload:
def __init__(self, filename):
self.filename = filename
boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
sep_boundary = '\n--' + boundary
end_boundary = sep_boundary + '--'
def mimeEncode(data, sep_boundary=sep_boundary, end_boundary=end_boundary):
'''Take the mapping of data and construct the body of a
multipart/form-data message with it using the indicated boundaries.
'''
ret = cStringIO.StringIO()
for key, value in data.items():
# handle multiple entries for the same name
if type(value) != type([]): value = [value]
for value in value:
ret.write(sep_boundary)
if isinstance(value, Upload):
ret.write('\nContent-Disposition: form-data; name="%s"'%key)
filename = os.path.basename(value.filename)
ret.write('; filename="%s"\n\n'%filename)
value = open(os.path.join(value.filename), "rb").read()
else:
ret.write('\nContent-Disposition: form-data; name="%s"'%key)
ret.write("\n\n")
value = str(value)
ret.write(str(value))
if value and value[-1] == '\r':
ret.write('\n') # write an extra newline
ret.write(end_boundary)
return ret.getvalue()
class Progress:
def __init__(self, info, data):
self.info = info
self.tosend = len(data)
self.total = self.tosend/1024
self.data = cStringIO.StringIO(data)
self.start = self.now = time.time()
self.sent = 0
self.num = 0
self.stepsize = self.total / 100 or 1
self.steptimes = []
self.display()
def __iter__(self): return self
def next(self):
self.num += 1
if self.sent >= self.tosend:
print self.info, 'done', ' '*(75-len(self.info)-6)
sys.stdout.flush()
raise StopIteration
chunk = self.data.read(1024)
self.sent += len(chunk)
#print (self.num, self.stepsize, self.total, self.sent, self.tosend)
if self.num % self.stepsize:
return chunk
self.display()
return chunk
def display(self):
# figure how long we've spent - guess how long to go
now = time.time()
steptime = now - self.now
self.steptimes.insert(0, steptime)
if len(self.steptimes) > 5:
self.steptimes.pop()
steptime = sum(self.steptimes) / len(self.steptimes)
self.now = now
eta = steptime * ((self.total - self.num)/self.stepsize)
# tell it like it is (or might be)
if now - self.start > 3:
M = eta / 60
H = M / 60
M = M % 60
S = eta % 60
if self.total:
s = '%s %2d%% (ETA %02d:%02d:%02d)'%(self.info,
self.num * 100. / self.total, H, M, S)
else:
s = '%s 0%% (ETA %02d:%02d:%02d)'%(self.info, H, M, S)
elif self.total:
s = '%s %2d%%'%(self.info, self.num * 100. / self.total)
else:
s = '%s %d done'%(self.info, self.num)
sys.stdout.write(s + ' '*(75-len(s)) + '\r')
sys.stdout.flush()
class progressHTTPConnection(httplib.HTTPConnection):
def progress_send(self, str):
"""Send `str' to the server."""
if self.sock is None:
self.connect()
p = Progress('Uploading', str)
for chunk in p:
sent = 0
while sent != len(chunk):
try:
sent += self.sock.send(chunk)
except socket.error, v:
if v[0] == 32: # Broken pipe
self.close()
raise
p.display()
class progressHTTP(httplib.HTTP):
_connection_class = progressHTTPConnection
def _setup(self, conn):
httplib.HTTP._setup(self, conn)
self.progress_send = self._conn.progress_send
def http_request(data, server, port, url):
h = progressHTTP(server, port)
data = mimeEncode(data)
h.putrequest('POST', url)
h.putheader('Content-type', 'multipart/form-data; boundary=%s'%boundary)
h.putheader('Content-length', str(len(data)))
h.putheader('Host', server)
h.endheaders()
h.progress_send(data)
errcode, errmsg, headers = h.getreply()
f = h.getfile()
response = f.read().strip()
f.close()
print '%s %s'%(errcode, errmsg)
if response: print response
def usage():
print '''This program is to be used to upload files to the PyWeek system.
You may use it to upload screenshots or code submissions.
REQUIRED ARGUMENTS:
-u username
-p password
-d description of file
-c file to upload
-e entry short name
OPTIONAL ARGUMENTS:
-s file is a screenshot
-f file is FINAL submission
-h override default host name (www.pyweek.org)
-P override default host port (80)
In order to qualify for judging at the end of the challenge, you MUST
upload your source and check the "Final Submission" checkbox.
'''
if __name__ == '__main__':
try:
optlist, args = getopt.getopt(sys.argv[1:], 'e:u:p:sfd:h:P:c:')
except getopt.GetoptError, message:
print message
usage()
sys.exit(1)
host = 'www.pyweek.org'
port = 80
data = dict(version=2)
optional = {}
url = None
for opt, arg in optlist:
if opt == '-u': data['user'] = arg
elif opt == '-p': data['password'] = arg
elif opt == '-s': optional['is_screenshot'] = 'yes'
elif opt == '-f': optional['is_final'] = 'yes'
elif opt == '-d': data['description'] = arg
elif opt == '-c': data['content_file'] = Upload(arg)
elif opt == '-e': url = '/e/%s/oup/'%arg
elif opt == '-h': host = arg
elif opt == '-P': port = int(arg)
if len(data) < 4 or url is None:
print 'Required argument missing'
usage()
sys.exit(1)
data.update(optional)
http_request(data, host, port, url)
| Python |
import games
import time
from move import Move
from globalconst import BLACK, WHITE, KING, MAN, OCCUPIED, BLACK_CHAR, WHITE_CHAR
from globalconst import BLACK_KING, WHITE_KING, FREE, OCCUPIED_CHAR, FREE_CHAR
from globalconst import COLORS, TYPES, TURN, CRAMP, BRV, KEV, KCV, MEV, MCV
from globalconst import INTACTDOUBLECORNER, ENDGAME, OPENING, MIDGAME
from globalconst import create_grid_map, KING_IDX, BLACK_IDX, WHITE_IDX
import copy
class Checkerboard(object):
# (white)
# 45 46 47 48
# 39 40 41 42
# 34 35 36 37
# 28 29 30 31
# 23 24 25 26
# 17 18 19 20
# 12 13 14 15
# 6 7 8 9
# (black)
valid_squares = [6,7,8,9,12,13,14,15,17,18,19,20,23,24,25,26,
28,29,30,31,34,35,36,37,39,40,41,42,45,46,
47,48]
# values of pieces (KING, MAN, BLACK, WHITE, FREE)
value = [0,0,0,0,0,1,256,0,0,16,4096,0,0,0,0,0,0]
edge = [6,7,8,9,15,17,26,28,37,39,45,46,47,48]
center = [18,19,24,25,29,30,35,36]
# values used to calculate tempo -- one for each square on board (0, 48)
row = [0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,2,2,2,2,0,0,3,3,3,3,0,
4,4,4,4,0,0,5,5,5,5,0,6,6,6,6,0,0,7,7,7,7]
safeedge = [9,15,39,45]
rank = {0:0, 1:-1, 2:1, 3:0, 4:1, 5:1, 6:2, 7:1, 8:1, 9:0,
10:7, 11:4, 12:2, 13:2, 14:9, 15:8}
def __init__(self):
self.squares = [OCCUPIED for i in range(56)]
s = self.squares
for i in range(0, 4):
s[6+i] = s[12+i] = s[17+i] = BLACK | MAN
s[34+i] = s[39+i] = s[45+i] = WHITE | MAN
s[23+i] = s[28+i] = FREE
self.to_move = BLACK
self.charlookup = {BLACK | MAN: BLACK_CHAR, WHITE | MAN: WHITE_CHAR,
BLACK | KING: BLACK_KING, WHITE | KING: WHITE_KING,
OCCUPIED: OCCUPIED_CHAR, FREE: FREE_CHAR}
self.observers = []
self.white_pieces = []
self.black_pieces = []
self.undo_list = []
self.redo_list = []
self.white_total = 12
self.black_total = 12
self.gridmap = create_grid_map()
self.ok_to_move = True
def __repr__(self):
bc = self.count(BLACK)
wc = self.count(WHITE)
sq = self.squares
lookup = self.lookup
s = "[%s=%2d %s=%2d (%+d)]\n" % (BLACK_CHAR, bc,
WHITE_CHAR, wc,
bc - wc)
s += "8 %s %s %s %s\n" % (lookup(sq[45]), lookup(sq[46]),
lookup(sq[47]), lookup(sq[48]))
s += "7 %s %s %s %s\n" % (lookup(sq[39]), lookup(sq[40]),
lookup(sq[41]), lookup(sq[42]))
s += "6 %s %s %s %s\n" % (lookup(sq[34]), lookup(sq[35]),
lookup(sq[36]), lookup(sq[37]))
s += "5 %s %s %s %s\n" % (lookup(sq[28]), lookup(sq[29]),
lookup(sq[30]), lookup(sq[31]))
s += "4 %s %s %s %s\n" % (lookup(sq[23]), lookup(sq[24]),
lookup(sq[25]), lookup(sq[26]))
s += "3 %s %s %s %s\n" % (lookup(sq[17]), lookup(sq[18]),
lookup(sq[19]), lookup(sq[20]))
s += "2 %s %s %s %s\n" % (lookup(sq[12]), lookup(sq[13]),
lookup(sq[14]), lookup(sq[15]))
s += "1 %s %s %s %s\n" % (lookup(sq[6]), lookup(sq[7]),
lookup(sq[8]), lookup(sq[9]))
s += " a b c d e f g h"
return s
def _get_enemy(self):
if self.to_move == BLACK:
return WHITE
return BLACK
enemy = property(_get_enemy,
doc="The color for the player that doesn't have the current turn")
def attach(self, observer):
if observer not in self.observers:
self.observers.append(observer)
def detach(self, observer):
if observer in self.observers:
self.observers.remove(observer)
def clear(self):
s = self.squares
for i in range(0, 4):
s[6+i] = s[12+i] = s[17+i] = FREE
s[23+i] = s[28+i] = FREE
s[34+i] = s[39+i] = s[45+i] = FREE
def lookup(self, square):
return self.charlookup[square & TYPES]
def count(self, color):
return self.white_total if color == WHITE else self.black_total
def get_pieces(self, color):
return self.black_pieces if color == BLACK else self.white_pieces
def has_opposition(self, color):
sq = self.squares
cols = range(6,10) if self.to_move == BLACK else range(12,16)
pieces_in_system = 0
for i in cols:
for j in range(4):
if sq[i+11*j] != FREE:
pieces_in_system += 1
return pieces_in_system % 2 == 1
def row_col_for_index(self, idx):
return self.gridmap[idx]
def update_piece_count(self):
self.white_pieces = []
for i, piece in enumerate(self.squares):
if piece & COLORS == WHITE:
self.white_pieces.append((i, piece))
self.black_pieces = []
for i, piece in enumerate(self.squares):
if piece & COLORS == BLACK:
self.black_pieces.append((i, piece))
self.white_total = len(self.white_pieces)
self.black_total = len(self.black_pieces)
def delete_redo_list(self):
del self.redo_list[:]
def make_move(self, move, notify=True, undo=True, annotation=''):
sq = self.squares
for idx, _, newval in move.affected_squares:
sq[idx] = newval
self.to_move ^= COLORS
if notify:
self.update_piece_count()
for o in self.observers:
o.notify(move)
if undo:
move.annotation = annotation
self.undo_list.append(move)
return self
def undo_move(self, move=None, notify=True, redo=True, annotation=''):
if move is None:
if not self.undo_list:
return
if redo:
move = self.undo_list.pop()
rev_move = Move([[idx, dest, src] for idx, src, dest
in move.affected_squares])
rev_move.annotation = move.annotation
self.make_move(rev_move, notify, False)
if redo:
move.annotation = annotation
self.redo_list.append(move)
def undo_all_moves(self, annotation=''):
while self.undo_list:
move = self.undo_list.pop()
rev_move = Move([[idx, dest, src] for idx, src, dest
in move.affected_squares])
rev_move.annotation = move.annotation
self.make_move(rev_move, True, False)
move.annotation = annotation
self.redo_list.append(move)
annotation = rev_move.annotation
def redo_move(self, move=None, annotation=''):
if move is None:
if not self.redo_list:
return
move = self.redo_list.pop()
self.make_move(move, True, True, annotation)
def redo_all_moves(self, annotation=''):
while self.redo_list:
move = self.redo_list.pop()
next_annotation = move.annotation
self.make_move(move, True, True, annotation)
annotation = next_annotation
def reset_undo(self):
self.undo_list = []
self.redo_list = []
def utility(self, player):
""" Player evaluation function """
sq = self.squares
code = sum(self.value[s] for s in sq)
nwm = code % 16
nwk = (code >> 4) % 16
nbm = (code >> 8) % 16
nbk = (code >> 12) % 16
v1 = 100 * nbm + 130 * nbk
v2 = 100 * nwm + 130 * nwk
eval = v1 - v2 # material values
# favor exchanges if in material plus
eval += (250 * (v1 - v2))/(v1 + v2)
nm = nbm + nwm
nk = nbk + nwk
# fine evaluation below
if player == BLACK:
eval += TURN
mult = -1
else:
eval -= TURN
mult = 1
return mult * \
(eval + self._eval_cramp(sq) + self._eval_backrankguard(sq) +
self._eval_doublecorner(sq) + self._eval_center(sq) +
self._eval_edge(sq) +
self._eval_tempo(sq, nm, nbk, nbm, nwk, nwm) +
self._eval_playeropposition(sq, nwm, nwk, nbk, nbm, nm, nk))
def _extend_capture(self, valid_moves, captures, add_sq_func, visited):
player = self.to_move
enemy = self.enemy
squares = self.squares
final_captures = []
while captures:
c = captures.pop()
new_captures = []
for j in valid_moves:
capture = c.affected_squares[:]
last_pos = capture[-1][0]
mid = last_pos+j
dest = last_pos+j*2
if ((last_pos, mid, dest) not in visited and
(dest, mid, last_pos) not in visited and
squares[mid] & enemy and
squares[dest] & FREE):
sq2, sq3 = add_sq_func(player, squares, mid, dest, last_pos)
capture[-1][2] = FREE
capture.extend([sq2, sq3])
visited.add((last_pos, mid, dest))
new_captures.append(Move(capture))
if new_captures:
captures.extend(new_captures)
else:
final_captures.append(Move(capture))
return final_captures
def _capture_man(self, player, squares, mid, dest, last_pos):
sq2 = [mid, squares[mid], FREE]
if ((player == BLACK and last_pos>=34) or
(player == WHITE and last_pos<=20)):
sq3 = [dest, FREE, player | KING]
else:
sq3 = [dest, FREE, player | MAN]
return sq2, sq3
def _capture_king(self, player, squares, mid, dest, last_pos):
sq2 = [mid, squares[mid], FREE]
sq3 = [dest, squares[dest], player | KING]
return sq2, sq3
def _get_captures(self):
player = self.to_move
enemy = self.enemy
squares = self.squares
valid_indices = WHITE_IDX if player == WHITE else BLACK_IDX
all_captures = []
for i in self.valid_squares:
if squares[i] & player and squares[i] & MAN:
for j in valid_indices:
mid = i+j
dest = i+j*2
if squares[mid] & enemy and squares[dest] & FREE:
sq1 = [i, player | MAN, FREE]
sq2 = [mid, squares[mid], FREE]
if ((player == BLACK and i>=34) or
(player == WHITE and i<=20)):
sq3 = [dest, FREE, player | KING]
else:
sq3 = [dest, FREE, player | MAN]
capture = [Move([sq1, sq2, sq3])]
visited = set()
visited.add((i, mid, dest))
temp = squares[i]
squares[i] = FREE
captures = self._extend_capture(valid_indices,
capture,
self._capture_man,
visited)
squares[i] = temp
all_captures.extend(captures)
if squares[i] & player and squares[i] & KING:
for j in KING_IDX:
mid = i+j
dest = i+j*2
if squares[mid] & enemy and squares[dest] & FREE:
sq1 = [i, player | KING, FREE]
sq2 = [mid, squares[mid], FREE]
sq3 = [dest, squares[dest], player | KING]
capture = [Move([sq1, sq2, sq3])]
visited = set()
visited.add((i, mid, dest))
temp = squares[i]
squares[i] = FREE
captures = self._extend_capture(KING_IDX,
capture,
self._capture_king,
visited)
squares[i] = temp
all_captures.extend(captures)
return all_captures
captures = property(_get_captures,
doc="Forced captures for the current player")
def _get_moves(self):
player = self.to_move
squares = self.squares
valid_indices = WHITE_IDX if player == WHITE else BLACK_IDX
moves = []
for i in self.valid_squares:
for j in valid_indices:
dest = i+j
if (squares[i] & player and
squares[i] & MAN and
squares[dest] & FREE):
sq1 = [i, player | MAN, FREE]
if ((player == BLACK and i>=39) or
(player == WHITE and i<=15)):
sq2 = [dest, FREE, player | KING]
else:
sq2 = [dest, FREE, player | MAN]
moves.append(Move([sq1, sq2]))
for j in KING_IDX:
dest = i+j
if (squares[i] & player and
squares[i] & KING and
squares[dest] & FREE):
sq1 = [i, player | KING, FREE]
sq2 = [dest, FREE, player | KING]
moves.append(Move([sq1, sq2]))
return moves
moves = property(_get_moves,
doc="Available moves for the current player")
def _eval_cramp(self, sq):
eval = 0
if sq[28] == BLACK | MAN and sq[34] == WHITE | MAN:
eval += CRAMP
if sq[26] == WHITE | MAN and sq[20] == BLACK | MAN:
eval -= CRAMP
return eval
def _eval_backrankguard(self, sq):
eval = 0
code = 0
if sq[6] & MAN: code += 1
if sq[7] & MAN: code += 2
if sq[8] & MAN: code += 4
if sq[9] & MAN: code += 8
backrank = self.rank[code]
code = 0
if sq[45] & MAN: code += 8
if sq[46] & MAN: code += 4
if sq[47] & MAN: code += 2
if sq[48] & MAN: code += 1
backrank = backrank - self.rank[code]
eval *= BRV * backrank
return eval
def _eval_doublecorner(self, sq):
eval = 0
if sq[9] == BLACK | MAN:
if sq[14] == BLACK | MAN or sq[15] == BLACK | MAN:
eval += INTACTDOUBLECORNER
if sq[45] == WHITE | MAN:
if sq[39] == WHITE | MAN or sq[40] == WHITE | MAN:
eval -= INTACTDOUBLECORNER
return eval
def _eval_center(self, sq):
eval = 0
nbmc = nbkc = nwmc = nwkc = 0
for c in self.center:
if sq[c] != FREE:
if sq[c] == BLACK | MAN:
nbmc += 1
if sq[c] == BLACK | KING:
nbkc += 1
if sq[c] == WHITE | MAN:
nwmc += 1
if sq[c] == WHITE | KING:
nwkc += 1
eval += (nbmc-nwmc) * MCV
eval += (nbkc-nwkc) * KCV
return eval
def _eval_edge(self, sq):
eval = 0
nbme = nbke = nwme = nwke = 0
for e in self.edge:
if sq[e] != FREE:
if sq[e] == BLACK | MAN:
nbme += 1
if sq[e] == BLACK | KING:
nbke += 1
if sq[e] == WHITE | MAN:
nwme += 1
if sq[e] == WHITE | KING:
nwke += 1
eval -= (nbme-nwme) * MEV
eval -= (nbke-nwke) * KEV
return eval
def _eval_tempo(self, sq, nm, nbk, nbm, nwk, nwm):
eval = tempo = 0
for i in range(6, 49):
if sq[i] == BLACK | MAN:
tempo += self.row[i]
if sq[i] == WHITE | MAN:
tempo -= 7 - self.row[i]
if nm >= 16:
eval += OPENING * tempo
if nm <= 15 and nm >= 12:
eval += MIDGAME * tempo
if nm < 9:
eval += ENDGAME * tempo
for s in self.safeedge:
if nbk + nbm > nwk + nwm and nwk < 3:
if sq[s] == WHITE | KING:
eval -= 15
if nwk + nwm > nbk + nbm and nbk < 3:
if sq[s] == BLACK | KING:
eval += 15
return eval
def _eval_playeropposition(self, sq, nwm, nwk, nbk, nbm, nm, nk):
eval = 0
pieces_in_system = 0
tn = nm + nk
if nwm + nwk - nbk - nbm == 0:
if self.to_move == BLACK:
for i in range(6, 10):
for j in range(4):
if sq[i+11*j] != FREE:
pieces_in_system += 1
if pieces_in_system % 2:
if tn <= 12: eval += 1
if tn <= 10: eval += 1
if tn <= 8: eval += 2
if tn <= 6: eval += 2
else:
if tn <= 12: eval -= 1
if tn <= 10: eval -= 1
if tn <= 8: eval -= 2
if tn <= 6: eval -= 2
else:
for i in range(12, 16):
for j in range(4):
if sq[i+11*j] != FREE:
pieces_in_system += 1
if pieces_in_system % 2 == 0:
if tn <= 12: eval += 1
if tn <= 10: eval += 1
if tn <= 8: eval += 2
if tn <= 6: eval += 2
else:
if tn <= 12: eval -= 1
if tn <= 10: eval -= 1
if tn <= 8: eval -= 2
if tn <= 6: eval -= 2
return eval
class Checkers(games.Game):
def __init__(self):
self.curr_state = Checkerboard()
def captures_available(self, curr_state=None):
state = curr_state or self.curr_state
return state.captures
def legal_moves(self, curr_state=None):
state = curr_state or self.curr_state
return state.captures or state.moves
def make_move(self, move, curr_state=None, notify=True, undo=True,
annotation=''):
state = curr_state or self.curr_state
return state.make_move(move, notify, undo, annotation)
def undo_move(self, move=None, curr_state=None, notify=True, redo=True,
annotation=''):
state = curr_state or self.curr_state
return state.undo_move(move, notify, redo, annotation)
def undo_all_moves(self, curr_state=None, annotation=''):
state = curr_state or self.curr_state
return state.undo_all_moves(annotation)
def redo_move(self, move=None, curr_state=None, annotation=''):
state = curr_state or self.curr_state
return state.redo_move(move, annotation)
def redo_all_moves(self, curr_state=None, annotation=''):
state = curr_state or self.curr_state
return state.redo_all_moves(annotation)
def utility(self, player, curr_state=None):
state = curr_state or self.curr_state
return state.utility(player)
def terminal_test(self, curr_state=None):
state = curr_state or self.curr_state
return not self.legal_moves(state)
def successors(self, curr_state=None):
state = curr_state or self.curr_state
moves = self.legal_moves(state)
if not moves:
yield [], state
else:
undone = False
try:
try:
for move in moves:
undone = False
self.make_move(move, state, False)
yield move, state
self.undo_move(move, state, False)
undone = True
except GeneratorExit:
raise
finally:
if moves and not undone:
self.undo_move(move, state, False)
def perft(self, depth, curr_state=None):
if depth == 0:
return 1
state = curr_state or self.curr_state
nodes = 0
for move in self.legal_moves(state):
state.make_move(move, False, False)
nodes += self.perft(depth-1, state)
state.undo_move(move, False, False)
return nodes
def play():
game = Checkers()
for depth in range(1, 11):
start = time.time()
print "Perft for depth %d: %d. Time: %5.3f sec" % (depth,
game.perft(depth),
time.time() - start)
if __name__ == '__main__':
play()
| Python |
from goal import Goal
class CompositeGoal(Goal):
def __init__(self, owner):
Goal.__init__(self, owner)
self.subgoals = []
def removeAllSubgoals(self):
for s in self.subgoals:
s.terminate()
self.subgoals = []
def processSubgoals(self):
# remove all completed and failed goals from the front of the
# subgoal list
while (self.subgoals and (self.subgoals[0].isComplete or
self.subgoals[0].hasFailed)):
subgoal = self.subgoals.pop()
subgoal.terminate()
if (self.subgoals):
subgoal = self.subgoals.pop()
status = subgoal.process()
if status == COMPLETED and len(self.subgoals) > 1:
return ACTIVE
return status
else:
return COMPLETED
def addSubgoal(self, goal):
self.subgoals.append(goal)
| Python |
class Controller(object):
def stop_process(self):
pass
| Python |
"""Provide some widely useful utilities. Safe for "from utils import *"."""
from __future__ import generators
import operator, math, random, copy, sys, os.path, bisect
#______________________________________________________________________________
# Simple Data Structures: booleans, infinity, Dict, Struct
infinity = 1.0e400
def Dict(**entries):
"""Create a dict out of the argument=value arguments.
Ex: Dict(a=1, b=2, c=3) ==> {'a':1, 'b':2, 'c':3}"""
return entries
class DefaultDict(dict):
"""Dictionary with a default value for unknown keys.
Ex: d = DefaultDict(0); d['x'] += 1; d['x'] ==> 1
d = DefaultDict([]); d['x'] += [1]; d['y'] += [2]; d['x'] ==> [1]"""
def __init__(self, default):
self.default = default
def __getitem__(self, key):
if key in self: return self.get(key)
return self.setdefault(key, copy.deepcopy(self.default))
class Struct:
"""Create an instance with argument=value slots.
This is for making a lightweight object whose class doesn't matter.
Ex: s = Struct(a=1, b=2); s.a ==> 1; s.a = 3; s ==> Struct(a=3, b=2)"""
def __init__(self, **entries):
self.__dict__.update(entries)
def __cmp__(self, other):
if isinstance(other, Struct):
return cmp(self.__dict__, other.__dict__)
else:
return cmp(self.__dict__, other)
def __repr__(self):
args = ['%s=%s' % (k, repr(v)) for (k, v) in vars(self).items()]
return 'Struct(%s)' % ', '.join(args)
def update(x, **entries):
"""Update a dict, or an object with slots, according to entries.
Ex: update({'a': 1}, a=10, b=20) ==> {'a': 10, 'b': 20}
update(Struct(a=1), a=10, b=20) ==> Struct(a=10, b=20)"""
if isinstance(x, dict):
x.update(entries)
else:
x.__dict__.update(entries)
return x
#______________________________________________________________________________
# Functions on Sequences (mostly inspired by Common Lisp)
# NOTE: Sequence functions (count_if, find_if, every, some) take function
# argument first (like reduce, filter, and map).
def sort(seq, compare=cmp):
"""Sort seq (mutating it) and return it. compare is the 2nd arg to .sort.
Ex: sort([3, 1, 2]) ==> [1, 2, 3]; reverse(sort([3, 1, 2])) ==> [3, 2, 1]
sort([-3, 1, 2], comparer(abs)) ==> [1, 2, -3]"""
if isinstance(seq, str):
seq = ''.join(sort(list(seq), compare))
elif compare == cmp:
seq.sort()
else:
seq.sort(compare)
return seq
def comparer(key=None, cmp=cmp):
"""Build a compare function suitable for sort. The most common use is
to specify key, meaning compare the values of key(x), key(y)."""
if key == None:
return cmp
else:
return lambda x,y: cmp(key(x), key(y))
def removeall(item, seq):
"""Return a copy of seq (or string) with all occurences of item removed.
Ex: removeall(3, [1, 2, 3, 3, 2, 1, 3]) ==> [1, 2, 2, 1]
removeall(4, [1, 2, 3]) ==> [1, 2, 3]"""
if isinstance(seq, str):
return seq.replace(item, '')
else:
return [x for x in seq if x != item]
def reverse(seq):
"""Return the reverse of a string or list or tuple. Mutates the seq.
Ex: reverse([1, 2, 3]) ==> [3, 2, 1]; reverse('abc') ==> 'cba'"""
if isinstance(seq, str):
return ''.join(reverse(list(seq)))
elif isinstance(seq, tuple):
return tuple(reverse(list(seq)))
else:
seq.reverse();
return seq
def unique(seq):
"""Remove duplicate elements from seq. Assumes hashable elements.
Ex: unique([1, 2, 3, 2, 1]) ==> [1, 2, 3] # order may vary"""
return list(set(seq))
def count_if(predicate, seq):
"""Count the number of elements of seq for which the predicate is true.
count_if(callable, [42, None, max, min]) ==> 2"""
f = lambda count, x: count + (not not predicate(x))
return reduce(f, seq, 0)
def find_if(predicate, seq):
"""If there is an element of seq that satisfies predicate, return it.
Ex: find_if(callable, [3, min, max]) ==> min
find_if(callable, [1, 2, 3]) ==> None"""
for x in seq:
if predicate(x): return x
return None
def every(predicate, seq):
"""True if every element of seq satisfies predicate.
Ex: every(callable, [min, max]) ==> 1; every(callable, [min, 3]) ==> 0"""
for x in seq:
if not predicate(x): return False
return True
def some(predicate, seq):
"""If some element x of seq satisfies predicate(x), return predicate(x).
Ex: some(callable, [min, 3]) ==> 1; some(callable, [2, 3]) ==> 0"""
for x in seq:
px = predicate(x)
if px: return px
return False
# Added by Brandon
def flatten(x):
if type(x) != type([]): return [x]
if x == []: return x
return flatten(x[0]) + flatten(x[1:])
#______________________________________________________________________________
# Functions on sequences of numbers
# NOTE: these take the sequence argument first, like min and max,
# and like standard math notation: \sigma (i = 1..n) fn(i)
# A lot of programing is finding the best value that satisfies some condition;
# so there are three versions of argmin/argmax, depending on what you want to
# do with ties: return the first one, return them all, or pick at random.
def sum(seq, fn=None):
"""Sum the elements seq[i], or fn(seq[i]) if fn is given.
Ex: sum([1, 2, 3]) ==> 6; sum(range(8), lambda x: 2**x) ==> 255"""
if fn: seq = map(fn, seq)
return reduce(operator.add, seq, 0)
def product(seq, fn=None):
"""Multiply the elements seq[i], or fn(seq[i]) if fn is given.
product([1, 2, 3]) ==> 6; product([1, 2, 3], lambda x: x*x) ==> 1*4*9"""
if fn: seq = map(fn, seq)
return reduce(operator.mul, seq, 1)
def argmin(gen, fn):
"""Return an element with lowest fn(x) score; tie goes to first one.
Gen must be a generator.
Ex: argmin(['one', 'to', 'three'], len) ==> 'to'"""
best = gen.next(); best_score = fn(best)
for x in gen:
x_score = fn(x)
if x_score < best_score:
best, best_score = x, x_score
return best
def argmin_list(gen, fn):
"""Return a list of elements of gen with the lowest fn(x) scores.
Ex: argmin_list(['one', 'to', 'three', 'or'], len) ==> ['to', 'or']"""
best_score, best = fn(gen.next()), []
for x in gen:
x_score = fn(x)
if x_score < best_score:
best, best_score = [x], x_score
elif x_score == best_score:
best.append(x)
return best
#def argmin_list(seq, fn):
# """Return a list of elements of seq[i] with the lowest fn(seq[i]) scores.
# Ex: argmin_list(['one', 'to', 'three', 'or'], len) ==> ['to', 'or']"""
# best_score, best = fn(seq[0]), []
# for x in seq:
# x_score = fn(x)
# if x_score < best_score:
# best, best_score = [x], x_score
# elif x_score == best_score:
# best.append(x)
# return best
def argmin_random_tie(gen, fn):
"""Return an element with lowest fn(x) score; break ties at random.
Thus, for all s,f: argmin_random_tie(s, f) in argmin_list(s, f)"""
try:
best = gen.next(); best_score = fn(best); n = 0
except StopIteration:
return []
for x in gen:
x_score = fn(x)
if x_score < best_score:
best, best_score = x, x_score; n = 1
elif x_score == best_score:
n += 1
if random.randrange(n) == 0:
best = x
return best
#def argmin_random_tie(seq, fn):
# """Return an element with lowest fn(seq[i]) score; break ties at random.
# Thus, for all s,f: argmin_random_tie(s, f) in argmin_list(s, f)"""
# best_score = fn(seq[0]); n = 0
# for x in seq:
# x_score = fn(x)
# if x_score < best_score:
# best, best_score = x, x_score; n = 1
# elif x_score == best_score:
# n += 1
# if random.randrange(n) == 0:
# best = x
# return best
def argmax(gen, fn):
"""Return an element with highest fn(x) score; tie goes to first one.
Ex: argmax(['one', 'to', 'three'], len) ==> 'three'"""
return argmin(gen, lambda x: -fn(x))
def argmax_list(seq, fn):
"""Return a list of elements of gen with the highest fn(x) scores.
Ex: argmax_list(['one', 'three', 'seven'], len) ==> ['three', 'seven']"""
return argmin_list(seq, lambda x: -fn(x))
def argmax_random_tie(seq, fn):
"Return an element with highest fn(x) score; break ties at random."
return argmin_random_tie(seq, lambda x: -fn(x))
#______________________________________________________________________________
# Statistical and mathematical functions
def histogram(values, mode=0, bin_function=None):
"""Return a list of (value, count) pairs, summarizing the input values.
Sorted by increasing value, or if mode=1, by decreasing count.
If bin_function is given, map it over values first.
Ex: vals = [100, 110, 160, 200, 160, 110, 200, 200, 220]
histogram(vals) ==> [(100, 1), (110, 2), (160, 2), (200, 3), (220, 1)]
histogram(vals, 1) ==> [(200, 3), (160, 2), (110, 2), (100, 1), (220, 1)]
histogram(vals, 1, lambda v: round(v, -2)) ==> [(200.0, 6), (100.0, 3)]"""
if bin_function: values = map(bin_function, values)
bins = {}
for val in values:
bins[val] = bins.get(val, 0) + 1
if mode:
return sort(bins.items(), lambda x,y: cmp(y[1],x[1]))
else:
return sort(bins.items())
def log2(x):
"""Base 2 logarithm.
Ex: log2(1024) ==> 10.0; log2(1.0) ==> 0.0; log2(0) raises OverflowError"""
return math.log10(x) / math.log10(2)
def mode(values):
"""Return the most common value in the list of values.
Ex: mode([1, 2, 3, 2]) ==> 2"""
return histogram(values, mode=1)[0][0]
def median(values):
"""Return the middle value, when the values are sorted.
If there are an odd number of elements, try to average the middle two.
If they can't be averaged (e.g. they are strings), choose one at random.
Ex: median([10, 100, 11]) ==> 11; median([1, 2, 3, 4]) ==> 2.5"""
n = len(values)
values = sort(values[:])
if n % 2 == 1:
return values[n/2]
else:
middle2 = values[(n/2)-1:(n/2)+1]
try:
return mean(middle2)
except TypeError:
return random.choice(middle2)
def mean(values):
"""Return the arithmetic average of the values."""
return sum(values) / float(len(values))
def stddev(values, meanval=None):
"""The standard deviation of a set of values.
Pass in the mean if you already know it."""
if meanval == None: meanval = mean(values)
return math.sqrt(sum([(x - meanval)**2 for x in values]))
def dotproduct(X, Y):
"""Return the sum of the element-wise product of vectors x and y.
Ex: dotproduct([1, 2, 3], [1000, 100, 10]) ==> 1230"""
return sum([x * y for x, y in zip(X, Y)])
def vector_add(a, b):
"""Component-wise addition of two vectors.
Ex: vector_add((0, 1), (8, 9)) ==> (8, 10)"""
return tuple(map(operator.add, a, b))
def probability(p):
"Return true with probability p."
return p > random.uniform(0.0, 1.0)
def num_or_str(x):
"""The argument is a string; convert to a number if possible, or strip it.
Ex: num_or_str('42') ==> 42; num_or_str(' 42x ') ==> '42x' """
try:
return int(x)
except ValueError:
try:
return float(x)
except ValueError:
return str(x).strip()
def distance((ax, ay), (bx, by)):
"The distance between two (x, y) points."
return math.hypot((ax - bx), (ay - by))
def distance2((ax, ay), (bx, by)):
"The square of the distance between two (x, y) points."
return (ax - bx)**2 + (ay - by)**2
def normalize(numbers, total=1.0):
"""Multiply each number by a constant such that the sum is 1.0 (or total).
Ex: normalize([1,2,1]) ==> [0.25, 0.5, 0.25]"""
k = total / sum(numbers)
return [k * n for n in numbers]
#______________________________________________________________________________
# Misc Functions
def printf(format, *args):
"""Format args with the first argument as format string, and write.
Return the last arg, or format itself if there are no args."""
sys.stdout.write(str(format) % args)
return if_(args, args[-1], format)
def print_(*args):
"""Print the args and return the last one."""
for arg in args: print arg,
print
return if_(args, args[-1], None)
def memoize(fn, slot=None):
"""Memoize fn: make it remember the computed value for any argument list.
If slot is specified, store result in that slot of first argument.
If slot is false, store results in a dictionary.
Ex: def fib(n): return (n<=1 and 1) or (fib(n-1) + fib(n-2)); fib(9) ==> 55
# Now we make it faster:
fib = memoize(fib); fib(9) ==> 55"""
if slot:
def memoized_fn(obj, *args):
if hasattr(obj, slot):
return getattr(obj, slot)
else:
val = fn(obj, *args)
setattr(obj, slot, val)
return val
else:
def memoized_fn(*args):
if not memoized_fn.cache.has_key(args):
memoized_fn.cache[args] = fn(*args)
return memoized_fn.cache[args]
memoized_fn.cache = {}
return memoized_fn
def method(name, *args):
"""Return a function that invokes the named method with the optional args.
Ex: map(method('upper'), ['a', 'b', 'cee']) ==> ['A', 'B', 'CEE']
map(method('count', 't'), ['this', 'is', 'a', 'test']) ==> [1, 0, 0, 2]"""
return lambda x: getattr(x, name)(*args)
def method2(name, *static_args):
"""Return a function that invokes the named method with the optional args.
Ex: map(method('upper'), ['a', 'b', 'cee']) ==> ['A', 'B', 'CEE']
map(method('count', 't'), ['this', 'is', 'a', 'test']) ==> [1, 0, 0, 2]"""
return lambda x, *dyn_args: getattr(x, name)(*(dyn_args + static_args))
def abstract():
"""Indicate abstract methods that should be implemented in a subclass.
Ex: def m(): abstract() # Similar to Java's 'abstract void m()'"""
raise NotImplementedError(caller() + ' must be implemented in subclass')
def caller(n=1):
"""Return the name of the calling function n levels up in the frame stack.
Ex: caller(0) ==> 'caller'; def f(): return caller(); f() ==> 'f'"""
import inspect
return inspect.getouterframes(inspect.currentframe())[n][3]
def indexed(seq):
"""Like [(i, seq[i]) for i in range(len(seq))], but with yield.
Ex: for i, c in indexed('abc'): print i, c"""
i = 0
for x in seq:
yield i, x
i += 1
def if_(test, result, alternative):
"""Like C++ and Java's (test ? result : alternative), except
both result and alternative are always evaluated. However, if
either evaluates to a function, it is applied to the empty arglist,
so you can delay execution by putting it in a lambda.
Ex: if_(2 + 2 == 4, 'ok', lambda: expensive_computation()) ==> 'ok' """
if test:
if callable(result): return result()
return result
else:
if callable(alternative): return alternative()
return alternative
def name(object):
"Try to find some reasonable name for the object."
return (getattr(object, 'name', 0) or getattr(object, '__name__', 0)
or getattr(getattr(object, '__class__', 0), '__name__', 0)
or str(object))
def isnumber(x):
"Is x a number? We say it is if it has a __int__ method."
return hasattr(x, '__int__')
def issequence(x):
"Is x a sequence? We say it is if it has a __getitem__ method."
return hasattr(x, '__getitem__')
def print_table(table, header=None, sep=' ', numfmt='%g'):
"""Print a list of lists as a table, so that columns line up nicely.
header, if specified, will be printed as the first row.
numfmt is the format for all numbers; you might want e.g. '%6.2f'.
(If you want different formats in differnt columns, don't use print_table.)
sep is the separator between columns."""
justs = [if_(isnumber(x), 'rjust', 'ljust') for x in table[0]]
if header:
table = [header] + table
table = [[if_(isnumber(x), lambda: numfmt % x, x) for x in row]
for row in table]
maxlen = lambda seq: max(map(len, seq))
sizes = map(maxlen, zip(*[map(str, row) for row in table]))
for row in table:
for (j, size, x) in zip(justs, sizes, row):
print getattr(str(x), j)(size), sep,
print
def AIMAFile(components, mode='r'):
"Open a file based at the AIMA root directory."
dir = os.path.dirname(__file__)
return open(apply(os.path.join, [dir] + components), mode)
def DataFile(name, mode='r'):
"Return a file in the AIMA /data directory."
return AIMAFile(['data', name], mode)
#______________________________________________________________________________
# Queues: Stack, FIFOQueue, PriorityQueue
class Queue:
"""Queue is an abstract class/interface. There are three types:
Stack(): A Last In First Out Queue.
FIFOQueue(): A First In First Out Queue.
PriorityQueue(lt): Queue where items are sorted by lt, (default <).
Each type supports the following methods and functions:
q.append(item) -- add an item to the queue
q.extend(items) -- equivalent to: for item in items: q.append(item)
q.pop() -- return the top item from the queue
len(q) -- number of items in q (also q.__len())
Note that isinstance(Stack(), Queue) is false, because we implement stacks
as lists. If Python ever gets interfaces, Queue will be an interface."""
def __init__(self): abstract()
def extend(self, items):
for item in items: self.append(item)
def Stack():
"""Return an empty list, suitable as a Last-In-First-Out Queue.
Ex: q = Stack(); q.append(1); q.append(2); q.pop(), q.pop() ==> (2, 1)"""
return []
class FIFOQueue(Queue):
"""A First-In-First-Out Queue.
Ex: q = FIFOQueue();q.append(1);q.append(2); q.pop(), q.pop() ==> (1, 2)"""
def __init__(self):
self.A = []; self.start = 0
def append(self, item):
self.A.append(item)
def __len__(self):
return len(self.A) - self.start
def extend(self, items):
self.A.extend(items)
def pop(self):
e = self.A[self.start]
self.start += 1
if self.start > 5 and self.start > len(self.A)/2:
self.A = self.A[self.start:]
self.start = 0
return e
class PriorityQueue(Queue):
"""A queue in which the minimum (or maximum) element (as determined by f and
order) is returned first. If order is min, the item with minimum f(x) is
returned first; if order is max, then it is the item with maximum f(x)."""
def __init__(self, order=min, f=lambda x: x):
update(self, A=[], order=order, f=f)
def append(self, item):
bisect.insort(self.A, (self.f(item), item))
def __len__(self):
return len(self.A)
def pop(self):
if self.order == min:
return self.A.pop(0)[1]
else:
return self.A.pop()[1]
#______________________________________________________________________________
## NOTE: Once we upgrade to Python 2.3, the following class can be replaced by
## from sets import set
class set:
"""This implements the set class from PEP 218, except it does not
overload the infix operators.
Ex: s = set([1,2,3]); 1 in s ==> True; 4 in s ==> False
s.add(4); 4 in s ==> True; len(s) ==> 4
s.discard(999); s.remove(4); 4 in s ==> False
s2 = set([3,4,5]); s.union(s2) ==> set([1,2,3,4,5])
s.intersection(s2) ==> set([3])
set([1,2,3]) == set([3,2,1]); repr(s) == '{1, 2, 3}'
for e in s: pass"""
def __init__(self, elements):
self.dict = {}
for e in elements:
self.dict[e] = 1
def __contains__(self, element):
return element in self.dict
def add(self, element):
self.dict[element] = 1
def remove(self, element):
del self.dict[element]
def discard(self, element):
if element in self.dict:
del self.dict[element]
def clear(self):
self.dict.clear()
def union(self, other):
return set(self).union_update(other)
def intersection(self, other):
return set(self).intersection_update(other)
def union_update(self, other):
for e in other:
self.add(e)
def intersection_update(self, other):
for e in self.dict.keys():
if e not in other:
self.remove(e)
def __iter__(self):
for e in self.dict:
yield e
def __len__(self):
return len(self.dict)
def __cmp__(self, other):
return (self is other or
(isinstance(other, set) and self.dict == other.dict))
def __repr__(self):
return "{%s}" % ", ".join([str(e) for e in self.dict.keys()])
#______________________________________________________________________________
# Additional tests
_docex = """
def is_even(x): return x % 2 == 0
sort([1, 2, -3]) ==> [-3, 1, 2]
sort(range(10), comparer(key=is_even)) ==> [1, 3, 5, 7, 9, 0, 2, 4, 6, 8]
sort(range(10), lambda x,y: y-x) ==> [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
removeall(4, []) ==> []
removeall('s', 'This is a test. Was a test.') ==> 'Thi i a tet. Wa a tet.'
removeall('s', 'Something') ==> 'Something'
removeall('s', '') ==> ''
reverse([]) ==> []
reverse('') ==> ''
count_if(is_even, [1, 2, 3, 4]) ==> 2
count_if(is_even, []) ==> 0
sum([]) ==> 0
product([]) ==> 1
argmax([1], lambda x: x*x) ==> 1
argmin([1], lambda x: x*x) ==> 1
argmax([]) raises TypeError
argmin([]) raises TypeError
# Test of memoize with slots in structures
countries = [Struct(name='united states'), Struct(name='canada')]
# Pretend that 'gnp' was some big hairy operation:
def gnp(country): return len(country.name) * 1e10
gnp = memoize(gnp, '_gnp')
map(gnp, countries) ==> [13e10, 6e10]
countries # note the _gnp slot.
# This time we avoid re-doing the calculation
map(gnp, countries) ==> [13e10, 6e10]
# Test Queues:
nums = [1, 8, 2, 7, 5, 6, -99, 99, 4, 3, 0]
def qtest(q): return [q.extend(nums), [q.pop() for i in range(len(q))]][1]
qtest(Stack()) ==> reverse(nums)
qtest(FIFOQueue()) ==> nums
qtest(PriorityQueue(min)) ==> [-99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 99]
qtest(PriorityQueue(max)) ==> [99, 8, 7, 6, 5, 4, 3, 2, 1, 0, -99]
qtest(PriorityQueue(min, abs)) ==> [0, 1, 2, 3, 4, 5, 6, 7, 8, -99, 99]
qtest(PriorityQueue(max, abs)) ==> [99, -99, 8, 7, 6, 5, 4, 3, 2, 1, 0]
"""
| Python |
import os
from Tkinter import *
from Tkconstants import END, N, S, E, W
from command import *
from observer import *
from globalconst import *
from autoscrollbar import AutoScrollbar
from textserialize import Serializer
from hyperlinkmgr import HyperlinkManager
from tkFileDialog import askopenfilename
from tkFont import Font
from tooltip import ToolTip
class BoardView(Observer):
def __init__(self, root, **props):
self._statusbar = props['statusbar']
self.root = root
self._model = props['model']
self._model.curr_state.attach(self)
self._gameMgr = props['parent']
self._board_side = props.get('side') or DEFAULT_SIZE
self.light_squares = props.get('lightsquares') or LIGHT_SQUARES
self.dark_squares = props.get('darksquares') or DARK_SQUARES
self.light_color = props.get('lightcheckers') or LIGHT_CHECKERS
self.dark_color = props.get('darkcheckers') or DARK_CHECKERS
self._square_size = self._board_side / 8
self._piece_offset = self._square_size / 5
self._crownpic = PhotoImage(file=CROWN_IMAGE)
self._boardpos = create_position_map()
self._gridpos = create_grid_map()
self.canvas = Canvas(root, width=self._board_side,
height=self._board_side, borderwidth=0,
highlightthickness=0)
right_panel = Frame(root, borderwidth=1, relief='sunken')
self.toolbar = Frame(root)
font, size = get_preferences_from_file()
self.scrollbar = AutoScrollbar(root, container=right_panel,
row=1, column=1, sticky='ns')
self.txt = Text(root, width=40, height=1, borderwidth=0,
font=(font,size), wrap='word',
yscrollcommand=self.scrollbar.set)
self.scrollbar.config(command=self.txt.yview)
self.canvas.pack(side='left', fill='both', expand=False)
self.toolbar.grid(in_=right_panel, row=0, column=0, sticky='ew')
right_panel.pack(side='right', fill='both', expand=True)
self.txt.grid(in_=right_panel, row=1, column=0, sticky='nsew')
right_panel.grid_rowconfigure(1, weight=1)
right_panel.grid_columnconfigure(0, weight=1)
self.init_images()
self.init_toolbar_buttons()
self.init_font_sizes(font, size)
self.init_tags()
self._register_event_handlers()
self.btnset = set([self.bold, self.italic, self.addLink, self.remLink])
self.btnmap = {'bold': self.bold, 'italic': self.italic,
'bullet': self.bullets, 'number': self.numbers,
'hyper': self.addLink}
self.hypermgr = HyperlinkManager(self.txt, self._gameMgr.load_game)
self.serializer = Serializer(self.txt, self.hypermgr)
self.curr_annotation = ''
self._setup_board(root)
starting_squares = [i for i in self._model.curr_state.valid_squares
if self._model.curr_state.squares[i] &
(BLACK | WHITE)]
self._draw_checkers(Command(add=starting_squares))
self.flip_view = False # black on bottom
self._label_board()
self.update_statusbar()
def _toggle_state(self, tags, btn):
# toggle the text state based on the first character in the
# selected range.
if self.txt.tag_ranges('sel'):
current_tags = self.txt.tag_names('sel.first')
elif self.txt.tag_ranges('insert'):
current_tags = self.txt.tag_names('insert')
else:
return
for tag in tags:
already_tagged = any((x for x in current_tags if
x.startswith(tag)))
for t in current_tags:
if t != 'sel':
self.txt.tag_remove(t, 'sel.first', 'sel.last')
if not already_tagged:
self.txt.tag_add(tag, 'sel.first', 'sel.last')
btn.configure(relief='sunken')
other_btns = self.btnset.difference([btn])
for b in other_btns:
b.configure(relief='raised')
else:
btn.configure(relief='raised')
def _on_bold(self):
self.bold_tooltip.hide()
self._toggle_state(['bold'], self.bold)
def _on_italic(self):
self.italic_tooltip.hide()
self._toggle_state(['italic'], self.italic)
def _on_bullets(self):
self._process_button_click('bullet', self.bullets_tooltip,
self._add_bullets_if_needed,
self._remove_bullets_if_needed)
def _on_numbers(self):
self._process_button_click('number', self.numbers_tooltip,
self._add_numbers_if_needed,
self._remove_numbers_if_needed)
def _process_button_click(self, tag, tooltip, add_func, remove_func):
tooltip.hide()
if self.txt.tag_ranges('sel'):
startline, _ = parse_index(self.txt.index('sel.first'))
endline, _ = parse_index(self.txt.index('sel.last'))
else:
startline, _ = parse_index(self.txt.index(INSERT))
endline = startline
current_tags = self.txt.tag_names('%d.0' % startline)
if tag not in current_tags:
add_func(startline, endline)
else:
remove_func(startline, endline)
def _add_bullets_if_needed(self, startline, endline):
self._remove_numbers_if_needed(startline, endline)
for line in range(startline, endline+1):
current_tags = self.txt.tag_names('%d.0' % line)
if 'bullet' not in current_tags:
start = '%d.0' % line
end = '%d.end' % line
self.txt.insert(start, '\t')
self.txt.image_create(start, image=self.bullet_image)
self.txt.insert(start, '\t')
self.txt.tag_add('bullet', start, end)
self.bullets.configure(relief='sunken')
self.numbers.configure(relief='raised')
def _remove_bullets_if_needed(self, startline, endline):
for line in range(startline, endline+1):
current_tags = self.txt.tag_names('%d.0' % line)
if 'bullet' in current_tags:
start = '%d.0' % line
end = '%d.end' % line
self.txt.tag_remove('bullet', start, end)
start = '%d.0' % line
end = '%d.3' % line
self.txt.delete(start, end)
self.bullets.configure(relief='raised')
def _add_numbers_if_needed(self, startline, endline):
self._remove_bullets_if_needed(startline, endline)
num = 1
for line in range(startline, endline+1):
current_tags = self.txt.tag_names('%d.0' % line)
if 'number' not in current_tags:
start = '%d.0' % line
end = '%d.end' % line
self.txt.insert(start, '\t')
numstr = '%d.' % num
self.txt.insert(start, numstr)
self.txt.insert(start, '\t')
self.txt.tag_add('number', start, end)
num += 1
self.numbers.configure(relief='sunken')
self.bullets.configure(relief='raised')
def _remove_numbers_if_needed(self, startline, endline):
cnt = IntVar()
for line in range(startline, endline+1):
current_tags = self.txt.tag_names('%d.0' % line)
if 'number' in current_tags:
start = '%d.0' % line
end = '%d.end' % line
self.txt.tag_remove('number', start, end)
# Regex to match a tab, followed by any number of digits,
# followed by a period, all at the start of a line.
# The cnt variable stores the number of characters matched.
pos = self.txt.search('^\t\d+\.\t', start, end, None, None,
None, True, None, cnt)
if pos:
end = '%d.%d' % (line, cnt.get())
self.txt.delete(start, end)
self.numbers.configure(relief='raised')
def _on_undo(self):
self.undo_tooltip.hide()
self._gameMgr.parent.undo_single_move()
def _on_undo_all(self):
self.undoall_tooltip.hide()
self._gameMgr.parent.undo_all_moves()
def _on_redo(self):
self.redo_tooltip.hide()
self._gameMgr.parent.redo_single_move()
def _on_redo_all(self):
self.redoall_tooltip.hide()
self._gameMgr.parent.redo_all_moves()
def _on_add_link(self):
filename = askopenfilename(initialdir='training')
if filename:
filename = os.path.relpath(filename, CUR_DIR)
self._toggle_state(self.hypermgr.add(filename), self.addLink)
def _on_remove_link(self):
if self.txt.tag_ranges('sel'):
current_tags = self.txt.tag_names('sel.first')
if 'hyper' in current_tags:
self._toggle_state(['hyper'], self.addLink)
def _register_event_handlers(self):
self.txt.event_add('<<KeyRel>>', '<KeyRelease-Home>', '<KeyRelease-End>',
'<KeyRelease-Left>', '<KeyRelease-Right>',
'<KeyRelease-Up>', '<KeyRelease-Down>',
'<KeyRelease-Delete>', '<KeyRelease-BackSpace>')
Widget.bind(self.txt, '<<Selection>>', self._sel_changed)
Widget.bind(self.txt, '<ButtonRelease-1>', self._sel_changed)
Widget.bind(self.txt, '<<KeyRel>>', self._key_release)
def _key_release(self, event):
line, char = parse_index(self.txt.index(INSERT))
self.update_button_state(to_string(line, char))
def _sel_changed(self, event):
self.update_button_state(self.txt.index(INSERT))
def is_dirty(self):
return self.curr_annotation != self.get_annotation()
def reset_toolbar_buttons(self):
for btn in self.btnset:
btn.configure(relief='raised')
def update_button_state(self, index):
if self.txt.tag_ranges('sel'):
current_tags = self.txt.tag_names('sel.first')
else:
current_tags = self.txt.tag_names(index)
for btn in self.btnmap.itervalues():
btn.configure(relief='raised')
for tag in current_tags:
if tag in self.btnmap.keys():
self.btnmap[tag].configure(relief='sunken')
def init_font_sizes(self, font, size):
self.txt.config(font=[font, size])
self._b_font = Font(self.root, (font, size, 'bold'))
self._i_font = Font(self.root, (font, size, 'italic'))
def init_tags(self):
self.txt.tag_config('bold', font=self._b_font, wrap='word')
self.txt.tag_config('italic', font=self._i_font, wrap='word')
self.txt.tag_config('number', tabs='.5c center 1c left',
lmargin1='0', lmargin2='1c')
self.txt.tag_config('bullet', tabs='.5c center 1c left',
lmargin1='0', lmargin2='1c')
def init_images(self):
self.bold_image = PhotoImage(file=BOLD_IMAGE)
self.italic_image = PhotoImage(file=ITALIC_IMAGE)
self.addlink_image = PhotoImage(file=ADDLINK_IMAGE)
self.remlink_image = PhotoImage(file=REMLINK_IMAGE)
self.bullets_image = PhotoImage(file=BULLETS_IMAGE)
self.bullet_image = PhotoImage(file=BULLET_IMAGE)
self.numbers_image = PhotoImage(file=NUMBERS_IMAGE)
self.undo_image = PhotoImage(file=UNDO_IMAGE)
self.undoall_image= PhotoImage(file=UNDOALL_IMAGE)
self.redo_image = PhotoImage(file=REDO_IMAGE)
self.redoall_image = PhotoImage(file=REDOALL_IMAGE)
def init_toolbar_buttons(self):
self.bold = Button(name='bold', image=self.bold_image,
borderwidth=1, command=self._on_bold)
self.bold.grid(in_=self.toolbar, row=0, column=0, sticky=W)
self.italic = Button(name='italic', image=self.italic_image,
borderwidth=1, command=self._on_italic)
self.italic.grid(in_=self.toolbar, row=0, column=1, sticky=W)
self.bullets = Button(name='bullets', image=self.bullets_image,
borderwidth=1, command=self._on_bullets)
self.bullets.grid(in_=self.toolbar, row=0, column=2, sticky=W)
self.numbers = Button(name='numbers', image=self.numbers_image,
borderwidth=1, command=self._on_numbers)
self.numbers.grid(in_=self.toolbar, row=0, column=3, sticky=W)
self.addLink = Button(name='addlink', image=self.addlink_image,
borderwidth=1, command=self._on_add_link)
self.addLink.grid(in_=self.toolbar, row=0, column=4, sticky=W)
self.remLink = Button(name='remlink', image=self.remlink_image,
borderwidth=1, command=self._on_remove_link)
self.remLink.grid(in_=self.toolbar, row=0, column=5, sticky=W)
self.frame = Frame(width=0)
self.frame.grid(in_=self.toolbar, padx=5, row=0, column=6, sticky=W)
self.undoall = Button(name='undoall', image=self.undoall_image,
borderwidth=1, command=self._on_undo_all)
self.undoall.grid(in_=self.toolbar, row=0, column=7, sticky=W)
self.undo = Button(name='undo', image=self.undo_image,
borderwidth=1, command=self._on_undo)
self.undo.grid(in_=self.toolbar, row=0, column=8, sticky=W)
self.redo = Button(name='redo', image=self.redo_image,
borderwidth=1, command=self._on_redo)
self.redo.grid(in_=self.toolbar, row=0, column=9, sticky=W)
self.redoall = Button(name='redoall', image=self.redoall_image,
borderwidth=1, command=self._on_redo_all)
self.redoall.grid(in_=self.toolbar, row=0, column=10, sticky=W)
self.bold_tooltip = ToolTip(self.bold, 'Bold')
self.italic_tooltip = ToolTip(self.italic, 'Italic')
self.bullets_tooltip = ToolTip(self.bullets, 'Bullet list')
self.numbers_tooltip = ToolTip(self.numbers, 'Numbered list')
self.addlink_tooltip = ToolTip(self.addLink, 'Add hyperlink')
self.remlink_tooltip = ToolTip(self.remLink, 'Remove hyperlink')
self.undoall_tooltip = ToolTip(self.undoall, 'First move')
self.undo_tooltip = ToolTip(self.undo, 'Back one move')
self.redo_tooltip = ToolTip(self.redo, 'Forward one move')
self.redoall_tooltip = ToolTip(self.redoall, 'Last move')
def reset_view(self, model):
self._model = model
self.txt.delete('1.0', END)
sq = self._model.curr_state.valid_squares
self.canvas.delete(self.dark_color)
self.canvas.delete(self.light_color)
starting_squares = [i for i in sq if (self._model.curr_state.squares[i]
& (BLACK | WHITE))]
self._draw_checkers(Command(add=starting_squares))
for i in sq:
self.highlight_square(i, DARK_SQUARES)
def calc_board_loc(self, x, y):
vx, vy = self.calc_valid_xy(x, y)
xi = int(vx / self._square_size)
yi = int(vy / self._square_size)
return xi, yi
def calc_board_pos(self, xi, yi):
return self._boardpos.get(xi + yi * 8, 0)
def calc_grid_pos(self, pos):
return self._gridpos[pos]
def highlight_square(self, idx, color):
row, col = self._gridpos[idx]
hpos = col + row * 8
self.canvas.itemconfigure('o'+str(hpos), outline=color)
def calc_valid_xy(self, x, y):
return (min(max(0, self.canvas.canvasx(x)), self._board_side-1),
min(max(0, self.canvas.canvasy(y)), self._board_side-1))
def notify(self, move):
add_lst = []
rem_lst = []
for idx, _, newval in move.affected_squares:
if newval & FREE:
rem_lst.append(idx)
else:
add_lst.append(idx)
cmd = Command(add=add_lst, remove=rem_lst)
self._draw_checkers(cmd)
self.txt.delete('1.0', END)
self.serializer.restore(move.annotation)
self.curr_annotation = move.annotation
if self.txt.get('1.0','end').strip() == '':
start = keymap[move.affected_squares[FIRST][0]]
dest = keymap[move.affected_squares[LAST][0]]
movestr = '%d-%d' % (start, dest)
self.txt.insert('1.0', movestr)
def get_annotation(self):
return self.serializer.dump()
def erase_checker(self, index):
self.canvas.delete('c'+str(index))
def flip_board(self, flip):
self._delete_labels()
self.canvas.delete(self.dark_color)
self.canvas.delete(self.light_color)
if self.flip_view != flip:
self.flip_view = flip
self._gridpos = reverse_dict(self._gridpos)
self._boardpos = reverse_dict(self._boardpos)
self._label_board()
starting_squares = [i for i in self._model.curr_state.valid_squares
if self._model.curr_state.squares[i] &
(BLACK | WHITE)]
all_checkers = Command(add=starting_squares)
self._draw_checkers(all_checkers)
def update_statusbar(self, output=None):
if output:
self._statusbar['text'] = output
self.root.update()
return
if self._model.terminal_test():
text = "Game over. "
if self._model.curr_state.to_move == WHITE:
text += "Black won."
else:
text += "White won."
self._statusbar['text'] = text
return
if self._model.curr_state.to_move == WHITE:
self._statusbar['text'] = "White to move"
else:
self._statusbar['text'] = "Black to move"
def get_positions(self, type):
return map(str, sorted((keymap[i]
for i in self._model.curr_state.valid_squares
if self._model.curr_state.squares[i] == type)))
# private functions
def _setup_board(self, root):
for r in range(0, 8, 2):
row = r * self._square_size
for c in range(0, 8, 2):
col = c * self._square_size
self.canvas.create_rectangle(col, row, col+self._square_size-1,
row+self._square_size-1,
fill=LIGHT_SQUARES,
outline=LIGHT_SQUARES)
for c in range(1, 8, 2):
col = c * self._square_size
self.canvas.create_rectangle(col, row+self._square_size,
col+self._square_size-1,
row+self._square_size*2-1,
fill=LIGHT_SQUARES,
outline=LIGHT_SQUARES)
for r in range(0, 8, 2):
row = r * self._square_size
for c in range(1, 8, 2):
col = c * self._square_size
self.canvas.create_rectangle(col, row, col+self._square_size-1,
row+self._square_size-1,
fill=DARK_SQUARES,
outline=DARK_SQUARES,
tags='o'+str(r*8+c))
for c in range(0, 8, 2):
col = c * self._square_size
self.canvas.create_rectangle(col, row+self._square_size,
col+self._square_size-1,
row+self._square_size*2-1,
fill=DARK_SQUARES,
outline=DARK_SQUARES,
tags='o'+str(((r+1)*8)+c))
def _label_board(self):
for key, pair in self._gridpos.iteritems():
row, col = pair
xpos, ypos = col * self._square_size, row * self._square_size
self.canvas.create_text(xpos+self._square_size-7,
ypos+self._square_size-7,
text=str(keymap[key]),
fill=LIGHT_SQUARES, tag='label')
def _delete_labels(self):
self.canvas.delete('label')
def _draw_checkers(self, change):
if change == None:
return
for i in change.remove:
self.canvas.delete('c'+str(i))
for i in change.add:
checker = self._model.curr_state.squares[i]
color = self.dark_color if checker & COLORS == BLACK else self.light_color
row, col = self._gridpos[i]
x = col * self._square_size + self._piece_offset
y = row * self._square_size + self._piece_offset
tag = 'c'+str(i)
self.canvas.create_oval(x+2, y+2, x+2+CHECKER_SIZE,
y+2+CHECKER_SIZE, outline='black',
fill='black', tags=(color, tag))
self.canvas.create_oval(x, y, x+CHECKER_SIZE, y+CHECKER_SIZE,
outline='black', fill=color,
tags=(color, tag))
if checker & KING:
self.canvas.create_image(x+15, y+15, image=self._crownpic,
anchor=CENTER, tags=(color, tag))
| Python |
from UserDict import UserDict
class TranspositionTable (UserDict):
def __init__ (self, maxSize):
UserDict.__init__(self)
assert maxSize > 0
self.maxSize = maxSize
self.krono = []
self.maxdepth = 0
self.killer1 = [-1]*20
self.killer2 = [-1]*20
self.hashmove = [-1]*20
def __setitem__ (self, key, item):
if not key in self:
if len(self) >= self.maxSize:
try:
del self[self.krono[0]]
except KeyError:
pass # Overwritten
del self.krono[0]
self.data[key] = item
self.krono.append(key)
def probe (self, hash, depth, alpha, beta):
if not hash in self:
return
move, score, hashf, ply = self[hash]
if ply < depth:
return
if hashf == hashfEXACT:
return move, score, hashf
if hashf == hashfALPHA and score <= alpha:
return move, alpha, hashf
if hashf == hashfBETA and score >= beta:
return move, beta, hashf
def record (self, hash, move, score, hashf, ply):
self[hash] = (move, score, hashf, ply)
def add_killer (self, ply, move):
if self.killer1[ply] == -1:
self.killer1[ply] = move
elif move != self.killer1[ply]:
self.killer2[ply] = move
def is_killer (self, ply, move):
if self.killer1[ply] == move:
return 10
elif self.killer2[ply] == move:
return 8
if ply >= 2:
if self.killer1[ply-2] == move:
return 6
elif self.killer2[ply-2] == move:
return 4
return 0
def set_hash_move (self, ply, move):
self.hashmove[ply] = move
def is_hash_move (self, ply, move):
return self.hashmove[ply] == move
| Python |
import re
import sys
class LinkRules(object):
"""Rules for recognizing external links."""
# For the link targets:
proto = r'http|https|ftp|nntp|news|mailto|telnet|file|irc'
extern = r'(?P<extern_addr>(?P<extern_proto>%s):.*)' % proto
interwiki = r'''
(?P<inter_wiki> [A-Z][a-zA-Z]+ ) :
(?P<inter_page> .* )
'''
def __init__(self):
self.addr_re = re.compile('|'.join([
self.extern,
self.interwiki,
]), re.X | re.U) # for addresses
class Rules(object):
"""Hold all the rules for generating regular expressions."""
# For the inline elements:
proto = r'http|https|ftp|nntp|news|mailto|telnet|file|irc'
link = r'''(?P<link>
\[\[
(?P<link_target>.+?) \s*
([|] \s* (?P<link_text>.+?) \s*)?
]]
)'''
image = r'''(?P<image>
{{
(?P<image_target>.+?) \s*
([|] \s* (?P<image_text>.+?) \s*)?
}}
)'''
macro = r'''(?P<macro>
<<
(?P<macro_name> \w+)
(\( (?P<macro_args> .*?) \))? \s*
([|] \s* (?P<macro_text> .+?) \s* )?
>>
)'''
code = r'(?P<code> {{{ (?P<code_text>.*?) }}} )'
emph = r'(?P<emph> (?<!:)// )' # there must be no : in front of the //
# avoids italic rendering in urls with
# unknown protocols
strong = r'(?P<strong> \*\* )'
linebreak = r'(?P<break> \\\\ )'
escape = r'(?P<escape> ~ (?P<escaped_char>\S) )'
char = r'(?P<char> . )'
# For the block elements:
separator = r'(?P<separator> ^ \s* ---- \s* $ )' # horizontal line
line = r'(?P<line> ^ \s* $ )' # empty line that separates paragraphs
head = r'''(?P<head>
^ \s*
(?P<head_head>=+) \s*
(?P<head_text> .*? ) \s*
(?P<head_tail>=*) \s*
$
)'''
text = r'(?P<text> .+ )'
list = r'''(?P<list>
^ [ \t]* ([*][^*\#]|[\#][^\#*]).* $
( \n[ \t]* [*\#]+.* $ )*
)''' # Matches the whole list, separate items are parsed later. The
# list *must* start with a single bullet.
item = r'''(?P<item>
^ \s*
(?P<item_head> [\#*]+) \s*
(?P<item_text> .*?)
$
)''' # Matches single list items
pre = r'''(?P<pre>
^{{{ \s* $
(\n)?
(?P<pre_text>
([\#]!(?P<pre_kind>\w*?)(\s+.*)?$)?
(.|\n)+?
)
(\n)?
^}}} \s*$
)'''
pre_escape = r' ^(?P<indent>\s*) ~ (?P<rest> \}\}\} \s*) $'
table = r'''(?P<table>
^ \s*
[|].*? \s*
[|]? \s*
$
)'''
# For splitting table cells:
cell = r'''
\| \s*
(
(?P<head> [=][^|]+ ) |
(?P<cell> ( %s | [^|])+ )
) \s*
''' % '|'.join([link, macro, image, code])
def __init__(self, bloglike_lines=False, url_protocols=None,
wiki_words=False):
c = re.compile
# For pre escaping, in creole 1.0 done with ~:
self.pre_escape_re = c(self.pre_escape, re.M | re.X)
# for link descriptions
self.link_re = c('|'.join([self.image, self.linebreak,
self.char]), re.X | re.U)
# for list items
self.item_re = c(self.item, re.X | re.U | re.M)
# for table cells
self.cell_re = c(self.cell, re.X | re.U)
# For block elements:
if bloglike_lines:
self.text = r'(?P<text> .+ ) (?P<break> (?<!\\)$\n(?!\s*$) )?'
self.block_re = c('|'.join([self.line, self.head, self.separator,
self.pre, self.list, self.table,
self.text]), re.X | re.U | re.M)
# For inline elements:
if url_protocols is not None:
self.proto = '|'.join(re.escape(p) for p in url_protocols)
self.url = r'''(?P<url>
(^ | (?<=\s | [.,:;!?()/=]))
(?P<escaped_url>~)?
(?P<url_target> (?P<url_proto> %s ):\S+? )
($ | (?=\s | [,.:;!?()] (\s | $))))''' % self.proto
inline_elements = [self.link, self.url, self.macro,
self.code, self.image, self.strong,
self.emph, self.linebreak,
self.escape, self.char]
if wiki_words:
import unicodedata
up_case = u''.join(unichr(i) for i in xrange(sys.maxunicode)
if unicodedata.category(unichr(i))=='Lu')
self.wiki = ur'''(?P<wiki>[%s]\w+[%s]\w+)''' % (up_case, up_case)
inline_elements.insert(3, self.wiki)
self.inline_re = c('|'.join(inline_elements), re.X | re.U)
| Python |
from Tkinter import *
from time import time, localtime, strftime
class ToolTip( Toplevel ):
"""
Provides a ToolTip widget for Tkinter.
To apply a ToolTip to any Tkinter widget, simply pass the widget to the
ToolTip constructor
"""
def __init__( self, wdgt, msg=None, msgFunc=None, delay=1, follow=True ):
"""
Initialize the ToolTip
Arguments:
wdgt: The widget this ToolTip is assigned to
msg: A static string message assigned to the ToolTip
msgFunc: A function that retrieves a string to use as the ToolTip text
delay: The delay in seconds before the ToolTip appears(may be float)
follow: If True, the ToolTip follows motion, otherwise hides
"""
self.wdgt = wdgt
self.parent = self.wdgt.master # The parent of the ToolTip is the parent of the ToolTips widget
Toplevel.__init__( self, self.parent, bg='black', padx=1, pady=1 ) # Initalise the Toplevel
self.withdraw() # Hide initially
self.overrideredirect( True ) # The ToolTip Toplevel should have no frame or title bar
self.msgVar = StringVar() # The msgVar will contain the text displayed by the ToolTip
if msg == None:
self.msgVar.set( 'No message provided' )
else:
self.msgVar.set( msg )
self.msgFunc = msgFunc
self.delay = delay
self.follow = follow
self.visible = 0
self.lastMotion = 0
Message( self, textvariable=self.msgVar, bg='#FFFFDD',
aspect=1000 ).grid() # The test of the ToolTip is displayed in a Message widget
self.wdgt.bind( '<Enter>', self.spawn, '+' ) # Add bindings to the widget. This will NOT override bindings that the widget already has
self.wdgt.bind( '<Leave>', self.hide, '+' )
self.wdgt.bind( '<Motion>', self.move, '+' )
def spawn( self, event=None ):
"""
Spawn the ToolTip. This simply makes the ToolTip eligible for display.
Usually this is caused by entering the widget
Arguments:
event: The event that called this funciton
"""
self.visible = 1
self.after( int( self.delay * 1000 ), self.show ) # The after function takes a time argument in miliseconds
def show( self ):
"""
Displays the ToolTip if the time delay has been long enough
"""
if self.visible == 1 and time() - self.lastMotion > self.delay:
self.visible = 2
if self.visible == 2:
self.deiconify()
def move( self, event ):
"""
Processes motion within the widget.
Arguments:
event: The event that called this function
"""
self.lastMotion = time()
if self.follow == False: # If the follow flag is not set, motion within the widget will make the ToolTip dissapear
self.withdraw()
self.visible = 1
self.geometry( '+%i+%i' % ( event.x_root+10, event.y_root+10 ) ) # Offset the ToolTip 10x10 pixes southwest of the pointer
try:
self.msgVar.set( self.msgFunc() ) # Try to call the message function. Will not change the message if the message function is None or the message function fails
except:
pass
self.after( int( self.delay * 1000 ), self.show )
def hide( self, event=None ):
"""
Hides the ToolTip. Usually this is caused by leaving the widget
Arguments:
event: The event that called this function
"""
self.visible = 0
self.withdraw()
def xrange2d( n,m ):
"""
Returns a generator of values in a 2d range
Arguments:
n: The number of rows in the 2d range
m: The number of columns in the 2d range
Returns:
A generator of values in a 2d range
"""
return ( (i,j) for i in xrange(n) for j in xrange(m) )
def range2d( n,m ):
"""
Returns a list of values in a 2d range
Arguments:
n: The number of rows in the 2d range
m: The number of columns in the 2d range
Returns:
A list of values in a 2d range
"""
return [(i,j) for i in range(n) for j in range(m) ]
def print_time():
"""
Prints the current time in the following format:
HH:MM:SS.00
"""
t = time()
timeString = 'time='
timeString += strftime( '%H:%M:', localtime(t) )
timeString += '%.2f' % ( t%60, )
return timeString
def main():
root = Tk()
btnList = []
for (i,j) in range2d( 6, 4 ):
text = 'delay=%i\n' % i
delay = i
if j >= 2:
follow=True
text += '+follow\n'
else:
follow = False
text += '-follow\n'
if j % 2 == 0:
msg = None
msgFunc = print_time
text += 'Message Function'
else:
msg = 'Button at %s' % str( (i,j) )
msgFunc = None
text += 'Static Message'
btnList.append( Button( root, text=text ) )
ToolTip( btnList[-1], msg=msg, msgFunc=msgFunc, follow=follow, delay=delay)
btnList[-1].grid( row=i, column=j, sticky=N+S+E+W )
root.mainloop()
if __name__ == '__main__':
main()
| Python |
from Tkinter import *
class HyperlinkManager(object):
def __init__(self, textWidget, linkFunc):
self.txt = textWidget
self.linkfunc = linkFunc
self.txt.tag_config('hyper', foreground='blue', underline=1)
self.txt.tag_bind('hyper', '<Enter>', self._enter)
self.txt.tag_bind('hyper', '<Leave>', self._leave)
self.txt.tag_bind('hyper', '<Button-1>', self._click)
self.reset()
def reset(self):
self.filenames = {}
def add(self, filename):
# Add a link with associated filename. The link function returns tags
# to use in the associated text widget.
tag = 'hyper-%d' % len(self.filenames)
self.filenames[tag] = filename
return 'hyper', tag
def _enter(self, event):
self.txt.config(cursor='hand2')
def _leave(self, event):
self.txt.config(cursor='')
def _click(self, event):
for tag in self.txt.tag_names(CURRENT):
if tag.startswith('hyper-'):
self.linkfunc(self.filenames[tag])
return
| Python |
import re
import sys
from rules import Rules
from document import DocNode
class Parser(object):
"""
Parse the raw text and create a document object
that can be converted into output using Emitter.
A separate instance should be created for parsing a new document.
The first parameter is the raw text to be parsed. An optional second
argument is the Rules object to use. You can customize the parsing
rules to enable optional features or extend the parser.
"""
def __init__(self, raw, rules=None):
self.rules = rules or Rules()
self.raw = raw
self.root = DocNode('document', None)
self.cur = self.root # The most recent document node
self.text = None # The node to add inline characters to
def _upto(self, node, kinds):
"""
Look up the tree to the first occurence
of one of the listed kinds of nodes or root.
Start at the node node.
"""
while node.parent is not None and not node.kind in kinds:
node = node.parent
return node
# The _*_repl methods called for matches in regexps. Sometimes the
# same method needs several names, because of group names in regexps.
def _url_repl(self, groups):
"""Handle raw urls in text."""
if not groups.get('escaped_url'):
# this url is NOT escaped
target = groups.get('url_target', '')
node = DocNode('link', self.cur)
node.content = target
DocNode('text', node, node.content)
self.text = None
else:
# this url is escaped, we render it as text
if self.text is None:
self.text = DocNode('text', self.cur, u'')
self.text.content += groups.get('url_target')
def _link_repl(self, groups):
"""Handle all kinds of links."""
target = groups.get('link_target', '')
text = (groups.get('link_text', '') or '').strip()
parent = self.cur
self.cur = DocNode('link', self.cur)
self.cur.content = target
self.text = None
self.parse_re(text, self.rules.link_re)
self.cur = parent
self.text = None
def _wiki_repl(self, groups):
"""Handle WikiWord links, if enabled."""
text = groups.get('wiki', '')
node = DocNode('link', self.cur)
node.content = text
DocNode('text', node, node.content)
self.text = None
def _macro_repl(self, groups):
"""Handles macros using the placeholder syntax."""
name = groups.get('macro_name', '')
text = (groups.get('macro_text', '') or '').strip()
node = DocNode('macro', self.cur, name)
node.args = groups.get('macro_args', '') or ''
DocNode('text', node, text or name)
self.text = None
def _image_repl(self, groups):
"""Handles images and attachemnts included in the page."""
target = groups.get('image_target', '').strip()
text = (groups.get('image_text', '') or '').strip()
node = DocNode("image", self.cur, target)
DocNode('text', node, text or node.content)
self.text = None
def _separator_repl(self, groups):
self.cur = self._upto(self.cur, ('document', 'section', 'blockquote'))
DocNode('separator', self.cur)
def _item_repl(self, groups):
bullet = groups.get('item_head', u'')
text = groups.get('item_text', u'')
if bullet[-1] == '#':
kind = 'number_list'
else:
kind = 'bullet_list'
level = len(bullet)
lst = self.cur
# Find a list of the same kind and level up the tree
while (lst and
not (lst.kind in ('number_list', 'bullet_list') and
lst.level == level) and
not lst.kind in ('document', 'section', 'blockquote')):
lst = lst.parent
if lst and lst.kind == kind:
self.cur = lst
else:
# Create a new level of list
self.cur = self._upto(self.cur,
('list_item', 'document', 'section', 'blockquote'))
self.cur = DocNode(kind, self.cur)
self.cur.level = level
self.cur = DocNode('list_item', self.cur)
self.parse_inline(text)
self.text = None
def _list_repl(self, groups):
text = groups.get('list', u'')
self.parse_re(text, self.rules.item_re)
def _head_repl(self, groups):
self.cur = self._upto(self.cur, ('document', 'section', 'blockquote'))
node = DocNode('header', self.cur, groups.get('head_text', '').strip())
node.level = len(groups.get('head_head', ' '))
def _text_repl(self, groups):
text = groups.get('text', '')
if self.cur.kind in ('table', 'table_row', 'bullet_list',
'number_list'):
self.cur = self._upto(self.cur,
('document', 'section', 'blockquote'))
if self.cur.kind in ('document', 'section', 'blockquote'):
self.cur = DocNode('paragraph', self.cur)
else:
text = u' ' + text
self.parse_inline(text)
if groups.get('break') and self.cur.kind in ('paragraph',
'emphasis', 'strong', 'code'):
DocNode('break', self.cur, '')
self.text = None
_break_repl = _text_repl
def _table_repl(self, groups):
row = groups.get('table', '|').strip()
self.cur = self._upto(self.cur, (
'table', 'document', 'section', 'blockquote'))
if self.cur.kind != 'table':
self.cur = DocNode('table', self.cur)
tb = self.cur
tr = DocNode('table_row', tb)
text = ''
for m in self.rules.cell_re.finditer(row):
cell = m.group('cell')
if cell:
self.cur = DocNode('table_cell', tr)
self.text = None
self.parse_inline(cell)
else:
cell = m.group('head')
self.cur = DocNode('table_head', tr)
self.text = DocNode('text', self.cur, u'')
self.text.content = cell.strip('=')
self.cur = tb
self.text = None
def _pre_repl(self, groups):
self.cur = self._upto(self.cur, ('document', 'section', 'blockquote'))
kind = groups.get('pre_kind', None)
text = groups.get('pre_text', u'')
def remove_tilde(m):
return m.group('indent') + m.group('rest')
text = self.rules.pre_escape_re.sub(remove_tilde, text)
node = DocNode('preformatted', self.cur, text)
node.sect = kind or ''
self.text = None
def _line_repl(self, groups):
self.cur = self._upto(self.cur, ('document', 'section', 'blockquote'))
def _code_repl(self, groups):
DocNode('code', self.cur, groups.get('code_text', u'').strip())
self.text = None
def _emph_repl(self, groups):
if self.cur.kind != 'emphasis':
self.cur = DocNode('emphasis', self.cur)
else:
self.cur = self._upto(self.cur, ('emphasis', )).parent
self.text = None
def _strong_repl(self, groups):
if self.cur.kind != 'strong':
self.cur = DocNode('strong', self.cur)
else:
self.cur = self._upto(self.cur, ('strong', )).parent
self.text = None
def _break_repl(self, groups):
DocNode('break', self.cur, None)
self.text = None
def _escape_repl(self, groups):
if self.text is None:
self.text = DocNode('text', self.cur, u'')
self.text.content += groups.get('escaped_char', u'')
def _char_repl(self, groups):
if self.text is None:
self.text = DocNode('text', self.cur, u'')
self.text.content += groups.get('char', u'')
def parse_inline(self, raw):
"""Recognize inline elements inside blocks."""
self.parse_re(raw, self.rules.inline_re)
def parse_re(self, raw, rules_re):
"""Parse a fragment according to the compiled rules."""
for match in rules_re.finditer(raw):
groups = dict((k, v) for (k, v)
in match.groupdict().iteritems()
if v is not None)
name = match.lastgroup
function = getattr(self, '_%s_repl' % name)
function(groups)
def parse(self):
"""Parse the text given as self.raw and return DOM tree."""
self.parse_re(self.raw, self.rules.block_re)
return self.root
| Python |
from Tkinter import *
from tkSimpleDialog import Dialog
from globalconst import *
class AboutBox(Dialog):
def body(self, master):
self.canvas = Canvas(self, width=300, height=275)
self.canvas.pack(side=TOP, fill=BOTH, expand=0)
self.canvas.create_text(152,47,text='Raven', fill='black',
font=('Helvetica', 36))
self.canvas.create_text(150,45,text='Raven', fill='white',
font=('Helvetica', 36))
self.canvas.create_text(150,85,text='Version '+ VERSION,
fill='black',
font=('Helvetica', 12))
self.canvas.create_text(150,115,text='An open source checkers program',
fill='black',
font=('Helvetica', 10))
self.canvas.create_text(150,130,text='by Brandon Corfman',
fill='black',
font=('Helvetica', 10))
self.canvas.create_text(150,160,text='Evaluation function translated from',
fill='black',
font=('Helvetica', 10))
self.canvas.create_text(150,175,text="Martin Fierz's Simple Checkers",
fill='black',
font=('Helvetica', 10))
self.canvas.create_text(150,205,text="Alpha-beta search code written by",
fill='black',
font=('Helvetica', 10))
self.canvas.create_text(150,220,text="Peter Norvig for the AIMA project;",
fill='black',
font=('Helvetica', 10))
self.canvas.create_text(150,235,text="adopted for checkers usage",
fill='black',
font=('Helvetica', 10))
self.canvas.create_text(150,250,text="by Brandon Corfman",
fill='black',
font=('Helvetica', 10))
return self.canvas
def cancel(self, event=None):
self.destroy()
def buttonbox(self):
self.button = Button(self, text='OK', padx='5m', command=self.cancel)
self.blank = Canvas(self, width=10, height=20)
self.blank.pack(side=BOTTOM, fill=BOTH, expand=0)
self.button.pack(side=BOTTOM)
self.button.focus_set()
self.bind("<Escape>", self.cancel)
| Python |
from globalconst import BLACK, WHITE, KING
import checkers
class Operator(object):
pass
class OneKingAttackOneKing(Operator):
def precondition(self, board):
plr_color = board.to_move
opp_color = board.enemy
return (board.count(plr_color) == 1 and board.count(opp_color) == 1 and
any((x & KING for x in board.get_pieces(opp_color))) and
any((x & KING for x in board.get_pieces(plr_color))) and
board.has_opposition(plr_color))
def postcondition(self, board):
board.make_move()
class PinEnemyKingInCornerWithPlayerKing(Operator):
def __init__(self):
self.pidx = 0
self.eidx = 0
self.goal = 8
def precondition(self, state):
self.pidx, plr = self.plr_lst[0] # only 1 piece per side
self.eidx, enemy = self.enemy_lst[0]
delta = abs(self.pidx - self.eidx)
return ((self.player_total == 1) and (self.enemy_total == 1) and
(plr & KING > 0) and (enemy & KING > 0) and
not (8 <= delta <= 10) and state.have_opposition(plr))
def postcondition(self, state):
new_state = None
old_delta = abs(self.eidx - self.pidx)
goal_delta = abs(self.goal - old_delta)
for move in state.moves:
for m in move:
newidx, _, _ = m[1]
new_delta = abs(self.eidx - newidx)
if abs(goal - new_delta) < goal_delta:
new_state = state.make_move(move)
break
return new_state
# (white)
# 37 38 39 40
# 32 33 34 35
# 28 29 30 31
# 23 24 25 26
# 19 20 21 22
# 14 15 16 17
# 10 11 12 13
# 5 6 7 8
# (black)
class SingleKingFleeToDoubleCorner(Operator):
def __init__(self):
self.pidx = 0
self.eidx = 0
self.dest = [8, 13, 27, 32]
self.goal_delta = 0
def precondition(self, state):
# fail fast
if self.player_total == 1 and self.enemy_total == 1:
return False
self.pidx, _ = self.plr_lst[0]
self.eidx, _ = self.enemy_lst[0]
for sq in self.dest:
if abs(self.pidx - sq) < abs(self.eidx - sq):
self.goal = sq
return True
return False
def postcondition(self, state):
self.goal_delta = abs(self.goal - self.pidx)
for move in state.moves:
for m in move:
newidx, _, _ = m[1]
new_delta = abs(self.goal - newidx)
if new_delta < self.goal_delta:
new_state = state.make_move(move)
break
return new_state
class FormShortDyke(Operator):
def precondition(self):
pass
| Python |
import copy, textwrap
from globalconst import *
from move import Move
from checkers import Checkers
class SavedGame(object):
def __init__(self):
self._model = Checkers()
self.to_move = None
self.moves = []
self.description = ''
self.black_men = []
self.white_men = []
self.black_kings = []
self.white_kings = []
self.flip_board = False
self.num_players = 1
self._move_check = False
self._bm_check = False
self._bk_check = False
self._wm_check = False
self._wk_check = False
def _write_positions(self, f, prefix, positions):
f.write(prefix + ' ')
for p in sorted(positions):
f.write('%d ' % p)
f.write('\n')
def _write_moves(self, f):
f.write('<moves>\n')
for move in reversed(self.moves):
start = keymap[move.affected_squares[FIRST][0]]
dest = keymap[move.affected_squares[LAST][0]]
movestr = '%d-%d' % (start, dest)
annotation = move.annotation
if annotation.startswith(movestr):
annotation = annotation.replace(movestr, '', 1).rstrip()
f.write('%s;%s\n' % (movestr, annotation))
def write(self, filename):
with open(filename, 'w') as f:
f.write('<description>\n')
for line in self.description.splitlines():
# numbered lists or hyperlinks are not word wrapped.
if line.startswith('# ') or '[[' in line:
f.write(line + '\n')
continue
else:
f.write(textwrap.fill(line, 80) + '\n')
f.write('<setup>\n')
if self.to_move == WHITE:
f.write('white_first\n')
elif self.to_move == BLACK:
f.write('black_first\n')
else:
raise ValueError, "Unknown value for to_move variable"
if self.num_players >=0 and self.num_players <=2:
f.write('%d_player_game\n' % self.num_players)
else:
raise ValueError, "Unknown value for num_players variable"
if self.flip_board:
f.write('flip_board 1\n')
else:
f.write('flip_board 0\n')
self._write_positions(f, 'black_men', self.black_men)
self._write_positions(f, 'black_kings', self.black_kings)
self._write_positions(f, 'white_men', self.white_men)
self._write_positions(f, 'white_kings', self.white_kings)
self._write_moves(f)
def read(self, filename):
with open(filename, 'r') as f:
lines = f.readlines()
linelen = len(lines)
i = 0
while True:
if i >= linelen:
break
line = lines[i].strip()
if line.startswith('<description>'):
self.description = ''
i += 1
while i < linelen and not lines[i].startswith('<setup>'):
self.description += lines[i]
i += 1
elif line.startswith('<setup>'):
i = self._parse_setup(lines, i, linelen)
elif line.startswith('<moves>'):
i = self._parse_moves(lines, i, linelen)
else:
raise IOError, 'Unrecognized section in file, line %d' % (i+1)
def _parse_items(self, line):
men = line.split()[1:]
return map(int, men)
def _add_men_to_board(self, locations, val):
squares = self._model.curr_state.squares
try:
for loc in locations:
idx = squaremap[loc]
squares[idx] = val
except ValueError:
raise IOError, 'Checker location not valid, line %d' % (i+1)
def _parse_setup(self, lines, idx, linelen):
curr_state = self._model.curr_state
curr_state.clear()
idx += 1
while idx < linelen and '<moves>' not in lines[idx]:
line = lines[idx].strip().lower()
if line == 'white_first':
self.to_move = curr_state.to_move = WHITE
self._move_check = True
elif line == 'black_first':
self.to_move = curr_state.to_move = BLACK
self._move_check = True
elif line.endswith('player_game'):
numstr, _ = line.split('_', 1)
self.num_players = int(numstr)
elif line.startswith('flip_board'):
_, setting = line.split()
val = int(setting)
self.flip_board = True if val else False
elif line.startswith('black_men'):
self.black_men = self._parse_items(line)
self._add_men_to_board(self.black_men, BLACK | MAN)
self._bm_check = True
elif line.startswith('white_men'):
self.white_men = self._parse_items(line)
self._add_men_to_board(self.white_men, WHITE | MAN)
self._wm_check = True
elif line.startswith('black_kings'):
self.black_kings = self._parse_items(line)
self._add_men_to_board(self.black_kings, BLACK | KING)
self._bk_check = True
elif line.startswith('white_kings'):
self.white_kings = self._parse_items(line)
self._add_men_to_board(self.white_kings, WHITE | KING)
self._wk_check = True
idx += 1
if (not self._move_check and not self._bm_check and not self._wm_check
and not self._bk_check and not self._wk_check):
raise IOError, 'Error in <setup> section: not all required items found'
return idx
def _is_move(self, delta):
return delta in KING_IDX
def _is_jump(self, delta):
return delta not in KING_IDX
def _try_move(self, idx, start, dest, state_copy, annotation):
legal_moves = self._model.legal_moves(state_copy)
# match move from file with available moves on checkerboard
found = False
startsq, destsq = squaremap[start], squaremap[dest]
for move in legal_moves:
if (startsq == move.affected_squares[FIRST][0] and
destsq == move.affected_squares[LAST][0]):
self._model.make_move(move, state_copy, False, False)
move.annotation = annotation
self.moves.append(move)
found = True
break
if not found:
raise IOError, 'Illegal move found in file, line %d' % (idx+1)
def _try_jump(self, idx, start, dest, state_copy, annotation):
if not self._model.captures_available(state_copy):
return False
legal_moves = self._model.legal_moves(state_copy)
# match jump from file with available jumps on checkerboard
startsq, destsq = squaremap[start], squaremap[dest]
small, large = min(startsq, destsq), max(startsq, destsq)
found = False
for move in legal_moves:
# a valid jump may either have a single jump in it, or
# multiple jumps. In the multiple jump case, startsq is the
# source of the first jump, and destsq is the endpoint of the
# last jump.
if (startsq == move.affected_squares[FIRST][0] and
destsq == move.affected_squares[LAST][0]):
self._model.make_move(move, state_copy, False, False)
move.annotation = annotation
self.moves.append(move)
found = True
break
return found
def _parse_moves(self, lines, idx, linelen):
""" Each move in the file lists the beginning and ending square, along
with an optional annotation string (in Creole format) that describes it.
Since the move listing in the file contains less information than
we need inside our Checkerboard model, I make sure that each move works
on a copy of the model before I commit to using it inside the code. """
state_copy = copy.deepcopy(self._model.curr_state)
idx += 1
while idx < linelen:
line = lines[idx].strip()
if line == "":
idx += 1
continue # ignore blank lines
try:
movestr, annotation = line.split(';', 1)
except ValueError:
raise IOError, 'Unrecognized section in file, line %d' % (idx+1)
# move is always part of the annotation; I just don't want to
# have to repeat it explicitly in the file.
annotation = movestr + annotation
# analyze affected squares to perform a move or jump.
try:
start, dest = [int(x) for x in movestr.split('-')]
except ValueError:
raise IOError, 'Bad move format in file, line %d' % idx
delta = squaremap[start] - squaremap[dest]
if self._is_move(delta):
self._try_move(idx, start, dest, state_copy, annotation)
else:
jumped = self._try_jump(idx, start, dest, state_copy,
annotation)
if not jumped:
raise IOError, 'Bad move format in file, line %d' % idx
idx += 1
self.moves.reverse()
return idx
| Python |
from abc import ABCMeta, abstractmethod
class GoalEvaluator(object):
__metaclass__ = ABCMeta
def __init__(self, bias):
self.bias = bias
@abstractmethod
def calculateDesirability(self, board):
pass
@abstractmethod
def setGoal(self, board):
pass
| Python |
import sys
import games
from globalconst import *
class Player(object):
def __init__(self, color):
self.col = color
def _get_color(self):
return self.col
color = property(_get_color, doc="Player color")
class AlphabetaPlayer(Player):
def __init__(self, color, depth=4):
Player.__init__(self, color)
self.searchDepth = depth
def select_move(self, game, state):
sys.stdout.write('\nThinking ... ')
movelist = games.alphabeta_search(state, game, False,
self.searchDepth)
positions = []
step = 2 if game.captures_available(state) else 1
for i in range(0, len(movelist), step):
idx, old, new = movelist[i]
positions.append(str(CBMAP[idx]))
move = '-'.join(positions)
print 'I move %s' % move
return movelist
class HumanPlayer(Player):
def __init__(self, color):
Player.__init__(self, color)
def select_move(self, game, state):
while 1:
moves = game.legal_moves(state)
positions = []
idx = 0
while 1:
reqstr = 'Move to? ' if positions else 'Move from? '
# do any positions match the input
pos = self._valid_pos(raw_input(reqstr), moves, idx)
if pos:
positions.append(pos)
# reduce moves to number matching the positions entered
moves = self._filter_moves(pos, moves, idx)
if game.captures_available(state):
idx += 2
else:
idx += 1
if len(moves) <= 1:
break
if len(moves) == 1:
return moves[0]
else:
print "Illegal move!"
def _valid_pos(self, pos, moves, idx):
t_pos = IMAP.get(pos.lower(), 0)
if t_pos == 0:
return None # move is illegal
for m in moves:
if idx < len(m) and m[idx][0] == t_pos:
return t_pos
return None
def _filter_moves(self, pos, moves, idx):
del_list = []
for i, m in enumerate(moves):
if pos != m[idx][0]:
del_list.append(i)
for i in reversed(del_list):
del moves[i]
return moves
| Python |
from Tkinter import *
class AutoScrollbar(Scrollbar):
def __init__(self, master=None, cnf={}, **kw):
self.container = kw.pop('container', None)
self.row = kw.pop('row', 0)
self.column = kw.pop('column', 0)
self.sticky = kw.pop('sticky', '')
Scrollbar.__init__(self, master, cnf, **kw)
# a scrollbar that hides itself if it's not needed. only
# works if you use the grid geometry manager.
def set(self, lo, hi):
if float(lo) <= 0.0 and float(hi) >= 1.0:
# grid_remove is currently missing from Tkinter!
self.tk.call('grid', 'remove', self)
else:
if not self.container:
self.grid()
else:
self.grid(in_=self.container, row=self.row,
column=self.column, sticky=self.sticky)
Scrollbar.set(self, lo, hi)
def pack(self, **kw):
raise TclError, 'cannot use pack with this widget'
def place(self, **kw):
raise TclError, 'cannot use place with this widget'
| Python |
import utils
class Observer(object):
def update(self, change):
utils.abstract()
| Python |
from Tkinter import *
from Tkconstants import W, E, N, S
from tkFileDialog import askopenfilename, asksaveasfilename
from tkMessageBox import askyesnocancel, showerror
from globalconst import *
from checkers import Checkers
from boardview import BoardView
from playercontroller import PlayerController
from alphabetacontroller import AlphaBetaController
from gamepersist import SavedGame
from textserialize import Serializer
class GameManager(object):
def __init__(self, **props):
self.model = Checkers()
self._root = props['root']
self.parent = props['parent']
statusbar = Label(self._root, relief=SUNKEN, font=('Helvetica',7),
anchor=NW)
statusbar.pack(side='bottom', fill='x')
self.view = BoardView(self._root, model=self.model, parent=self,
statusbar=statusbar)
self.player_color = BLACK
self.num_players = 1
self.set_controllers()
self._controller1.start_turn()
self.filename = None
def set_controllers(self):
think_time = self.parent.thinkTime.get()
if self.num_players == 0:
self._controller1 = AlphaBetaController(model=self.model,
view=self.view,
searchtime=think_time,
end_turn_event=self.turn_finished)
self._controller2 = AlphaBetaController(model=self.model,
view=self.view,
searchtime=think_time,
end_turn_event=self.turn_finished)
elif self.num_players == 1:
# assumption here is that Black is the player
self._controller1 = PlayerController(model=self.model,
view=self.view,
end_turn_event=self.turn_finished)
self._controller2 = AlphaBetaController(model=self.model,
view=self.view,
searchtime=think_time,
end_turn_event=self.turn_finished)
# swap controllers if White is selected as the player
if self.player_color == WHITE:
self._controller1, self._controller2 = self._controller2, self._controller1
elif self.num_players == 2:
self._controller1 = PlayerController(model=self.model,
view=self.view,
end_turn_event=self.turn_finished)
self._controller2 = PlayerController(model=self.model,
view=self.view,
end_turn_event=self.turn_finished)
self._controller1.set_before_turn_event(self._controller2.remove_highlights)
self._controller2.set_before_turn_event(self._controller1.remove_highlights)
def _stop_updates(self):
# stop alphabeta threads from making any moves
self.model.curr_state.ok_to_move = False
self._controller1.stop_process()
self._controller2.stop_process()
def _save_curr_game_if_needed(self):
if self.view.is_dirty():
msg = 'Do you want to save your changes'
if self.filename:
msg += ' to %s?' % self.filename
else:
msg += '?'
result = askyesnocancel(TITLE, msg)
if result == True:
self.save_game()
return result
else:
return False
def new_game(self):
self._stop_updates()
self._save_curr_game_if_needed()
self.filename = None
self._root.title('Raven ' + VERSION)
self.model = Checkers()
self.player_color = BLACK
self.view.reset_view(self.model)
self.think_time = self.parent.thinkTime.get()
self.set_controllers()
self.view.update_statusbar()
self.view.reset_toolbar_buttons()
self.view.curr_annotation = ''
self._controller1.start_turn()
def load_game(self, filename):
self._stop_updates()
try:
saved_game = SavedGame()
saved_game.read(filename)
self.model.curr_state.clear()
self.model.curr_state.to_move = saved_game.to_move
self.num_players = saved_game.num_players
squares = self.model.curr_state.squares
for i in saved_game.black_men:
squares[squaremap[i]] = BLACK | MAN
for i in saved_game.black_kings:
squares[squaremap[i]] = BLACK | KING
for i in saved_game.white_men:
squares[squaremap[i]] = WHITE | MAN
for i in saved_game.white_kings:
squares[squaremap[i]] = WHITE | KING
self.model.curr_state.reset_undo()
self.model.curr_state.redo_list = saved_game.moves
self.model.curr_state.update_piece_count()
self.view.reset_view(self.model)
self.view.serializer.restore(saved_game.description)
self.view.curr_annotation = self.view.get_annotation()
self.view.flip_board(saved_game.flip_board)
self.view.update_statusbar()
self.parent.set_title_bar_filename(filename)
self.filename = filename
except IOError as (err):
showerror(PROGRAM_TITLE, 'Invalid file. ' + str(err))
def open_game(self):
self._stop_updates()
self._save_curr_game_if_needed()
f = askopenfilename(filetypes=(('Raven Checkers files','*.rcf'),
('All files','*.*')),
initialdir=TRAINING_DIR)
if not f:
return
self.load_game(f)
def save_game_as(self):
self._stop_updates()
filename = asksaveasfilename(filetypes=(('Raven Checkers files','*.rcf'),
('All files','*.*')),
initialdir=TRAINING_DIR,
defaultextension='.rcf')
if filename == '':
return
self._write_file(filename)
def save_game(self):
self._stop_updates()
filename = self.filename
if not self.filename:
filename = asksaveasfilename(filetypes=(('Raven Checkers files','*.rcf'),
('All files','*.*')),
initialdir=TRAINING_DIR,
defaultextension='.rcf')
if filename == '':
return
self._write_file(filename)
def _write_file(self, filename):
try:
saved_game = SavedGame()
# undo moves back to the beginning of play
undo_steps = 0
while self.model.curr_state.undo_list:
undo_steps += 1
self.model.curr_state.undo_move(None, True, True,
self.view.get_annotation())
# save the state of the board
saved_game.to_move = self.model.curr_state.to_move
saved_game.num_players = self.num_players
saved_game.black_men = []
saved_game.black_kings = []
saved_game.white_men = []
saved_game.white_kings = []
for i, sq in enumerate(self.model.curr_state.squares):
if sq == BLACK | MAN:
saved_game.black_men.append(keymap[i])
elif sq == BLACK | KING:
saved_game.black_kings.append(keymap[i])
elif sq == WHITE | MAN:
saved_game.white_men.append(keymap[i])
elif sq == WHITE | KING:
saved_game.white_kings.append(keymap[i])
saved_game.description = self.view.serializer.dump()
saved_game.moves = self.model.curr_state.redo_list
saved_game.flip_board = self.view.flip_view
saved_game.write(filename)
# redo moves forward to the previous state
for i in range(undo_steps):
annotation = self.view.get_annotation()
self.model.curr_state.redo_move(None, annotation)
# record current filename in title bar
self.parent.set_title_bar_filename(filename)
self.filename = filename
except IOError:
showerror(PROGRAM_TITLE, 'Could not save file.')
def turn_finished(self):
if self.model.curr_state.to_move == BLACK:
self._controller2.end_turn() # end White's turn
self._root.update()
self.view.update_statusbar()
self._controller1.start_turn() # begin Black's turn
else:
self._controller1.end_turn() # end Black's turn
self._root.update()
self.view.update_statusbar()
self._controller2.start_turn() # begin White's turn
| Python |
import games
import copy
import multiprocessing
import time
import random
from controller import Controller
from transpositiontable import TranspositionTable
from globalconst import *
class AlphaBetaController(Controller):
def __init__(self, **props):
self._model = props['model']
self._view = props['view']
self._end_turn_event = props['end_turn_event']
self._highlights = []
self._search_time = props['searchtime'] # in seconds
self._before_turn_event = None
self._parent_conn, self._child_conn = multiprocessing.Pipe()
self._term_event = multiprocessing.Event()
self.process = multiprocessing.Process()
self._start_time = None
self._call_id = 0
self._trans_table = TranspositionTable(50000)
def set_before_turn_event(self, evt):
self._before_turn_event = evt
def add_highlights(self):
for h in self._highlights:
self._view.highlight_square(h, OUTLINE_COLOR)
def remove_highlights(self):
for h in self._highlights:
self._view.highlight_square(h, DARK_SQUARES)
def start_turn(self):
if self._model.terminal_test():
self._before_turn_event()
self._model.curr_state.attach(self._view)
return
self._view.update_statusbar('Thinking ...')
self.process = multiprocessing.Process(target=calc_move,
args=(self._model,
self._trans_table,
self._search_time,
self._term_event,
self._child_conn))
self._start_time = time.time()
self.process.daemon = True
self.process.start()
self._view.canvas.after(100, self.get_move)
def get_move(self):
#if self._term_event.is_set() and self._model.curr_state.ok_to_move:
# self._end_turn_event()
# return
self._highlights = []
moved = self._parent_conn.poll()
while (not moved and (time.time() - self._start_time)
< self._search_time * 2):
self._call_id = self._view.canvas.after(500, self.get_move)
return
self._view.canvas.after_cancel(self._call_id)
move = self._parent_conn.recv()
#if self._model.curr_state.ok_to_move:
self._before_turn_event()
# highlight remaining board squares used in move
step = 2 if len(move.affected_squares) > 2 else 1
for m in move.affected_squares[0::step]:
idx = m[0]
self._view.highlight_square(idx, OUTLINE_COLOR)
self._highlights.append(idx)
self._model.curr_state.attach(self._view)
self._model.make_move(move, None, True, True,
self._view.get_annotation())
# a new move obliterates any more redo's along a branch of the game tree
self._model.curr_state.delete_redo_list()
self._end_turn_event()
def set_search_time(self, time):
self._search_time = time # in seconds
def stop_process(self):
self._term_event.set()
self._view.canvas.after_cancel(self._call_id)
def end_turn(self):
self._view.update_statusbar()
self._model.curr_state.detach(self._view)
def longest_of(moves):
length = -1
selected = None
for move in moves:
l = len(move.affected_squares)
if l > length:
length = l
selected = move
return selected
def calc_move(model, table, search_time, term_event, child_conn):
move = None
term_event.clear()
captures = model.captures_available()
if captures:
time.sleep(0.7)
move = longest_of(captures)
else:
depth = 0
start_time = time.time()
curr_time = start_time
checkpoint = start_time
model_copy = copy.deepcopy(model)
while 1:
depth += 1
table.set_hash_move(depth, -1)
move = games.alphabeta_search(model_copy.curr_state,
model_copy,
depth)
checkpoint = curr_time
curr_time = time.time()
rem_time = search_time - (curr_time - checkpoint)
if term_event.is_set(): # a signal means terminate
term_event.clear()
move = None
break
if (curr_time - start_time > search_time or
((curr_time - checkpoint) * 2) > rem_time or
depth > MAXDEPTH):
break
child_conn.send(move)
#model.curr_state.ok_to_move = True
| Python |
import math, os, sys
from ConfigParser import RawConfigParser
DEFAULT_SIZE = 400
BOARD_SIZE = 8
CHECKER_SIZE = 30
MAX_VALID_SQ = 32
MOVE = 0
JUMP = 1
OCCUPIED = 0
BLACK = 1
WHITE = 2
MAN = 4
KING = 8
FREE = 16
COLORS = BLACK | WHITE
TYPES = OCCUPIED | BLACK | WHITE | MAN | KING | FREE
HUMAN = 0
COMPUTER = 1
MIN = 0
MAX = 1
IMAGE_DIR = 'images' + os.sep
RAVEN_ICON = IMAGE_DIR + '_raven.ico'
BULLET_IMAGE = IMAGE_DIR + 'bullet_green.gif'
CROWN_IMAGE = IMAGE_DIR + 'crown.gif'
BOLD_IMAGE = IMAGE_DIR + 'text_bold.gif'
ITALIC_IMAGE = IMAGE_DIR + 'text_italic.gif'
BULLETS_IMAGE = IMAGE_DIR + 'text_list_bullets.gif'
NUMBERS_IMAGE = IMAGE_DIR + 'text_list_numbers.gif'
ADDLINK_IMAGE = IMAGE_DIR + 'link.gif'
REMLINK_IMAGE = IMAGE_DIR + 'link_break.gif'
UNDO_IMAGE = IMAGE_DIR + 'resultset_previous.gif'
UNDOALL_IMAGE = IMAGE_DIR + 'resultset_first.gif'
REDO_IMAGE = IMAGE_DIR + 'resultset_next.gif'
REDOALL_IMAGE = IMAGE_DIR + 'resultset_last.gif'
LIGHT_SQUARES = 'tan'
DARK_SQUARES = 'dark green'
OUTLINE_COLOR = 'white'
LIGHT_CHECKERS = 'white'
DARK_CHECKERS = 'red'
WHITE_CHAR = 'w'
WHITE_KING = 'W'
BLACK_CHAR = 'b'
BLACK_KING = 'B'
FREE_CHAR = '.'
OCCUPIED_CHAR = '-'
INFINITY = 9999999
MAXDEPTH = 10
VERSION = '0.4'
TITLE = 'Raven ' + VERSION
PROGRAM_TITLE = 'Raven Checkers'
CUR_DIR = sys.path[0]
TRAINING_DIR = 'training'
# search values for transposition table
hashfALPHA, hashfBETA, hashfEXACT = range(3)
# constants for evaluation function
TURN = 2 # color to move gets + turn
BRV = 3 # multiplier for back rank
KCV = 5 # multiplier for kings in center
MCV = 1 # multiplier for men in center
MEV = 1 # multiplier for men on edge
KEV = 5 # multiplier for kings on edge
CRAMP = 5 # multiplier for cramp
OPENING = 2 # multipliers for tempo
MIDGAME = -1
ENDGAME = 2
INTACTDOUBLECORNER = 3
BLACK_IDX = [5,6]
WHITE_IDX = [-5,-6]
KING_IDX = [-6,-5,5,6]
FIRST = 0
MID = 1
LAST = -1
# (white)
# 45 46 47 48
# 39 40 41 42
# 34 35 36 37
# 28 29 30 31
# 23 24 25 26
# 17 18 19 20
# 12 13 14 15
# 6 7 8 9
# (black)
# other squares reachable from a particular square with a white man
WHITEMAP = {45: set([39,40,34,35,28,29,30,23,24,25,17,18,19,20,12,13,14,15,6,7,8,9]),
46: set([40,41,34,35,36,28,29,30,31,23,24,25,26,17,18,19,20,12,13,14,15,6,7,8,9]),
47: set([41,42,35,36,37,29,30,31,23,24,25,26,17,18,19,20,12,13,14,15,6,7,8,9]),
48: set([42,36,37,30,31,24,25,26,18,19,20,12,13,14,15,6,7,8,9]),
39: set([34,28,29,23,24,17,18,19,12,13,14,6,7,8,9]),
40: set([34,35,28,29,30,23,24,25,17,18,19,20,12,13,14,15,6,7,8,9]),
41: set([35,36,29,30,31,23,24,25,26,17,18,19,20,12,13,14,15,6,7,8,9]),
42: set([36,37,30,31,24,25,26,18,19,20,12,13,14,15,6,7,8,9]),
34: set([28,29,23,24,17,18,19,12,13,14,6,7,8,9]),
35: set([29,30,23,24,25,17,18,19,20,12,13,14,15,6,7,8,9]),
36: set([30,31,24,25,26,18,19,20,12,13,14,15,6,7,8,9]),
37: set([31,25,26,19,20,13,14,15,7,8,9]),
28: set([23,17,18,12,13,6,7,8]),
29: set([23,24,17,18,19,12,13,14,6,7,8,9]),
30: set([24,25,18,19,20,12,13,14,15,6,7,8,9]),
31: set([25,26,19,20,13,14,15,7,8,9]),
23: set([17,18,12,13,6,7,8]),
24: set([18,19,12,13,14,6,7,8,9]),
25: set([19,20,13,14,15,7,8,9]),
26: set([20,14,15,8,9]),
17: set([12,6,7]),
18: set([12,13,6,7,8]),
19: set([13,14,7,8,9]),
20: set([14,15,8,9]),
12: set([6,7]),
13: set([7,8]),
14: set([8,9]),
15: set([9]),
6: set(),
7: set(),
8: set(),
9: set()}
# (white)
# 45 46 47 48
# 39 40 41 42
# 34 35 36 37
# 28 29 30 31
# 23 24 25 26
# 17 18 19 20
# 12 13 14 15
# 6 7 8 9
# (black)
# other squares reachable from a particular square with a black man
BLACKMAP = {6: set([12,17,18,23,24,28,29,30,34,35,36,39,40,41,42,45,46,47,48]),
7: set([12,13,17,18,19,23,24,25,28,29,30,31,34,35,36,37,39,40,41,42,45,46,47,48]),
8: set([13,14,18,19,20,23,24,25,26,28,29,30,31,34,35,36,37,39,40,41,42,45,46,47,48]),
9: set([14,15,19,20,24,25,26,29,30,31,34,35,36,37,39,40,41,42,45,46,47,48]),
12: set([17,18,23,24,28,29,30,34,35,36,39,40,41,42,45,46,47,48]),
13: set([18,19,23,24,25,28,29,30,31,34,35,36,37,39,40,41,42,45,46,47,48]),
14: set([19,20,24,25,26,29,30,31,34,35,36,37,39,40,41,42,45,46,47,48]),
15: set([20,25,26,30,31,35,36,37,40,41,42,45,46,47,48]),
17: set([23,28,29,34,35,39,40,41,45,46,47]),
18: set([23,24,28,29,30,34,35,36,39,40,41,42,45,46,47,48]),
19: set([24,25,29,30,31,34,35,36,37,39,40,41,42,45,46,47,48]),
20: set([25,26,30,31,35,36,37,40,41,42,45,46,47,48]),
23: set([28,29,34,35,39,40,41,45,46,47]),
24: set([29,30,34,35,36,39,40,41,42,45,46,47,48]),
25: set([30,31,35,36,37,40,41,42,45,46,47,48]),
26: set([31,36,37,41,42,46,47,48]),
28: set([34,39,40,45,46]),
29: set([34,35,39,40,41,45,46,47]),
30: set([35,36,40,41,42,45,46,47,48]),
31: set([36,37,41,42,46,47,48]),
34: set([39,40,45,46]),
35: set([40,41,45,46,47]),
36: set([41,42,46,47,48]),
37: set([42,47,48]),
39: set([45]),
40: set([45,46]),
41: set([46,47]),
42: set([47,48]),
45: set(),
46: set(),
47: set(),
48: set()}
# translate from simple input notation to real checkerboard notation
IMAP = {'a1': 5, 'c1': 6, 'e1': 7, 'g1': 8,
'b2': 10, 'd2': 11, 'f2': 12, 'h2': 13,
'a3': 14, 'c3': 15, 'e3': 16, 'g3': 17,
'b4': 19, 'd4': 20, 'f4': 21, 'h4': 22,
'a5': 23, 'c5': 24, 'e5': 25, 'g5': 26,
'b6': 28, 'd6': 29, 'f6': 30, 'h6': 31,
'a7': 32, 'c7': 33, 'e7': 34, 'g7': 35,
'b8': 37, 'd8': 38, 'f8': 39, 'h8': 40}
CBMAP = {5:4, 6:3, 7:2, 8:1,
10:8, 11:7, 12:6, 13:5,
14:12, 15:11, 16:10, 17:9,
19:16, 20:15, 21:14, 22:13,
23:20, 24:19, 25:18, 26:17,
28:24, 29:23, 30:22, 31:21,
32:28, 33:27, 34:26, 35:25,
37:32, 38:31, 39:30, 40:29}
def create_position_map():
""" Maps compressed grid indices xi + yi * 8 to internal
board indices """
pos = {}
pos[1] = 45; pos[3] = 46; pos[5] = 47; pos[7] = 48
pos[8] = 39; pos[10] = 40; pos[12] = 41; pos[14] = 42
pos[17] = 34; pos[19] = 35; pos[21] = 36; pos[23] = 37
pos[24] = 28; pos[26] = 29; pos[28] = 30; pos[30] = 31
pos[33] = 23; pos[35] = 24; pos[37] = 25; pos[39] = 26
pos[40] = 17; pos[42] = 18; pos[44] = 19; pos[46] = 20
pos[49] = 12; pos[51] = 13; pos[53] = 14; pos[55] = 15
pos[56] = 6; pos[58] = 7; pos[60] = 8; pos[62] = 9
return pos
def create_key_map():
""" Maps internal board indices to checkerboard label numbers """
key = {}
key[6] = 4; key[7] = 3; key[8] = 2; key[9] = 1
key[12] = 8; key[13] = 7; key[14] = 6; key[15] = 5
key[17] = 12; key[18] = 11; key[19] = 10; key[20] = 9
key[23] = 16; key[24] = 15; key[25] = 14; key[26] = 13
key[28] = 20; key[29] = 19; key[30] = 18; key[31] = 17
key[34] = 24; key[35] = 23; key[36] = 22; key[37] = 21
key[39] = 28; key[40] = 27; key[41] = 26; key[42] = 25
key[45] = 32; key[46] = 31; key[47] = 30; key[48] = 29
return key
def create_grid_map():
""" Maps internal board indices to grid (row, col) coordinates """
grd = {}
grd[6] = (7,0); grd[7] = (7,2); grd[8] = (7,4); grd[9] = (7,6)
grd[12] = (6,1); grd[13] = (6,3); grd[14] = (6,5); grd[15] = (6,7)
grd[17] = (5,0); grd[18] = (5,2); grd[19] = (5,4); grd[20] = (5,6)
grd[23] = (4,1); grd[24] = (4,3); grd[25] = (4,5); grd[26] = (4,7)
grd[28] = (3,0); grd[29] = (3,2); grd[30] = (3,4); grd[31] = (3,6)
grd[34] = (2,1); grd[35] = (2,3); grd[36] = (2,5); grd[37] = (2,7)
grd[39] = (1,0); grd[40] = (1,2); grd[41] = (1,4); grd[42] = (1,6)
grd[45] = (0,1); grd[46] = (0,3); grd[47] = (0,5); grd[48] = (0,7)
return grd
def flip_dict(m):
d = {}
keys = [k for k, _ in m.iteritems()]
vals = [v for _, v in m.iteritems()]
for k, v in zip(vals, keys):
d[k] = v
return d
def reverse_dict(m):
d = {}
keys = [k for k, _ in m.iteritems()]
vals = [v for _, v in m.iteritems()]
for k, v in zip(keys, reversed(vals)):
d[k] = v
return d
def similarity(pattern, pieces):
global grid
p1 = [grid[i] for i in pattern]
p2 = [grid[j] for j in pieces]
return sum(min(math.hypot(x1-x2, y1-y2) for x1, y1 in p1) for x2, y2 in p2)
def get_preferences_from_file():
config = RawConfigParser()
if not os.access('raven.ini',os.F_OK):
# no .ini file yet, so make one
config.add_section('AnnotationWindow')
config.set('AnnotationWindow', 'font', 'Arial')
config.set('AnnotationWindow', 'size', '12')
# Writing our configuration file to 'raven.ini'
with open('raven.ini', 'wb') as configfile:
config.write(configfile)
config.read('raven.ini')
font = config.get('AnnotationWindow', 'font')
size = config.get('AnnotationWindow', 'size')
return font, size
def write_preferences_to_file(font, size):
config = RawConfigParser()
config.add_section('AnnotationWindow')
config.set('AnnotationWindow', 'font', font)
config.set('AnnotationWindow', 'size', size)
# Writing our configuration file to 'raven.ini'
with open('raven.ini', 'wb') as configfile:
config.write(configfile)
def parse_index(idx):
line, _, char = idx.partition('.')
return int(line), int(char)
def to_string(line, char):
return "%d.%d" % (line, char)
grid = create_grid_map()
keymap = create_key_map()
squaremap = flip_dict(keymap)
| Python |
import sys
from goal import Goal
from composite import CompositeGoal
class Goal_OneKingFlee(CompositeGoal):
def __init__(self, owner):
CompositeGoal.__init__(self, owner)
def activate(self):
self.status = self.ACTIVE
self.removeAllSubgoals()
# because goals are *pushed* onto the front of the subgoal list they must
# be added in reverse order.
self.addSubgoal(Goal_MoveTowardNearestDoubleCorner(self.owner))
self.addSubgoal(Goal_SeeSaw(self.owner))
def process(self):
self.activateIfInactive()
return self.processSubgoals()
def terminate(self):
self.status = self.INACTIVE
class Goal_MoveTowardBestDoubleCorner(Goal):
def __init__(self, owner):
Goal.__init__(self, owner)
self.dc = [8, 13, 27, 32]
def activate(self):
self.status = self.ACTIVE
def process(self):
# if status is inactive, activate
self.activateIfInactive()
# only moves (not captures) are a valid goal
if self.owner.captures:
self.status = self.FAILED
return
# identify player king and enemy king
plr_color = self.owner.to_move
enemy_color = self.owner.enemy
player = self.owner.get_pieces(plr_color)[0]
p_idx, _ = player
p_row, p_col = self.owner.row_col_for_index(p_idx)
enemy = self.owner.get_pieces(enemy_color)[0]
e_idx, _ = enemy
e_row, e_col = self.owner.row_col_for_index(e_idx)
# pick DC that isn't blocked by enemy
lowest_dist = sys.maxint
dc = 0
for i in self.dc:
dc_row, dc_col = self.owner.row_col_for_index(i)
pdist = abs(dc_row - p_row) + abs(dc_col - p_col)
edist = abs(dc_row - e_row) + abs(dc_col - e_col)
if pdist < lowest_dist and edist > pdist:
lowest_dist = pdist
dc = i
# if lowest distance is 0, then goal is complete.
if lowest_dist == 0:
self.status = self.COMPLETED
return
# select the available move that decreases the distance
# between the original player position and the chosen double corner.
# If no such move exists, the goal has failed.
dc_row, dc_col = self.owner.row_col_for_index(dc)
good_move = None
for m in self.owner.moves:
# try a move and gather the new row & col for the player
self.owner.make_move(m, False, False)
plr_update = self.owner.get_pieces(plr_color)[0]
pu_idx, _ = plr_update
pu_row, pu_col = self.owner.row_col_for_index(pu_idx)
self.owner.undo_move(m, False, False)
new_diff = abs(pu_row - dc_row) + abs(pu_col - dc_col)
if new_diff < lowest_dist:
good_move = m
break
if good_move:
self.owner.make_move(good_move, True, True)
else:
self.status = self.FAILED
def terminate(self):
self.status = self.INACTIVE
class Goal_SeeSaw(Goal):
def __init__(self, owner):
Goal.__init__(self, owner)
def activate(self):
self.status = self.ACTIVE
def process(self):
# for now, I'm not even sure I need this goal, but I'm saving it
# as a placeholder.
self.status = self.COMPLETED
def terminate(self):
self.status = self.INACTIVE
| Python |
import os
from Tkinter import *
from Tkconstants import W, E
import Tkinter as tk
from tkMessageBox import askyesnocancel
from multiprocessing import freeze_support
from globalconst import *
from aboutbox import AboutBox
from setupboard import SetupBoard
from gamemanager import GameManager
from centeredwindow import CenteredWindow
from prefdlg import PreferencesDialog
class MainFrame(object, CenteredWindow):
def __init__(self, master):
self.root = master
self.root.withdraw()
self.root.iconbitmap(RAVEN_ICON)
self.root.title('Raven ' + VERSION)
self.root.protocol('WM_DELETE_WINDOW', self._on_close)
self.thinkTime = IntVar(value=5)
self.manager = GameManager(root=self.root, parent=self)
self.menubar = tk.Menu(self.root)
self.create_game_menu()
self.create_options_menu()
self.create_help_menu()
self.root.config(menu=self.menubar)
CenteredWindow.__init__(self, self.root)
self.root.deiconify()
def _on_close(self):
if self.manager.view.is_dirty():
msg = 'Do you want to save your changes before exiting?'
result = askyesnocancel(TITLE, msg)
if result == True:
self.manager.save_game()
elif result == None:
return
self.root.destroy()
def set_title_bar_filename(self, filename=None):
if not filename:
self.root.title(TITLE)
else:
self.root.title(TITLE + ' - ' + os.path.basename(filename))
def undo_all_moves(self, *args):
self.stop_processes()
self.manager.model.undo_all_moves(None,
self.manager.view.get_annotation())
self.manager._controller1.remove_highlights()
self.manager._controller2.remove_highlights()
self.manager.view.update_statusbar()
def redo_all_moves(self, *args):
self.stop_processes()
self.manager.model.redo_all_moves(None,
self.manager.view.get_annotation())
self.manager._controller1.remove_highlights()
self.manager._controller2.remove_highlights()
self.manager.view.update_statusbar()
def undo_single_move(self, *args):
self.stop_processes()
self.manager.model.undo_move(None, None, True, True,
self.manager.view.get_annotation())
self.manager._controller1.remove_highlights()
self.manager._controller2.remove_highlights()
self.manager.view.update_statusbar()
def redo_single_move(self, *args):
self.stop_processes()
annotation = self.manager.view.get_annotation()
self.manager.model.redo_move(None, None, annotation)
self.manager._controller1.remove_highlights()
self.manager._controller2.remove_highlights()
self.manager.view.update_statusbar()
def create_game_menu(self):
game = Menu(self.menubar, tearoff=0)
game.add_command(label='New game', underline=0,
command=self.manager.new_game)
game.add_command(label='Open game ...', underline=0,
command=self.manager.open_game)
game.add_separator()
game.add_command(label='Save game', underline=0,
command=self.manager.save_game)
game.add_command(label='Save game As ...', underline=10,
command=self.manager.save_game_as)
game.add_separator()
game.add_command(label='Set up Board ...', underline=7,
command=self.show_setup_board_dialog)
game.add_command(label='Flip board', underline=0,
command=self.flip_board)
game.add_separator()
game.add_command(label='Exit', underline=0,
command=self._on_close)
self.menubar.add_cascade(label='Game', menu=game)
def create_options_menu(self):
options = Menu(self.menubar, tearoff=0)
think = Menu(options, tearoff=0)
think.add_radiobutton(label="1 second", underline=None,
command=self.set_think_time,
variable=self.thinkTime,
value=1)
think.add_radiobutton(label="2 seconds", underline=None,
command=self.set_think_time,
variable=self.thinkTime,
value=2)
think.add_radiobutton(label="5 seconds", underline=None,
command=self.set_think_time,
variable=self.thinkTime,
value=5)
think.add_radiobutton(label="10 seconds", underline=None,
command=self.set_think_time,
variable=self.thinkTime,
value=10)
think.add_radiobutton(label="30 seconds", underline=None,
command=self.set_think_time,
variable=self.thinkTime,
value=30)
think.add_radiobutton(label="1 minute", underline=None,
command=self.set_think_time,
variable=self.thinkTime,
value=60)
options.add_cascade(label='CPU think time', underline=0,
menu=think)
options.add_separator()
options.add_command(label='Preferences ...', underline=0,
command=self.show_preferences_dialog)
self.menubar.add_cascade(label='Options', menu=options)
def create_help_menu(self):
helpmenu = Menu(self.menubar, tearoff=0)
helpmenu.add_command(label='About Raven ...', underline=0,
command=self.show_about_box)
self.menubar.add_cascade(label='Help', menu=helpmenu)
def stop_processes(self):
# stop any controller processes from making moves
self.manager.model.curr_state.ok_to_move = False
self.manager._controller1.stop_process()
self.manager._controller2.stop_process()
def show_about_box(self):
AboutBox(self.root, 'About Raven')
def show_setup_board_dialog(self):
self.stop_processes()
dlg = SetupBoard(self.root, 'Set up board', self.manager)
self.manager.set_controllers()
self.root.focus_set()
self.manager.turn_finished()
def show_preferences_dialog(self):
font, size = get_preferences_from_file()
dlg = PreferencesDialog(self.root, 'Preferences', font, size)
if dlg.result:
self.manager.view.init_font_sizes(dlg.font, dlg.size)
self.manager.view.init_tags()
write_preferences_to_file(dlg.font, dlg.size)
def set_think_time(self):
self.manager._controller1.set_search_time(self.thinkTime.get())
self.manager._controller2.set_search_time(self.thinkTime.get())
def flip_board(self):
if self.manager.model.to_move == BLACK:
self.manager._controller1.remove_highlights()
else:
self.manager._controller2.remove_highlights()
self.manager.view.flip_board(not self.manager.view.flip_view)
if self.manager.model.to_move == BLACK:
self.manager._controller1.add_highlights()
else:
self.manager._controller2.add_highlights()
def start():
root = Tk()
mainframe = MainFrame(root)
mainframe.root.update()
mainframe.root.mainloop()
if __name__=='__main__':
freeze_support()
start()
| Python |
class Move(object):
def __init__(self, squares, annotation=''):
self.affected_squares = squares
self.annotation = annotation
def __repr__(self):
return str(self.affected_squares)
| Python |
from composite import CompositeGoal
from onek_onek import OneKingAttackOneKingEvaluator, OneKingFleeOneKingEvaluator
class Goal_Think(CompositeGoal):
def __init__(self, owner):
CompositeGoal.__init__(self, owner)
self.evaluators = [OneKingAttackOneKingEvaluator(1.0),
OneKingFleeOneKingEvaluator(1.0)]
def activate(self):
self.arbitrate()
self.status = self.ACTIVE
def process(self):
self.activateIfInactive()
status = self.processSubgoals()
if status == self.COMPLETED or status == self.FAILED:
self.status = self.INACTIVE
return status
def terminate(self):
pass
def arbitrate(self):
most_desirable = None
best_score = 0
for e in self.evaluators:
d = e.calculateDesirability()
if d > best_score:
most_desirable = e
best_score = d
if most_desirable:
most_desirable.setGoal(self.owner)
return best_score
| Python |
from abc import ABCMeta, abstractmethod
class Goal:
__metaclass__ = ABCMeta
INACTIVE = 0
ACTIVE = 1
COMPLETED = 2
FAILED = 3
def __init__(self, owner):
self.owner = owner
self.status = self.INACTIVE
@abstractmethod
def activate(self):
pass
@abstractmethod
def process(self):
pass
@abstractmethod
def terminate(self):
pass
def handleMessage(self, msg):
return False
def addSubgoal(self, goal):
raise NotImplementedError('Cannot add goals to atomic goals')
def reactivateIfFailed(self):
if self.status == self.FAILED:
self.status = self.INACTIVE
def activateIfInactive(self):
if self.status == self.INACTIVE:
self.status = self.ACTIVE
| Python |
from Tkinter import *
from ttk import Checkbutton
from tkSimpleDialog import Dialog
from globalconst import *
class SetupBoard(Dialog):
def __init__(self, parent, title, gameManager):
self._master = parent
self._manager = gameManager
self._load_entry_box_vars()
self.result = False
Dialog.__init__(self, parent, title)
def body(self, master):
self._npLFrame = LabelFrame(master, text='No. of players:')
self._npFrameEx1 = Frame(self._npLFrame, width=30)
self._npFrameEx1.pack(side=LEFT, pady=5, expand=1)
self._npButton1 = Radiobutton(self._npLFrame, text='Zero (autoplay)',
value=0, variable=self._num_players,
command=self._disable_player_color)
self._npButton1.pack(side=LEFT, pady=5, expand=1)
self._npButton2 = Radiobutton(self._npLFrame, text='One',
value=1, variable=self._num_players,
command=self._enable_player_color)
self._npButton2.pack(side=LEFT, pady=5, expand=1)
self._npButton3 = Radiobutton(self._npLFrame, text='Two',
value=2, variable=self._num_players,
command=self._disable_player_color)
self._npButton3.pack(side=LEFT, pady=5, expand=1)
self._npFrameEx2 = Frame(self._npLFrame, width=30)
self._npFrameEx2.pack(side=LEFT, pady=5, expand=1)
self._npLFrame.pack(fill=X)
self._playerFrame = LabelFrame(master, text='Player color:')
self._playerFrameEx1 = Frame(self._playerFrame, width=50)
self._playerFrameEx1.pack(side=LEFT, pady=5, expand=1)
self._rbColor1 = Radiobutton(self._playerFrame, text='Black',
value=BLACK, variable=self._player_color)
self._rbColor1.pack(side=LEFT, padx=0, pady=5, expand=1)
self._rbColor2 = Radiobutton(self._playerFrame, text='White',
value=WHITE, variable=self._player_color)
self._rbColor2.pack(side=LEFT, padx=0, pady=5, expand=1)
self._playerFrameEx2 = Frame(self._playerFrame, width=50)
self._playerFrameEx2.pack(side=LEFT, pady=5, expand=1)
self._playerFrame.pack(fill=X)
self._rbFrame = LabelFrame(master, text='Next to move:')
self._rbFrameEx1 = Frame(self._rbFrame, width=50)
self._rbFrameEx1.pack(side=LEFT, pady=5, expand=1)
self._rbTurn1 = Radiobutton(self._rbFrame, text='Black',
value=BLACK, variable=self._player_turn)
self._rbTurn1.pack(side=LEFT, padx=0, pady=5, expand=1)
self._rbTurn2 = Radiobutton(self._rbFrame, text='White',
value=WHITE, variable=self._player_turn)
self._rbTurn2.pack(side=LEFT, padx=0, pady=5, expand=1)
self._rbFrameEx2 = Frame(self._rbFrame, width=50)
self._rbFrameEx2.pack(side=LEFT, pady=5, expand=1)
self._rbFrame.pack(fill=X)
self._bcFrame = LabelFrame(master, text='Board configuration')
self._wmFrame = Frame(self._bcFrame, borderwidth=0)
self._wmLabel = Label(self._wmFrame, text='White men:')
self._wmLabel.pack(side=LEFT, padx=7, pady=10)
self._wmEntry = Entry(self._wmFrame, width=40,
textvariable=self._white_men)
self._wmEntry.pack(side=LEFT, padx=10)
self._wmFrame.pack()
self._wkFrame = Frame(self._bcFrame, borderwidth=0)
self._wkLabel = Label(self._wkFrame, text='White kings:')
self._wkLabel.pack(side=LEFT, padx=5, pady=10)
self._wkEntry = Entry(self._wkFrame, width=40,
textvariable=self._white_kings)
self._wkEntry.pack(side=LEFT, padx=10)
self._wkFrame.pack()
self._bmFrame = Frame(self._bcFrame, borderwidth=0)
self._bmLabel = Label(self._bmFrame, text='Black men:')
self._bmLabel.pack(side=LEFT, padx=7, pady=10)
self._bmEntry = Entry(self._bmFrame, width=40,
textvariable=self._black_men)
self._bmEntry.pack(side=LEFT, padx=10)
self._bmFrame.pack()
self._bkFrame = Frame(self._bcFrame, borderwidth=0)
self._bkLabel = Label(self._bkFrame, text='Black kings:')
self._bkLabel.pack(side=LEFT, padx=5, pady=10)
self._bkEntry = Entry(self._bkFrame, width=40,
textvariable=self._black_kings)
self._bkEntry.pack(side=LEFT, padx=10)
self._bkFrame.pack()
self._bcFrame.pack(fill=X)
self._bsState = IntVar()
self._bsFrame = Frame(master, borderwidth=0)
self._bsCheck = Checkbutton(self._bsFrame, variable=self._bsState,
text='Start new game with the current setup?')
self._bsCheck.pack()
self._bsFrame.pack(fill=X)
if self._num_players.get() == 1:
self._enable_player_color()
else:
self._disable_player_color()
def validate(self):
self.wm_list = self._parse_int_list(self._white_men.get())
self.wk_list = self._parse_int_list(self._white_kings.get())
self.bm_list = self._parse_int_list(self._black_men.get())
self.bk_list = self._parse_int_list(self._black_kings.get())
if (self.wm_list == None or self.wk_list == None
or self.bm_list == None or self.bk_list == None):
return 0 # Error occurred during parsing
if not self._all_unique(self.wm_list, self.wk_list,
self.bm_list, self.bk_list):
return 0 # A repeated index occurred
return 1
def apply(self):
mgr = self._manager
model = mgr.model
view = mgr.view
state = model.curr_state
mgr.player_color = self._player_color.get()
mgr.num_players = self._num_players.get()
mgr.model.curr_state.to_move = self._player_turn.get()
# only reset the BoardView if men or kings have new positions
if (sorted(self.wm_list) != sorted(self._orig_white_men) or
sorted(self.wk_list) != sorted(self._orig_white_kings) or
sorted(self.bm_list) != sorted(self._orig_black_men) or
sorted(self.bk_list) != sorted(self._orig_black_kings) or
self._bsState.get() == 1):
state.clear()
sq = state.squares
for item in self.wm_list:
idx = squaremap[item]
sq[idx] = WHITE | MAN
for item in self.wk_list:
idx = squaremap[item]
sq[idx] = WHITE | KING
for item in self.bm_list:
idx = squaremap[item]
sq[idx] = BLACK | MAN
for item in self.bk_list:
idx = squaremap[item]
sq[idx] = BLACK | KING
state.to_move = self._player_turn.get()
state.reset_undo()
view.reset_view(mgr.model)
if self._bsState.get() == 1:
mgr.filename = None
mgr.parent.set_title_bar_filename()
state.ok_to_move = True
self.result = True
self.destroy()
def cancel(self, event=None):
self.destroy()
def _load_entry_box_vars(self):
self._white_men = StringVar()
self._white_kings = StringVar()
self._black_men = StringVar()
self._black_kings = StringVar()
self._player_color = IntVar()
self._player_turn = IntVar()
self._num_players = IntVar()
self._player_color.set(self._manager.player_color)
self._num_players.set(self._manager.num_players)
model = self._manager.model
self._player_turn.set(model.curr_state.to_move)
view = self._manager.view
self._white_men.set(', '.join(view.get_positions(WHITE | MAN)))
self._white_kings.set(', '.join(view.get_positions(WHITE | KING)))
self._black_men.set(', '.join(view.get_positions(BLACK | MAN)))
self._black_kings.set(', '.join(view.get_positions(BLACK | KING)))
self._orig_white_men = map(int, view.get_positions(WHITE | MAN))
self._orig_white_kings = map(int, view.get_positions(WHITE | KING))
self._orig_black_men = map(int, view.get_positions(BLACK | MAN))
self._orig_black_kings = map(int, view.get_positions(BLACK | KING))
def _disable_player_color(self):
self._rbColor1.configure(state=DISABLED)
self._rbColor2.configure(state=DISABLED)
def _enable_player_color(self):
self._rbColor1.configure(state=NORMAL)
self._rbColor2.configure(state=NORMAL)
def _all_unique(self, *lists):
s = set()
total_list = []
for i in lists:
total_list.extend(i)
s = s.union(i)
return sorted(total_list) == sorted(s)
def _parse_int_list(self, parsestr):
try:
lst = parsestr.split(',')
except AttributeError:
return None
if lst == ['']:
return []
try:
lst = [int(i) for i in lst]
except ValueError:
return None
if not all(((x>=1 and x<=MAX_VALID_SQ) for x in lst)):
return None
return lst
| Python |
from Tkinter import Widget
from controller import Controller
from globalconst import *
class PlayerController(Controller):
def __init__(self, **props):
self._model = props['model']
self._view = props['view']
self._before_turn_event = None
self._end_turn_event = props['end_turn_event']
self._highlights = []
self._move_in_progress = False
def _register_event_handlers(self):
Widget.bind(self._view.canvas, '<Button-1>', self.mouse_click)
def _unregister_event_handlers(self):
Widget.unbind(self._view.canvas, '<Button-1>')
def stop_process(self):
pass
def set_search_time(self, time):
pass
def get_player_type(self):
return HUMAN
def set_before_turn_event(self, evt):
self._before_turn_event = evt
def add_highlights(self):
for h in self._highlights:
self._view.highlight_square(h, OUTLINE_COLOR)
def remove_highlights(self):
for h in self._highlights:
self._view.highlight_square(h, DARK_SQUARES)
def start_turn(self):
self._register_event_handlers()
self._model.curr_state.attach(self._view)
def end_turn(self):
self._unregister_event_handlers()
self._model.curr_state.detach(self._view)
def mouse_click(self, event):
xi, yi = self._view.calc_board_loc(event.x, event.y)
pos = self._view.calc_board_pos(xi, yi)
sq = self._model.curr_state.squares[pos]
if not self._move_in_progress:
player = self._model.curr_state.to_move
self.moves = self._model.legal_moves()
if (sq & player) and self.moves:
self._before_turn_event()
# highlight the start square the user clicked on
self._view.highlight_square(pos, OUTLINE_COLOR)
self._highlights = [pos]
# reduce moves to number matching the positions entered
self.moves = self._filter_moves(pos, self.moves, 0)
self.idx = 2 if self._model.captures_available() else 1
# if only one move available, take it.
if len(self.moves) == 1:
self._make_move()
self._view.canvas.after(100, self._end_turn_event)
return
self._move_in_progress = True
else:
if sq & FREE:
self.moves = self._filter_moves(pos, self.moves, self.idx)
if len(self.moves) == 0: # illegal move
# remove previous square highlights
for h in self._highlights:
self._view.highlight_square(h, DARK_SQUARES)
self._move_in_progress = False
return
else:
self._view.highlight_square(pos, OUTLINE_COLOR)
self._highlights.append(pos)
if len(self.moves) == 1:
self._make_move()
self._view.canvas.after(100, self._end_turn_event)
return
self.idx += 2 if self._model.captures_available() else 1
def _filter_moves(self, pos, moves, idx):
del_list = []
for i, m in enumerate(moves):
if pos != m.affected_squares[idx][0]:
del_list.append(i)
for i in reversed(del_list):
del moves[i]
return moves
def _make_move(self):
move = self.moves[0].affected_squares
step = 2 if len(move) > 2 else 1
# highlight remaining board squares used in move
for m in move[step::step]:
idx = m[0]
self._view.highlight_square(idx, OUTLINE_COLOR)
self._highlights.append(idx)
self._model.make_move(self.moves[0], None, True, True,
self._view.get_annotation())
# a new move obliterates any more redo's along a branch of the game tree
self._model.curr_state.delete_redo_list()
self._move_in_progress = False
| Python |
from goal import Goal
from composite import CompositeGoal
class Goal_OneKingAttack(CompositeGoal):
def __init__(self, owner):
CompositeGoal.__init__(self, owner)
def activate(self):
self.status = self.ACTIVE
self.removeAllSubgoals()
# because goals are *pushed* onto the front of the subgoal list they must
# be added in reverse order.
self.addSubgoal(Goal_MoveTowardEnemy(self.owner))
self.addSubgoal(Goal_PinEnemy(self.owner))
def process(self):
self.activateIfInactive()
return self.processSubgoals()
def terminate(self):
self.status = self.INACTIVE
class Goal_MoveTowardEnemy(Goal):
def __init__(self, owner):
Goal.__init__(self, owner)
def activate(self):
self.status = self.ACTIVE
def process(self):
# if status is inactive, activate
self.activateIfInactive()
# only moves (not captures) are a valid goal
if self.owner.captures:
self.status = self.FAILED
return
# identify player king and enemy king
plr_color = self.owner.to_move
enemy_color = self.owner.enemy
player = self.owner.get_pieces(plr_color)[0]
p_idx, _ = player
p_row, p_col = self.owner.row_col_for_index(p_idx)
enemy = self.owner.get_pieces(enemy_color)[0]
e_idx, _ = enemy
e_row, e_col = self.owner.row_col_for_index(e_idx)
# if distance between player and enemy is already down
# to 2 rows or cols, then goal is complete.
if abs(p_row - e_row) == 2 or abs(p_col - e_col) == 2:
self.status = self.COMPLETED
# select the available move that decreases the distance
# between the player and the enemy. If no such move exists,
# the goal has failed.
good_move = None
for m in self.owner.moves:
# try a move and gather the new row & col for the player
self.owner.make_move(m, False, False)
plr_update = self.owner.get_pieces(plr_color)[0]
pu_idx, _ = plr_update
pu_row, pu_col = self.owner.row_col_for_index(pu_idx)
self.owner.undo_move(m, False, False)
new_diff = abs(pu_row - e_row) + abs(pu_col - e_col)
old_diff = abs(p_row - e_row) + abs(p_col - e_col)
if new_diff < old_diff:
good_move = m
break
if good_move:
self.owner.make_move(good_move, True, True)
else:
self.status = self.FAILED
def terminate(self):
self.status = self.INACTIVE
class Goal_PinEnemy(Goal):
def __init__(self, owner):
Goal.__init__(self, owner)
def activate(self):
self.status = self.ACTIVE
def process(self):
# for now, I'm not even sure I need this goal, but I'm saving it
# as a placeholder.
self.status = self.COMPLETED
def terminate(self):
self.status = self.INACTIVE
| Python |
from Tkinter import *
class CenteredWindow:
def __init__(self, root):
self.root = root
self.root.after_idle(self.center_on_screen)
self.root.update()
def center_on_screen(self):
self.root.update_idletasks()
sw = self.root.winfo_screenwidth()
sh = self.root.winfo_screenheight()
w = self.root.winfo_reqwidth()
h = self.root.winfo_reqheight()
new_geometry = "+%d+%d" % ((sw-w)/2, (sh-h)/2)
self.root.geometry(newGeometry=new_geometry) | Python |
class Command(object):
def __init__(self, **props):
self.add = props.get('add') or []
self.remove = props.get('remove') or []
| Python |
from globalconst import BLACK, WHITE, MAN, KING
from goalevaluator import GoalEvaluator
from onekingattack import Goal_OneKingAttack
class OneKingAttackOneKingEvaluator(GoalEvaluator):
def __init__(self, bias):
GoalEvaluator.__init__(self, bias)
def calculateDesirability(self, board):
plr_color = board.to_move
enemy_color = board.enemy
# if we don't have one man on each side or the player
# doesn't have the opposition, then goal is undesirable.
if (board.count(BLACK) != 1 or board.count(WHITE) != 1 or
not board.has_opposition(plr_color)):
return 0.0
player = board.get_pieces(plr_color)[0]
p_idx, p_val = player
p_row, p_col = board.row_col_for_index(p_idx)
enemy = board.get_pieces(enemy_color)[0]
e_idx, e_val = enemy
e_row, e_col = board.row_col_for_index(e_idx)
# must be two kings against each other and the distance
# between them at least three rows away
if ((p_val & KING) and (e_val & KING) and
(abs(p_row - e_row) > 2 or abs(p_col - e_col) > 2)):
return 1.0
return 0.0
def setGoal(self, board):
player = board.to_move
board.removeAllSubgoals()
if player == WHITE:
goalset = board.addWhiteSubgoal
else:
goalset = board.addBlackSubgoal
goalset(Goal_OneKingAttack(board))
class OneKingFleeOneKingEvaluator(GoalEvaluator):
def __init__(self, bias):
GoalEvaluator.__init__(self, bias)
def calculateDesirability(self, board):
plr_color = board.to_move
enemy_color = board.enemy
# if we don't have one man on each side or the player
# has the opposition (meaning we should attack instead),
# then goal is not applicable.
if (board.count(BLACK) != 1 or board.count(WHITE) != 1 or
board.has_opposition(plr_color)):
return 0.0
player = board.get_pieces(plr_color)[0]
p_idx, p_val = player
enemy = board.get_pieces(enemy_color)[0]
e_idx, e_val = enemy
# must be two kings against each other; otherwise it's
# not applicable.
if not ((p_val & KING) and (e_val & KING)):
return 0.0
return 1.0
def setGoal(self, board):
player = board.to_move
board.removeAllSubgoals()
if player == WHITE:
goalset = board.addWhiteSubgoal
else:
goalset = board.addBlackSubgoal
goalset(Goal_OneKingFlee(board))
| Python |
import unittest
import checkers
import games
from globalconst import *
# (white)
# 45 46 47 48
# 39 40 41 42
# 34 35 36 37
# 28 29 30 31
# 23 24 25 26
# 17 18 19 20
# 12 13 14 15
# 6 7 8 9
# (black)
class TestBlackManSingleJump(unittest.TestCase):
def setUp(self):
self.game = checkers.Checkers()
self.board = self.game.curr_state
squares = self.board.squares
self.board.clear()
squares[6] = BLACK | MAN
squares[12] = WHITE | MAN
def testJump(self):
moves = self.game.legal_moves(self.board)
self.assertEqual(moves[0].affected_squares,
[[6, BLACK | MAN, FREE],
[12, WHITE | MAN, FREE],
[18, FREE, BLACK | MAN]])
class TestBlackManDoubleJump(unittest.TestCase):
def setUp(self):
self.game = checkers.Checkers()
self.board = self.game.curr_state
squares = self.board.squares
self.board.clear()
squares[6] = BLACK | MAN
squares[12] = WHITE | MAN
squares[23] = WHITE | MAN
def testJump(self):
moves = self.game.legal_moves(self.board)
self.assertEqual(moves[0].affected_squares,
[[6, BLACK | MAN, FREE],
[12, WHITE | MAN, FREE],
[18, FREE, FREE],
[23, WHITE | MAN, FREE],
[28, FREE, BLACK | MAN]])
class TestBlackManCrownKingOnJump(unittest.TestCase):
def setUp(self):
self.game = checkers.Checkers()
self.board = self.game.curr_state
squares = self.board.squares
self.board.clear()
# (white)
# 45 46 47 48
# 39 40 41 42
# 34 35 36 37
# 28 29 30 31
# 23 24 25 26
# 17 18 19 20
# 12 13 14 15
# 6 7 8 9
# (black)
squares[12] = BLACK | MAN
squares[18] = WHITE | MAN
squares[30] = WHITE | MAN
squares[41] = WHITE | MAN
# set another man on 40 to test that crowning
# move ends the turn
squares[40] = WHITE | MAN
def testJump(self):
moves = self.game.legal_moves(self.board)
self.assertEqual(moves[0].affected_squares,
[[12, BLACK | MAN, FREE],
[18, WHITE | MAN, FREE],
[24, FREE, FREE],
[30, WHITE | MAN, FREE],
[36, FREE, FREE],
[41, WHITE | MAN, FREE],
[46, FREE, BLACK | KING]])
class TestBlackManCrownKingOnMove(unittest.TestCase):
def setUp(self):
self.game = checkers.Checkers()
self.board = self.game.curr_state
squares = self.board.squares
self.board.clear()
squares[39] = BLACK | MAN
squares[18] = WHITE | MAN
def testJump(self):
moves = self.game.legal_moves(self.board)
self.assertEqual(moves[0].affected_squares,
[[39, BLACK | MAN, FREE],
[45, FREE, BLACK | KING]])
class TestBlackKingOptionalJumpDiamond(unittest.TestCase):
def setUp(self):
self.game = checkers.Checkers()
self.board = self.game.curr_state
squares = self.board.squares
self.board.clear()
squares[13] = BLACK | KING
squares[19] = WHITE | MAN
squares[30] = WHITE | MAN
squares[29] = WHITE | MAN
squares[18] = WHITE | MAN
def testJump(self):
moves = self.game.legal_moves(self.board)
self.assertEqual(moves[0].affected_squares,
[[13, BLACK | KING, FREE], [18, WHITE | MAN, FREE],
[23, FREE, FREE], [29, WHITE | MAN, FREE],
[35, FREE, FREE], [30, WHITE | MAN, FREE],
[25, FREE, FREE], [19, WHITE | MAN, FREE],
[13, FREE, BLACK | KING]])
self.assertEqual(moves[1].affected_squares,
[[13, BLACK | KING, FREE], [19, WHITE | MAN, FREE],
[25, FREE, FREE], [30, WHITE | MAN, FREE],
[35, FREE, FREE], [29, WHITE | MAN, FREE],
[23, FREE, FREE], [18, WHITE | MAN, FREE],
[13, FREE, BLACK | KING]])
class TestWhiteManSingleJump(unittest.TestCase):
def setUp(self):
self.game = checkers.Checkers()
self.board = self.game.curr_state
self.board.to_move = WHITE
squares = self.board.squares
self.board.clear()
squares[41] = WHITE | MAN
squares[36] = BLACK | MAN
def testJump(self):
moves = self.game.legal_moves(self.board)
self.assertEqual(moves[0].affected_squares,
[[41, WHITE | MAN, FREE],
[36, BLACK | MAN, FREE],
[31, FREE, WHITE | MAN]])
class TestWhiteManDoubleJump(unittest.TestCase):
def setUp(self):
self.game = checkers.Checkers()
self.board = self.game.curr_state
self.board.to_move = WHITE
squares = self.board.squares
self.board.clear()
squares[41] = WHITE | MAN
squares[36] = BLACK | MAN
squares[25] = BLACK | MAN
def testJump(self):
moves = self.game.legal_moves(self.board)
self.assertEqual(moves[0].affected_squares,
[[41, WHITE | MAN, FREE],
[36, BLACK | MAN, FREE],
[31, FREE, FREE],
[25, BLACK | MAN, FREE],
[19, FREE, WHITE | MAN]])
class TestWhiteManCrownKingOnMove(unittest.TestCase):
def setUp(self):
self.game = checkers.Checkers()
self.board = self.game.curr_state
self.board.to_move = WHITE
squares = self.board.squares
self.board.clear()
squares[15] = WHITE | MAN
squares[36] = BLACK | MAN
def testJump(self):
moves = self.game.legal_moves(self.board)
self.assertEqual(moves[0].affected_squares,
[[15, WHITE | MAN, FREE],
[9, FREE, WHITE | KING]])
class TestWhiteManCrownKingOnJump(unittest.TestCase):
def setUp(self):
self.game = checkers.Checkers()
self.board = self.game.curr_state
self.board.to_move = WHITE
squares = self.board.squares
self.board.clear()
squares[41] = WHITE | MAN
squares[36] = BLACK | MAN
squares[25] = BLACK | MAN
squares[13] = BLACK | KING
# set another man on 10 to test that crowning
# move ends the turn
squares[12] = BLACK | KING
def testJump(self):
moves = self.game.legal_moves(self.board)
self.assertEqual(moves[0].affected_squares,
[[41, WHITE | MAN, FREE],
[36, BLACK | MAN, FREE],
[31, FREE, FREE],
[25, BLACK | MAN, FREE],
[19, FREE, FREE],
[13, BLACK | KING, FREE],
[7, FREE, WHITE | KING]])
class TestWhiteKingOptionalJumpDiamond(unittest.TestCase):
def setUp(self):
self.game = checkers.Checkers()
self.board = self.game.curr_state
self.board.to_move = WHITE
squares = self.board.squares
self.board.clear()
squares[13] = WHITE | KING
squares[19] = BLACK | MAN
squares[30] = BLACK | MAN
squares[29] = BLACK | MAN
squares[18] = BLACK | MAN
def testJump(self):
moves = self.game.legal_moves(self.board)
self.assertEqual(moves[0].affected_squares,
[[13, WHITE | KING, FREE], [18, BLACK | MAN, FREE],
[23, FREE, FREE], [29, BLACK | MAN, FREE],
[35, FREE, FREE], [30, BLACK | MAN, FREE],
[25, FREE, FREE], [19, BLACK | MAN, FREE],
[13, FREE, WHITE | KING]])
self.assertEqual(moves[1].affected_squares,
[[13, WHITE | KING, FREE], [19, BLACK | MAN, FREE],
[25, FREE, FREE], [30, BLACK | MAN, FREE],
[35, FREE, FREE], [29, BLACK | MAN, FREE],
[23, FREE, FREE], [18, BLACK | MAN, FREE],
[13, FREE, WHITE | KING]])
class TestUtilityFunc(unittest.TestCase):
def setUp(self):
self.game = checkers.Checkers()
self.board = self.game.curr_state
self.board.to_move = WHITE
self.squares = self.board.squares
def testInitialUtility(self):
code = sum(self.board.value[s] for s in self.squares)
nwm = code % 16
nwk = (code >> 4) % 16
nbm = (code >> 8) % 16
nbk = (code >> 12) % 16
nm = nbm + nwm
nk = nbk + nwk
self.assertEqual(self.board._eval_cramp(self.squares), 0)
self.assertEqual(self.board._eval_backrankguard(self.squares), 0)
self.assertEqual(self.board._eval_doublecorner(self.squares), 0)
self.assertEqual(self.board._eval_center(self.squares), 0)
self.assertEqual(self.board._eval_edge(self.squares), 0)
self.assertEqual(self.board._eval_tempo(self.squares, nm, nbk,
nbm, nwk, nwm), 0)
self.assertEqual(self.board._eval_playeropposition(self.squares, nwm,
nwk, nbk, nbm, nm,
nk), 0)
self.assertEqual(self.board.utility(WHITE), -2)
class TestSuccessorFuncForBlack(unittest.TestCase):
def setUp(self):
self.game = checkers.Checkers()
self.board = self.game.curr_state
def testInitialBlackMoves(self):
# Tests whether initial game moves are correct from
# Black's perspective
moves = [m for m, _ in self.game.successors(self.board)]
self.assertEqual(moves[0].affected_squares,
[[17, BLACK | MAN, FREE],
[23, FREE, BLACK | MAN]])
self.assertEqual(moves[1].affected_squares,
[[18, BLACK | MAN, FREE],
[23, FREE, BLACK | MAN]])
self.assertEqual(moves[2].affected_squares,
[[18, BLACK | MAN, FREE],
[24, FREE, BLACK | MAN]])
self.assertEqual(moves[3].affected_squares,
[[19, BLACK | MAN, FREE],
[24, FREE, BLACK | MAN]])
self.assertEqual(moves[4].affected_squares,
[[19, BLACK | MAN, FREE],
[25, FREE, BLACK | MAN]])
self.assertEqual(moves[5].affected_squares,
[[20, BLACK | MAN, FREE],
[25, FREE, BLACK | MAN]])
self.assertEqual(moves[6].affected_squares,
[[20, BLACK | MAN, FREE],
[26, FREE, BLACK | MAN]])
class TestSuccessorFuncForWhite(unittest.TestCase):
def setUp(self):
self.game = checkers.Checkers()
self.board = self.game.curr_state
# I'm cheating here ... white never moves first in
# a real game, but I want to see that the moves
# would work anyway.
self.board.to_move = WHITE
def testInitialWhiteMoves(self):
# Tests whether initial game moves are correct from
# White's perspective
moves = [m for m, _ in self.game.successors(self.board)]
self.assertEqual(moves[0].affected_squares,
[[34, WHITE | MAN, FREE],
[29, FREE, WHITE | MAN]])
self.assertEqual(moves[1].affected_squares,
[[34, WHITE | MAN, FREE],
[28, FREE, WHITE | MAN]])
self.assertEqual(moves[2].affected_squares,
[[35, WHITE | MAN, FREE],
[30, FREE, WHITE | MAN]])
self.assertEqual(moves[3].affected_squares,
[[35, WHITE | MAN, FREE],
[29, FREE, WHITE | MAN]])
self.assertEqual(moves[4].affected_squares,
[[36, WHITE | MAN, FREE],
[31, FREE, WHITE | MAN]])
self.assertEqual(moves[5].affected_squares,
[[36, WHITE | MAN, FREE],
[30, FREE, WHITE | MAN]])
self.assertEqual(moves[6].affected_squares,
[[37, WHITE | MAN, FREE],
[31, FREE, WHITE | MAN]])
if __name__ == '__main__':
unittest.main()
| Python |
from Tkinter import PhotoImage
from Tkconstants import *
from globalconst import BULLET_IMAGE
from creoleparser import Parser
from rules import LinkRules
class TextTagEmitter(object):
"""
Generate tagged output compatible with the Tkinter Text widget
"""
def __init__(self, root, txtWidget, hyperMgr, bulletImage,
link_rules=None):
self.root = root
self.link_rules = link_rules or LinkRules()
self.txtWidget = txtWidget
self.hyperMgr = hyperMgr
self.line = 1
self.index = 0
self.number = 1
self.bullet = False
self.bullet_image = bulletImage
self.begin_italic = ''
self.begin_bold = ''
self.begin_list_item = ''
self.list_item = ''
self.begin_link = ''
# visit/leave methods for emitting nodes of the document:
def visit_document(self, node):
pass
def leave_document(self, node):
# leave_paragraph always leaves two extra carriage returns at the
# end of the text. This deletes them.
txtindex = '%d.%d' % (self.line-1, self.index)
self.txtWidget.delete(txtindex, END)
def visit_text(self, node):
if self.begin_list_item:
self.list_item = node.content
elif self.begin_link:
pass
else:
txtindex = '%d.%d' % (self.line, self.index)
self.txtWidget.insert(txtindex, node.content)
def leave_text(self, node):
if not self.begin_list_item:
self.index += len(node.content)
def visit_separator(self, node):
raise NotImplementedError
def leave_separator(self, node):
raise NotImplementedError
def visit_paragraph(self, node):
pass
def leave_paragraph(self, node):
txtindex = '%d.%d' % (self.line, self.index)
self.txtWidget.insert(txtindex, '\n\n')
self.line += 2
self.index = 0
self.number = 1
def visit_bullet_list(self, node):
self.bullet = True
def leave_bullet_list(self, node):
txtindex = '%d.%d' % (self.line, self.index)
self.txtWidget.insert(txtindex, '\n')
self.line += 1
self.index = 0
self.bullet = False
def visit_number_list(self, node):
self.number = 1
def leave_number_list(self, node):
txtindex = '%d.%d' % (self.line, self.index)
self.txtWidget.insert(txtindex, '\n')
self.line += 1
self.index = 0
def visit_list_item(self, node):
self.begin_list_item = '%d.%d' % (self.line, self.index)
def leave_list_item(self, node):
if self.bullet:
self.txtWidget.insert(self.begin_list_item, '\t')
next = '%d.%d' % (self.line, self.index+1)
self.txtWidget.image_create(next, image=self.bullet_image)
next = '%d.%d' % (self.line, self.index+2)
content = '\t%s\t\n' % self.list_item
self.txtWidget.insert(next, content)
end_list_item = '%d.%d' % (self.line, self.index + len(content)+2)
self.txtWidget.tag_add('bullet', self.begin_list_item, end_list_item)
elif self.number:
content = '\t%d.\t%s\n' % (self.number, self.list_item)
end_list_item = '%d.%d' % (self.line, self.index + len(content))
self.txtWidget.insert(self.begin_list_item, content)
self.txtWidget.tag_add('number', self.begin_list_item, end_list_item)
self.number += 1
self.begin_list_item = ''
self.list_item = ''
self.line += 1
self.index = 0
def visit_emphasis(self, node):
self.begin_italic = '%d.%d' % (self.line, self.index)
def leave_emphasis(self, node):
end_italic = '%d.%d' % (self.line, self.index)
self.txtWidget.tag_add('italic', self.begin_italic, end_italic)
def visit_strong(self, node):
self.begin_bold = '%d.%d' % (self.line, self.index)
def leave_strong(self, node):
end_bold = '%d.%d' % (self.line, self.index)
self.txtWidget.tag_add('bold', self.begin_bold, end_bold)
def visit_link(self, node):
self.begin_link = '%d.%d' % (self.line, self.index)
def leave_link(self, node):
end_link = '%d.%d' % (self.line, self.index)
# TODO: Revisit unicode encode/decode issues later.
# 1. Decode early. 2. Unicode everywhere 3. Encode late
# However, decoding filename and link_text here works for now.
fname = str(node.content).replace('%20', ' ')
link_text = str(node.children[0].content).replace('%20', ' ')
self.txtWidget.insert(self.begin_link, link_text,
self.hyperMgr.add(fname))
self.begin_link = ''
def visit_break(self, node):
txtindex = '%d.%d' % (self.line, self.index)
self.txtWidget.insert(txtindex, '\n')
def leave_break(self, node):
self.line += 1
self.index = 0
def visit_default(self, node):
"""Fallback function for visiting unknown nodes."""
raise TypeError
def leave_default(self, node):
"""Fallback function for leaving unknown nodes."""
raise TypeError
def emit_children(self, node):
"""Emit all the children of a node."""
for child in node.children:
self.emit_node(child)
def emit_node(self, node):
"""Visit/depart a single node and its children."""
visit = getattr(self, 'visit_%s' % node.kind, self.visit_default)
visit(node)
self.emit_children(node)
leave = getattr(self, 'leave_%s' % node.kind, self.leave_default)
leave(node)
def emit(self):
"""Emit the document represented by self.root DOM tree."""
return self.emit_node(self.root)
class Serializer(object):
def __init__(self, txtWidget, hyperMgr):
self.txt = txtWidget
self.hyperMgr = hyperMgr
self.bullet_image = PhotoImage(file=BULLET_IMAGE)
self._reset()
def _reset(self):
self.number = 0
self.bullet = False
self.filename = ''
self.link_start = False
self.first_tab = True
self.list_end = False
def dump(self, index1='1.0', index2=END):
# outputs contents from Text widget in Creole format.
creole = ''
self._reset()
for key, value, index in self.txt.dump(index1, index2):
if key == 'tagon':
if value == 'bold':
creole += '**'
elif value == 'italic':
creole += '//'
elif value == 'bullet':
creole += '*'
self.bullet = True
self.list_end = False
elif value.startswith('hyper-'):
self.filename = self.hyperMgr.filenames[value]
self.link_start = True
elif value == 'number':
creole += '#'
self.number += 1
elif key == 'tagoff':
if value == 'bold':
creole += '**'
elif value == 'italic':
creole += '//'
elif value.startswith('hyper-'):
creole += ']]'
elif value == 'number':
numstr = '#\t%d.\t' % self.number
if numstr in creole:
creole = creole.replace(numstr, '# ', 1)
self.list_end = True
elif value == 'bullet':
creole = creole.replace('\n*\t\t', '\n* ', 1)
self.bullet = False
self.list_end = True
elif key == 'text':
if self.link_start:
# TODO: Revisit unicode encode/decode issues later.
# 1. Decode early. 2. Unicode everywhere 3. Encode late
# However, encoding filename and link_text here works for
# now.
fname = self.filename.replace(' ', '%20').encode('utf-8')
link_text = value.replace(' ', '%20')
value = '[[%s|%s' % (fname, link_text)
self.link_start = False
numstr = '%d.\t' % self.number
if self.list_end and value != '\n' and numstr not in value:
creole += '\n'
self.number = 0
self.list_end = False
creole += value
return creole.rstrip()
def restore(self, creole):
self.hyperMgr.reset()
document = Parser(unicode(creole, 'utf-8', 'ignore')).parse()
return TextTagEmitter(document, self.txt, self.hyperMgr,
self.bullet_image).emit()
| Python |
"""Games, or Adversarial Search. (Chapters 6)
"""
from utils import infinity, argmax, argmax_random_tie, num_or_str, Dict, update
from utils import if_, Struct
import random
import time
#______________________________________________________________________________
# Minimax Search
def minimax_decision(state, game):
"""Given a state in a game, calculate the best move by searching
forward all the way to the terminal states. [Fig. 6.4]"""
player = game.to_move(state)
def max_value(state):
if game.terminal_test(state):
return game.utility(state, player)
v = -infinity
for (_, s) in game.successors(state):
v = max(v, min_value(s))
return v
def min_value(state):
if game.terminal_test(state):
return game.utility(state, player)
v = infinity
for (_, s) in game.successors(state):
v = min(v, max_value(s))
return v
# Body of minimax_decision starts here:
action, state = argmax(game.successors(state),
lambda ((a, s)): min_value(s))
return action
#______________________________________________________________________________
def alphabeta_full_search(state, game):
"""Search game to determine best action; use alpha-beta pruning.
As in [Fig. 6.7], this version searches all the way to the leaves."""
player = game.to_move(state)
def max_value(state, alpha, beta):
if game.terminal_test(state):
return game.utility(state, player)
v = -infinity
for (a, s) in game.successors(state):
v = max(v, min_value(s, alpha, beta))
if v >= beta:
return v
alpha = max(alpha, v)
return v
def min_value(state, alpha, beta):
if game.terminal_test(state):
return game.utility(state, player)
v = infinity
for (a, s) in game.successors(state):
v = min(v, max_value(s, alpha, beta))
if v <= alpha:
return v
beta = min(beta, v)
return v
# Body of alphabeta_search starts here:
action, state = argmax(game.successors(state),
lambda ((a, s)): min_value(s, -infinity, infinity))
return action
def alphabeta_search(state, game, d=4, cutoff_test=None, eval_fn=None):
"""Search game to determine best action; use alpha-beta pruning.
This version cuts off search and uses an evaluation function."""
player = game.to_move(state)
def max_value(state, alpha, beta, depth):
if cutoff_test(state, depth):
return eval_fn(state)
v = -infinity
succ = game.successors(state)
for (a, s) in succ:
v = max(v, min_value(s, alpha, beta, depth+1))
if v >= beta:
succ.close()
return v
alpha = max(alpha, v)
return v
def min_value(state, alpha, beta, depth):
if cutoff_test(state, depth):
return eval_fn(state)
v = infinity
succ = game.successors(state)
for (a, s) in succ:
v = min(v, max_value(s, alpha, beta, depth+1))
if v <= alpha:
succ.close()
return v
beta = min(beta, v)
return v
# Body of alphabeta_search starts here:
# The default test cuts off at depth d or at a terminal state
cutoff_test = (cutoff_test or
(lambda state,depth: depth>d or game.terminal_test(state)))
eval_fn = eval_fn or (lambda state: game.utility(player, state))
action, state = argmax_random_tie(game.successors(state),
lambda ((a, s)): min_value(s, -infinity,
infinity, 0))
return action
#______________________________________________________________________________
# Players for Games
def query_player(game, state):
"Make a move by querying standard input."
game.display(state)
return num_or_str(raw_input('Your move? '))
def random_player(game, state):
"A player that chooses a legal move at random."
return random.choice(game.legal_moves())
def alphabeta_player(game, state):
return alphabeta_search(state, game)
def play_game(game, *players):
"Play an n-person, move-alternating game."
print game.curr_state
while True:
for player in players:
if game.curr_state.to_move == player.color:
move = player.select_move(game)
print game.make_move(move)
if game.terminal_test():
return game.utility(player.color)
#______________________________________________________________________________
# Some Sample Games
class Game:
"""A game is similar to a problem, but it has a utility for each
state and a terminal test instead of a path cost and a goal
test. To create a game, subclass this class and implement
legal_moves, make_move, utility, and terminal_test. You may
override display and successors or you can inherit their default
methods. You will also need to set the .initial attribute to the
initial state; this can be done in the constructor."""
def legal_moves(self, state):
"Return a list of the allowable moves at this point."
abstract
def make_move(self, move, state):
"Return the state that results from making a move from a state."
abstract
def utility(self, state, player):
"Return the value of this final state to player."
abstract
def terminal_test(self, state):
"Return True if this is a final state for the game."
return not self.legal_moves(state)
def to_move(self, state):
"Return the player whose move it is in this state."
return state.to_move
def display(self, state):
"Print or otherwise display the state."
print state
def successors(self, state):
"Return a list of legal (move, state) pairs."
return [(move, self.make_move(move, state))
for move in self.legal_moves(state)]
def __repr__(self):
return '<%s>' % self.__class__.__name__
class Fig62Game(Game):
"""The game represented in [Fig. 6.2]. Serves as a simple test case.
>>> g = Fig62Game()
>>> minimax_decision('A', g)
'a1'
>>> alphabeta_full_search('A', g)
'a1'
>>> alphabeta_search('A', g)
'a1'
"""
succs = {'A': [('a1', 'B'), ('a2', 'C'), ('a3', 'D')],
'B': [('b1', 'B1'), ('b2', 'B2'), ('b3', 'B3')],
'C': [('c1', 'C1'), ('c2', 'C2'), ('c3', 'C3')],
'D': [('d1', 'D1'), ('d2', 'D2'), ('d3', 'D3')]}
utils = Dict(B1=3, B2=12, B3=8, C1=2, C2=4, C3=6, D1=14, D2=5, D3=2)
initial = 'A'
def successors(self, state):
return self.succs.get(state, [])
def utility(self, state, player):
if player == 'MAX':
return self.utils[state]
else:
return -self.utils[state]
def terminal_test(self, state):
return state not in ('A', 'B', 'C', 'D')
def to_move(self, state):
return if_(state in 'BCD', 'MIN', 'MAX')
class TicTacToe(Game):
"""Play TicTacToe on an h x v board, with Max (first player) playing 'X'.
A state has the player to move, a cached utility, a list of moves in
the form of a list of (x, y) positions, and a board, in the form of
a dict of {(x, y): Player} entries, where Player is 'X' or 'O'."""
def __init__(self, h=3, v=3, k=3):
update(self, h=h, v=v, k=k)
moves = [(x, y) for x in range(1, h+1)
for y in range(1, v+1)]
self.initial = Struct(to_move='X', utility=0, board={}, moves=moves)
def legal_moves(self, state):
"Legal moves are any square not yet taken."
return state.moves
def make_move(self, move, state):
if move not in state.moves:
return state # Illegal move has no effect
board = state.board.copy(); board[move] = state.to_move
moves = list(state.moves); moves.remove(move)
return Struct(to_move=if_(state.to_move == 'X', 'O', 'X'),
utility=self.compute_utility(board, move, state.to_move),
board=board, moves=moves)
def utility(self, state):
"Return the value to X; 1 for win, -1 for loss, 0 otherwise."
return state.utility
def terminal_test(self, state):
"A state is terminal if it is won or there are no empty squares."
return state.utility != 0 or len(state.moves) == 0
def display(self, state):
board = state.board
for x in range(1, self.h+1):
for y in range(1, self.v+1):
print board.get((x, y), '.'),
print
def compute_utility(self, board, move, player):
"If X wins with this move, return 1; if O return -1; else return 0."
if (self.k_in_row(board, move, player, (0, 1)) or
self.k_in_row(board, move, player, (1, 0)) or
self.k_in_row(board, move, player, (1, -1)) or
self.k_in_row(board, move, player, (1, 1))):
return if_(player == 'X', +1, -1)
else:
return 0
def k_in_row(self, board, move, player, (delta_x, delta_y)):
"Return true if there is a line through move on board for player."
x, y = move
n = 0 # n is number of moves in row
while board.get((x, y)) == player:
n += 1
x, y = x + delta_x, y + delta_y
x, y = move
while board.get((x, y)) == player:
n += 1
x, y = x - delta_x, y - delta_y
n -= 1 # Because we counted move itself twice
return n >= self.k
class ConnectFour(TicTacToe):
"""A TicTacToe-like game in which you can only make a move on the bottom
row, or in a square directly above an occupied square. Traditionally
played on a 7x6 board and requiring 4 in a row."""
def __init__(self, h=7, v=6, k=4):
TicTacToe.__init__(self, h, v, k)
def legal_moves(self, state):
"Legal moves are any square not yet taken."
return [(x, y) for (x, y) in state.moves
if y == 0 or (x, y-1) in state.board]
| Python |
class DocNode(object):
"""
A node in the document.
"""
def __init__(self, kind='', parent=None, content=None):
self.children = []
self.parent = parent
self.kind = kind
self.content = content
if self.parent is not None:
self.parent.children.append(self)
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.