|
From: <li...@us...> - 2008-10-15 10:15:43
|
Revision: 547
http://pyphant.svn.sourceforge.net/pyphant/?rev=547&view=rev
Author: liehr
Date: 2008-10-15 10:15:34 +0000 (Wed, 15 Oct 2008)
Log Message:
-----------
viewOSC visualizes the thickness map
Setting parameter '-v thicknessMap' shows the thickness map of the
investigated sample. Furthermore the position of the absorption curve,
which is specified by parameter -n, is indicated by plotting a cross at the
respective position. For this purpose
the coordinate system of the thickness map is shifted by -(stepX,stepY),
such that the cross marks the center of the respective pixel.
Modified Paths:
--------------
trunk/doc/demo/viewOSC.py
trunk/src/workers/OSC/OSC/OscAbsorption.py
Modified: trunk/doc/demo/viewOSC.py
===================================================================
--- trunk/doc/demo/viewOSC.py 2008-10-14 15:23:47 UTC (rev 546)
+++ trunk/doc/demo/viewOSC.py 2008-10-15 10:15:34 UTC (rev 547)
@@ -81,8 +81,13 @@
import pyphant.core.PyTablesPersister
+visualizer = None
from optparse import OptionParser
+visualizationThemes = ("compareAbsorption",
+ "noisyAbsorption",
+ "thicknessMap")
+
parser = OptionParser(usage="usage: %prog [options] path2recipe")
parser.add_option("-n", "--number", dest="curvNo",type='long',
@@ -91,7 +96,7 @@
help="Frequency range to use for data slicing.", metavar="FREQRANGE", default=None)
parser.add_option("-s", "--scale", dest="scale", type="str",
help="Scale parameter", metavar="SCALE", default=None)
-visualizationThemes = ("compareAbsorption","noisyAbsorption")
+
parser.add_option("-v", "--visualize", dest="theme", type="choice",choices = visualizationThemes,
help="Choose visualization theme from %s" % str(visualizationThemes),
metavar="THEME", default=visualizationThemes[0])
@@ -114,9 +119,9 @@
#Get Absorption
worker = recipe.getWorkers("Slicing")[0]
if freqRange != None:
- print freqRange, worker.paramDim1.value
- worker.paramDim1.value=freqRange
-noisyAbsorption = worker.plugExtract.getResult()
+ print freqRange, worker.paramDim1.value
+ worker.paramDim1.value=freqRange
+ noisyAbsorption = worker.plugExtract.getResult()
#Get Simulation
worker = recipe.getWorkers("Coat Thickness Model")[0]
@@ -126,6 +131,11 @@
worker = recipe.getWorkers("Multi Resolution Analyser")[0]
worker.paramScale.value=scale
+if theme == visualizationThemes[2]:
+ worker = recipe.getWorkers("Osc Mapper")[0]
+ worker.plugMapHeights.invalidate()
+ oscMap = worker.plugMapHeights.getResult()
+
#Get EstimatedWidth
worker = recipe.getWorkers("Add Column")[0]
table = worker.plugCompute.getResult(subscriber=TextSubscriber("Add Column"))
@@ -181,8 +191,6 @@
pylab.axes([left,bottom,right-left,top-bottom])
if theme == visualizationThemes[0]:
-
-
pylab.plot(noisyAbsorption.dimensions[1].inUnitsOf(simulation.dimensions[1]).data,
noisyAbsorption.data[curvNo,:],label="$%s$"%noisyAbsorption.shortname)
pylab.plot(simulation.dimensions[1].data,
@@ -195,13 +203,25 @@
elif theme == visualizationThemes[1]:
pylab.plot(noisyAbsorption.dimensions[1].inUnitsOf(simulation.dimensions[1]).data,
noisyAbsorption.data[curvNo,:],label="$%s$"%noisyAbsorption.shortname)
+ pylab.vlines(minimaPos.data[:,curvNo],0.1,1.0,
+ label ="$%s$"%minimaPos.shortname)
pylab.title(result)
pylab.xlabel(simulation.dimensions[1].label)
pylab.ylabel(simulation.label)
-
+
+elif theme == visualizationThemes[2]:
+ from pyphant.visualizers.ImageVisualizer import ImageVisualizer
+ visualizer = ImageVisualizer(oscMap)
+ pylab.plot([xPos.data[curvNo]],[yPos.data[curvNo]],'xk',scalex=False,scaley=False)
+
+
if options.postscript:
from os.path import basename
- pylab.savefig('%s-%s-n%s.eps' % (basename(pathToRecipe)[:-3],theme,curvNo))
+ filename = '%s-%s-n%s.eps' % (basename(pathToRecipe)[:-3],theme,curvNo)
+ if visualizer:
+ visualizer.figure.savefig(filename)
+ else:
+ pylab.savefig(filename)
else:
pylab.show()
Modified: trunk/src/workers/OSC/OSC/OscAbsorption.py
===================================================================
--- trunk/src/workers/OSC/OSC/OscAbsorption.py 2008-10-14 15:23:47 UTC (rev 546)
+++ trunk/src/workers/OSC/OSC/OscAbsorption.py 2008-10-15 10:15:34 UTC (rev 547)
@@ -179,9 +179,9 @@
yOff, yStep, yInd = grid2Index(yf, self.paramExtentY.value)
xMax = xInd.maxV
yMax = yInd.maxV
- xDim = DataContainer.FieldContainer( numpy.linspace(xInd.minV,xInd.maxV,xInd.stepCount), xCon.unit,
+ xDim = DataContainer.FieldContainer( numpy.linspace(xInd.minV,xInd.maxV,xInd.stepCount)-0.5*xStep, xCon.unit,
longname = xCon.longname, shortname = xCon.shortname )
- yDim = DataContainer.FieldContainer( numpy.linspace(yInd.minV,yInd.maxV,yInd.stepCount), yCon.unit,
+ yDim = DataContainer.FieldContainer( numpy.linspace(yInd.minV,yInd.maxV,yInd.stepCount)-0.5*yStep, yCon.unit,
longname = yCon.longname, shortname = yCon.shortname )
img = numpy.ones((yInd.stepCount, xInd.stepCount), dtype='float')*numpy.NaN
mask = numpy.ones((yInd.stepCount, xInd.stepCount), dtype='bool')
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <zk...@us...> - 2008-10-29 14:40:09
|
Revision: 562
http://pyphant.svn.sourceforge.net/pyphant/?rev=562&view=rev
Author: zklaus
Date: 2008-10-29 14:40:05 +0000 (Wed, 29 Oct 2008)
Log Message:
-----------
Parser realizing the 1.0 specification of the Full-Metadata-Format
The flexibility of the Full-Metadata-Format is demonstrated on basis of the example file
doc/demo/example.fmf. The parser determines appropriate data types both for metadata
and data columns.
Modified Paths:
--------------
trunk/src/workers/fmfile/fmfile/FMFLoader2.py
Added Paths:
-----------
trunk/doc/demo/example.fmf
trunk/doc/demo/readfmf.py
Added: trunk/doc/demo/example.fmf
===================================================================
--- trunk/doc/demo/example.fmf (rev 0)
+++ trunk/doc/demo/example.fmf 2008-10-29 14:40:05 UTC (rev 562)
@@ -0,0 +1,55 @@
+# -*- fmf-version: 1.0; coding: utf-8 -*-
+[*reference]
+title: Demonstrating the flexibility of the Full-Metadata-Format
+creator: Andreas W. Liehr
+created: 2008-10-29
+place: Freiburger Materialforschungszentrum, Universität Freiburg, Deutschland
+[String Examples]
+word: Hello!
+sentence: Hello World!
+comma separated list: world, die Welt, el mundo, monde
+multiline: '''A multiline value,
+that spans more than one line :-)
+The line breaks are included in the value.'''
+[Numbers]
+#Note, that the 'key' is arbitrary, but has to be unique within a section
+integer: 1
+float: 1.0
+float with leading dot: .1
+float with exponential: 1e-10
+float with Exponential: -1.1E10
+complex: 1+2j
+[Physical Quantities]
+number: N = 2
+voltage: U = 1V
+temperature in Celsius: T_C = 22 degC
+temperature in Fahrenheit: T = 22 degF
+[Physical Quantities with error]
+voltage: U = 1 V +- 1 mV
+current: I = 1 A +/- 0.001 A
+energy: E = 1 J \pm 1 mJ
+work: A = 1 W +- 0.1%
+voltage in brackets: U = (1 +- 0.001) V
+current in brackets: I = (1 +- 0.1%) A
+estimated parameter: p = 1 \pm 0.1
+another estimated parameter: p = 1 \pm 1%
+[*table definitions]
+table: T
+mixed: M
+[*data definitions: T]
+String: S
+Integer: I
+Float with dot: Fd
+Float with exponent: Fe
+Complex: C
+[*data: T]
+H_2 1 1. 1e1 1+0j
+O_2 2 .2 2E1 2+.1j
+O 2 2 .2 2E1 2+.1j
+[*data definitions: M]
+String: S
+Complex: C
+Float: F
+[*data: M]
+N_2 1 2
+2 1+1j 2.1
Added: trunk/doc/demo/readfmf.py
===================================================================
--- trunk/doc/demo/readfmf.py (rev 0)
+++ trunk/doc/demo/readfmf.py 2008-10-29 14:40:05 UTC (rev 562)
@@ -0,0 +1,7 @@
+from fmfile.FMFLoader2 import FMFLoader2
+
+worker = FMFLoader2()
+worker.paramFilename.value='example.fmf'
+result = worker.plugLoadFMF.getResult()
+print result
+print result.attributes
Modified: trunk/src/workers/fmfile/fmfile/FMFLoader2.py
===================================================================
--- trunk/src/workers/fmfile/fmfile/FMFLoader2.py 2008-10-29 10:33:20 UTC (rev 561)
+++ trunk/src/workers/fmfile/fmfile/FMFLoader2.py 2008-10-29 14:40:05 UTC (rev 562)
@@ -249,29 +249,41 @@
return unit
def item2value(section, key):
- pm = re.compile(ur"(?:\\pm|\+/?-)")
+ pm = re.compile(ur"(?:\\pm|\+-|\+/-)")
oldVal = section[key]
try:
shortname, value = tuple([s.strip() for s in oldVal.split('=')])
try:
value, error = [s.strip() for s in pm.split(value)]
- if value.startswith('('):
- value = float(value[1:])
- error, unit = [s.strip() for s in error.split(')')]
- if error.endswith('%'):
- error = value*float(error[:-1])/100.0
- else:
- error = float(error)
- unit = str2unit(unit)
- value *= unit
- error *= unit
- return (shortname, value, error)
except:
- error = str2unit(error)
- value = str2unit(value)
- return (shortname, value, error)
+ error = None
+ if value.startswith('('):
+ value = float(value[1:])
+ error, unit = [s.strip() for s in error.split(')')]
+ unit = str2unit(unit)
+ value *= unit
+ else:
+ value = str2unit(value)
+ if error != None:
+ if error.endswith('%'):
+ error = value*float(error[:-1])/100.0
+ else:
+ try:
+ error = float(error)*unit
+ except:
+ error = str2unit(error)
+ return (shortname, value, error)
except:
- pass
+ try:
+ return int(oldVal)
+ except:
+ try:
+ return float(oldVal)
+ except:
+ try:
+ return complex(oldVal)
+ except:
+ pass
return oldVal
if config.has_key('*table definitions'):
@@ -297,6 +309,19 @@
return tables
def data2table(longname, shortname, preParsedData, config):
+ datTable = []
+ for col in preParsedData:
+ try:
+ result = col.astype('i')
+ except ValueError,e:
+ try:
+ result = col.astype('f')
+ except ValueError,e:
+ try:
+ result = col.astype('complex')
+ except ValueError,e:
+ result = col
+ datTable.append(result)
colspec_re = re.compile(ur"(?P<shortname>[^\s([]*)\s*(?P<deps>\([^)]*\))?\s*(?:(?:\\pm|\+-|\+/-)\s*(?P<error>[^\s[]*))?\s*(?P<unit>\[[^]]*])?")
fields = []
fields_by_name = {}
@@ -325,7 +350,7 @@
else:
dimensions_for_fields[fieldShortname] = None
errors_for_fields[fieldShortname] = match.group('error')
- field = DataContainer.FieldContainer(preParsedData[i],
+ field = DataContainer.FieldContainer(datTable[i],
longname=fieldLongname,
shortname=fieldShortname,
unit=unit)
@@ -366,7 +391,7 @@
preParsedData = {}
def preParseData(match):
try:
- preParsedData[match.group(2)] = numpy.loadtxt(StringIO.StringIO(match.group(3)), unpack=True, comments=';')
+ preParsedData[match.group(2)] = numpy.loadtxt(StringIO.StringIO(match.group(3)), unpack=True, comments=commentChar,dtype='S',delimiter='\t')
except Exception, e:
return match.group(0)
return u""
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <li...@us...> - 2008-10-31 05:40:22
|
Revision: 565
http://pyphant.svn.sourceforge.net/pyphant/?rev=565&view=rev
Author: liehr
Date: 2008-10-31 05:40:11 +0000 (Fri, 31 Oct 2008)
Log Message:
-----------
Introduced FMF-variable 'delimiter', specifying the numpy.loadtxt delimiter.
Modified Paths:
--------------
trunk/src/workers/fmfile/fmfile/FMFLoader2.py
Added Paths:
-----------
trunk/doc/demo/example_delimiter.fmf
Added: trunk/doc/demo/example_delimiter.fmf
===================================================================
--- trunk/doc/demo/example_delimiter.fmf (rev 0)
+++ trunk/doc/demo/example_delimiter.fmf 2008-10-31 05:40:11 UTC (rev 565)
@@ -0,0 +1,56 @@
+# -*- fmf-version: 1.0; coding: utf-8; delimiter: space -*-
+[*reference]
+title: Demonstrating the flexibility of the Full-Metadata-Format
+creator: Andreas W. Liehr
+created: 2008-10-29
+place: Freiburger Materialforschungszentrum, Universität Freiburg, Deutschland
+[String Examples]
+word: Hello!
+sentence: Hello World!
+comma separated list: world, die Welt, el mundo, monde
+multiline: '''A multiline value,
+that spans more than one line :-)
+The line breaks are included in the value.'''
+[Numbers]
+#Note, that the 'key' is arbitrary, but has to be unique within a section
+integer: 1
+float: 1.0
+float with leading dot: .1
+float with exponential: 1e-10
+float with Exponential: -1.1E10
+complex: 1+2j
+[Physical Quantities]
+number: N = 2
+voltage: U = 1V
+temperature in Celsius: T_C = 22 degC
+temperature in Fahrenheit: T = 22 degF
+[Physical Quantities with error]
+voltage: U = 1 V +- 1 mV
+current: I = 1 A +/- 0.001 A
+energy: E = 1 J \pm 1 mJ
+work: A = 1 W +- 0.1%
+voltage in brackets: U = (1 +- 0.001) V
+current in brackets: I = (1 +- 0.1%) A
+estimated parameter: p = 1 \pm 0.1
+another estimated parameter: p = 1 \pm 1%
+[*table definitions]
+table: T
+mixed: M
+[*data definitions: T]
+String: S
+Integer: I
+Float with dot: Fd
+Float with exponent: Fe
+Complex: C
+Missing Value: V_m
+Infinite Value: V_i
+[*data: T]
+H_2 1 1. 1e1 1+0j nan inf
+O_2 2 .2 2E1 2+.1j NaN INF
+[*data definitions: M]
+String: S
+Complex: C
+Float: F
+[*data: M]
+N_2 1 2
+2 1+1j 2.1
Modified: trunk/src/workers/fmfile/fmfile/FMFLoader2.py
===================================================================
--- trunk/src/workers/fmfile/fmfile/FMFLoader2.py 2008-10-31 05:39:41 UTC (rev 564)
+++ trunk/src/workers/fmfile/fmfile/FMFLoader2.py 2008-10-31 05:40:11 UTC (rev 565)
@@ -377,13 +377,16 @@
def preParseData(b):
- localVar = {'fmf-version':'1.0','coding':'cp1252'}
+ localVar = {'fmf-version':'1.0','coding':'cp1252',
+ 'delimiter':'\t'}
commentChar = ';'
if b[0] == ';' or b[0] == '#':
commentChar = b[0]
items = [var.strip().split(':') for var in b.split('-*-')[1].split(';')]
for key,value in items:
localVar[key.strip()]=value.strip()
+ if localVar[key.strip()]=='space':
+ localVar[key.strip()] = ' '
d = unicode(b, localVar['coding'])
dataExpr = re.compile(ur"^(\[\*data(?::\s*([^\]]*))?\]\r?\n)([^[]*)", re.MULTILINE | re.DOTALL)
commentExpr = re.compile(ur"^%s.*"%commentChar, re.MULTILINE)
@@ -391,7 +394,11 @@
preParsedData = {}
def preParseData(match):
try:
- preParsedData[match.group(2)] = numpy.loadtxt(StringIO.StringIO(match.group(3)), unpack=True, comments=commentChar,dtype='S',delimiter='\t')
+ preParsedData[match.group(2)] = numpy.loadtxt(StringIO.StringIO(match.group(3)),
+ unpack=True,
+ comments=commentChar,
+ dtype='S',
+ delimiter=localVar['delimiter'])
except Exception, e:
return match.group(0)
return u""
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <li...@us...> - 2008-11-01 14:56:24
|
Revision: 566
http://pyphant.svn.sourceforge.net/pyphant/?rev=566&view=rev
Author: liehr
Date: 2008-11-01 14:56:20 +0000 (Sat, 01 Nov 2008)
Log Message:
-----------
Variable delimiter in FMF headline can be explicitely set to 'whitespace'.
Modified Paths:
--------------
trunk/doc/demo/example_delimiter.fmf
trunk/src/workers/fmfile/fmfile/FMFLoader2.py
Modified: trunk/doc/demo/example_delimiter.fmf
===================================================================
--- trunk/doc/demo/example_delimiter.fmf 2008-10-31 05:40:11 UTC (rev 565)
+++ trunk/doc/demo/example_delimiter.fmf 2008-11-01 14:56:20 UTC (rev 566)
@@ -1,4 +1,4 @@
-# -*- fmf-version: 1.0; coding: utf-8; delimiter: space -*-
+# -*- fmf-version: 1.0; coding: utf-8; delimiter: whitespace -*-
[*reference]
title: Demonstrating the flexibility of the Full-Metadata-Format
creator: Andreas W. Liehr
Modified: trunk/src/workers/fmfile/fmfile/FMFLoader2.py
===================================================================
--- trunk/src/workers/fmfile/fmfile/FMFLoader2.py 2008-10-31 05:40:11 UTC (rev 565)
+++ trunk/src/workers/fmfile/fmfile/FMFLoader2.py 2008-11-01 14:56:20 UTC (rev 566)
@@ -385,8 +385,8 @@
items = [var.strip().split(':') for var in b.split('-*-')[1].split(';')]
for key,value in items:
localVar[key.strip()]=value.strip()
- if localVar[key.strip()]=='space':
- localVar[key.strip()] = ' '
+ if localVar[key.strip()]=='whitespace':
+ localVar[key.strip()] = None
d = unicode(b, localVar['coding'])
dataExpr = re.compile(ur"^(\[\*data(?::\s*([^\]]*))?\]\r?\n)([^[]*)", re.MULTILINE | re.DOTALL)
commentExpr = re.compile(ur"^%s.*"%commentChar, re.MULTILINE)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <li...@us...> - 2008-11-01 14:57:04
|
Revision: 569
http://pyphant.svn.sourceforge.net/pyphant/?rev=569&view=rev
Author: liehr
Date: 2008-11-01 14:57:01 +0000 (Sat, 01 Nov 2008)
Log Message:
-----------
Enhanced list handling of FMFLoader2, extended example.fmf.
The FMFLoader2 returns lists of integer, float and complex whenever appropriate.
To reflect the new capabilities example.fmf has been extended.
Modified Paths:
--------------
trunk/doc/demo/example.fmf
trunk/src/workers/fmfile/fmfile/FMFLoader2.py
Modified: trunk/doc/demo/example.fmf
===================================================================
--- trunk/doc/demo/example.fmf 2008-11-01 14:56:44 UTC (rev 568)
+++ trunk/doc/demo/example.fmf 2008-11-01 14:57:01 UTC (rev 569)
@@ -4,21 +4,32 @@
creator: Andreas W. Liehr
created: 2008-10-29
place: Freiburger Materialforschungszentrum, Universität Freiburg, Deutschland
-[String Examples]
+ort: "Freiburger Materialforschungszentrum, Universität Freiburg, Deutschland"
+[Textual values]
word: Hello!
sentence: Hello World!
+timestamp: 2008-10-31 12:00:59.438151
comma separated list: world, die Welt, el mundo, monde
multiline: '''A multiline value,
that spans more than one line :-)
The line breaks are included in the value.'''
-[Numbers]
+Another multiline: """A multiline value,
+that spans more than one line :-)"""
+Enclosed quotation marks: """ Andreas says: "Hello World!" """
+[Numerical values]
#Note, that the 'key' is arbitrary, but has to be unique within a section
integer: 1
+list of integers: 1, 2, 3, 4, 5
float: 1.0
float with leading dot: .1
float with exponential: 1e-10
float with Exponential: -1.1E10
+list of floats: 1.0, .1, 1e-10, -1.1E10
complex: 1+2j
+Complex: 1+2J
+Complex number with zero real part : 2J
+Complex number with zero imaginary part: 1+0J
+list of complex: 1+2j, 1+2J
[Physical Quantities]
number: N = 2
voltage: U = 1V
@@ -47,7 +58,7 @@
[*data: T]
H_2 1 1. 1e1 1+0j nan inf
O_2 2 .2 2E1 2+.1j NaN INF
-O 2 2 .2 2E1 2+.1j NAN Inf
+O 2 2 .2 2E1 2+.1J NAN Inf
[*data definitions: M]
String: S
Complex: C
Modified: trunk/src/workers/fmfile/fmfile/FMFLoader2.py
===================================================================
--- trunk/src/workers/fmfile/fmfile/FMFLoader2.py 2008-11-01 14:56:44 UTC (rev 568)
+++ trunk/src/workers/fmfile/fmfile/FMFLoader2.py 2008-11-01 14:57:01 UTC (rev 569)
@@ -274,16 +274,29 @@
error = str2unit(error)
return (shortname, value, error)
except:
- try:
- return int(oldVal)
- except:
+ if type(oldVal)==type([]):
try:
- return float(oldVal)
+ return map(int,oldVal)
except:
- try:
- return complex(oldVal)
+ try:
+ return map(float,oldVal)
except:
- pass
+ try:
+ return map(complex,oldVal)
+ except:
+ pass
+ else:
+ try:
+ return int(oldVal)
+ except:
+ try:
+ return float(oldVal)
+ except:
+ try:
+ return complex(oldVal)
+ except:
+ pass
+
return oldVal
if config.has_key('*table definitions'):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <li...@us...> - 2008-11-01 15:55:58
|
Revision: 570
http://pyphant.svn.sourceforge.net/pyphant/?rev=570&view=rev
Author: liehr
Date: 2008-11-01 15:55:56 +0000 (Sat, 01 Nov 2008)
Log Message:
-----------
FMFLoader2 bugfix: Units in LaTeX notation are also recognized in the metadata sections.
Modified Paths:
--------------
trunk/doc/demo/example.fmf
trunk/src/workers/fmfile/fmfile/FMFLoader2.py
Modified: trunk/doc/demo/example.fmf
===================================================================
--- trunk/doc/demo/example.fmf 2008-11-01 14:57:01 UTC (rev 569)
+++ trunk/doc/demo/example.fmf 2008-11-01 15:55:56 UTC (rev 570)
@@ -35,6 +35,8 @@
voltage: U = 1V
temperature in Celsius: T_C = 22 degC
temperature in Fahrenheit: T = 22 degF
+resistance: \omega = 2.0 kg*m^2*A^-2*s^-3
+resistance 2: \omega = 2.0 kg*m**2*A**-2*s**-3
[Physical Quantities with error]
voltage: U = 1 V +- 1 mV
current: I = 1 A +/- 0.001 A
@@ -42,6 +44,8 @@
work: A = 1 W +- 0.1%
voltage in brackets: U = (1 +- 0.001) V
current in brackets: I = (1 +- 0.1%) A
+trailing amplitude: \omega = (1 +- 0.01) 2 ohm
+trailing amplitude, relative error: \omega = (1 +- 1%) 2 ohm
estimated parameter: p = 1 \pm 0.1
another estimated parameter: p = 1 \pm 1%
[*table definitions]
Modified: trunk/src/workers/fmfile/fmfile/FMFLoader2.py
===================================================================
--- trunk/src/workers/fmfile/fmfile/FMFLoader2.py 2008-11-01 14:57:01 UTC (rev 569)
+++ trunk/src/workers/fmfile/fmfile/FMFLoader2.py 2008-11-01 15:55:56 UTC (rev 570)
@@ -243,7 +243,7 @@
elif not unit[0].isdigit():
unit = '1'+unit
try:
- unit = PhysicalQuantity(unit.encode('utf-8'))
+ unit = PhysicalQuantity(unit.encode('utf-8').replace('^','**'))
except:
unit = float(unit)
return unit
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <li...@us...> - 2008-12-05 12:22:17
|
Revision: 580
http://pyphant.svn.sourceforge.net/pyphant/?rev=580&view=rev
Author: liehr
Date: 2008-12-05 11:45:47 +0000 (Fri, 05 Dec 2008)
Log Message:
-----------
Enhanced method .getWorkers of CompositeWorker class
If a recipe contains several workers from the same worker class
a specific worker can be selected via the .getWorker() method
by naming its precursor worker.
Modified Paths:
--------------
trunk/doc/demo/viewOSC.py
trunk/src/pyphant/pyphant/core/CompositeWorker.py
Modified: trunk/doc/demo/viewOSC.py
===================================================================
--- trunk/doc/demo/viewOSC.py 2008-12-05 11:45:16 UTC (rev 579)
+++ trunk/doc/demo/viewOSC.py 2008-12-05 11:45:47 UTC (rev 580)
@@ -125,7 +125,7 @@
worker = recipe.getWorkers("Slicing")[0]
worker.paramDim1.value=freqRange
if scale != None:
- worker = recipe.getWorkers("Multi Resolution Analyser")[0]
+ worker = recipe.getWorkers("Multi Resolution Analyser","Slicing")[0]
worker.paramScale.value=scale
def initPylab(postscript):
@@ -170,7 +170,7 @@
noisyAbsorption = worker.plugExtract.getResult()
worker = recipe.getWorkers("Coat Thickness Model")[0]
simulation = worker.plugCalcAbsorption.getResult()
- worker = recipe.getWorkers("Multi Resolution Analyser")[0]
+ worker = recipe.getWorkers("Multi Resolution Analyser","Slicing")[0]
minimaPos = worker.plugMra.getResult().inUnitsOf(simulation.dimensions[1])
worker = recipe.getWorkers("Add Column")[0]
table = worker.plugCompute.getResult(subscriber=TextSubscriber("Add Column"))
@@ -204,7 +204,7 @@
noisyAbsorption = worker.plugExtract.getResult()
worker = recipe.getWorkers("Coat Thickness Model")[0]
simulation = worker.plugCalcAbsorption.getResult()
- worker = recipe.getWorkers("Multi Resolution Analyser")[0]
+ worker = recipe.getWorkers("Multi Resolution Analyser","Slicing")[0]
minimaPos = worker.plugMra.getResult().inUnitsOf(simulation.dimensions[1])
worker = recipe.getWorkers("Add Column")[0]
table = worker.plugCompute.getResult(subscriber=TextSubscriber("Add Column"))
@@ -242,7 +242,7 @@
functional = worker.plugCompute.getResult()
worker = recipe.getWorkers("Coat Thickness Model")[0]
simulation = worker.plugCalcAbsorption.getResult()
- worker = recipe.getWorkers("Multi Resolution Analyser")[0]
+ worker = recipe.getWorkers("Multi Resolution Analyser","Slicing")[0]
minimaPos = worker.plugMra.getResult().inUnitsOf(simulation.dimensions[1])
worker = recipe.getWorkers("Add Column")[0]
table = worker.plugCompute.getResult(subscriber=TextSubscriber("Add Column"))
@@ -264,7 +264,7 @@
table = worker.plugCompute.getResult(subscriber=TextSubscriber("Add Column"))
thickness = table[u"thickness"]
index = curvNo2Index(table[u"pixel"], curvNo)
- worker = recipe.getWorkers("Multi Resolution Analyser")[0]
+ worker = recipe.getWorkers("Multi Resolution Analyser","Slicing")[0]
minimaPos = worker.plugMra.getResult().inUnitsOf(simulation.dimensions[1])
visualizer = ImageVisualizer(simulation, False)
ordinate = simulation.dimensions[1].data
@@ -285,7 +285,7 @@
yPos = table[u"vertical_table_position"]
thickness = table[u"thickness"]
cols = [index, xPos, yPos, thickness]
- worker = recipe.getWorkers("Multi Resolution Analyser")[0]
+ worker = recipe.getWorkers("Multi Resolution Analyser","Slicing")[0]
minimaPos = worker.plugMra.getResult().inUnitsOf(simulation.dimensions[1])
import numpy
data = numpy.vstack([ c.data for c in cols]
Modified: trunk/src/pyphant/pyphant/core/CompositeWorker.py
===================================================================
--- trunk/src/pyphant/pyphant/core/CompositeWorker.py 2008-12-05 11:45:16 UTC (rev 579)
+++ trunk/src/pyphant/pyphant/core/CompositeWorker.py 2008-12-05 11:45:47 UTC (rev 580)
@@ -110,13 +110,18 @@
self._sinks.remove(worker)
self._notifyListeners(WorkerRemovedEvent(worker, data))
- def getWorkers(self,desiredWorker=''):
+ def getWorkers(self,desiredWorker='',precursor=None):
if desiredWorker == '':
result = self._workers
else:
result = [w for w in self._workers if w.name == desiredWorker]
if result == []:
raise ValueError, "Recipe does not contain Worker %s" % desiredWorker
+ if precursor:
+ result = [worker for worker in result
+ if precursor in
+ [socket._plug.worker.name for socket in worker.getSockets()]
+ ]
return result
def getSources(self):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <li...@us...> - 2008-12-08 14:42:48
|
Revision: 582
http://pyphant.svn.sourceforge.net/pyphant/?rev=582&view=rev
Author: liehr
Date: 2008-12-08 14:42:45 +0000 (Mon, 08 Dec 2008)
Log Message:
-----------
FMFLoader accepts 'a.u.' or 'A.U.' as abbreviation of 'arbitrary units'.
Modified Paths:
--------------
trunk/doc/demo/readfmf.py
trunk/src/workers/fmfile/fmfile/FMFLoader.py
Modified: trunk/doc/demo/readfmf.py
===================================================================
--- trunk/doc/demo/readfmf.py 2008-12-05 11:46:43 UTC (rev 581)
+++ trunk/doc/demo/readfmf.py 2008-12-08 14:42:45 UTC (rev 582)
@@ -1,7 +1,13 @@
-from fmfile.FMFLoader2 import FMFLoader2
+import sys
+from fmfile.FMFLoader import FMFLoader
-worker = FMFLoader2()
-worker.paramFilename.value='example.fmf'
-result = worker.plugLoadFMF.getResult()
-print result
-print result.attributes
+worker = FMFLoader()
+if len(sys.argv) == 1:
+ filenames = ['example.fmf']
+else:
+ filenames = sys.argv[1:]
+for filename in filenames:
+ worker.paramFilename.value=filename
+ result = worker.plugLoadFMF.getResult()
+ print result
+ print result.attributes
Modified: trunk/src/workers/fmfile/fmfile/FMFLoader.py
===================================================================
--- trunk/src/workers/fmfile/fmfile/FMFLoader.py 2008-12-05 11:46:43 UTC (rev 581)
+++ trunk/src/workers/fmfile/fmfile/FMFLoader.py 2008-12-08 14:42:45 UTC (rev 582)
@@ -353,6 +353,8 @@
unit = '0'+unit
elif unit == '%':
unit = 0.01
+ elif unit == 'a.u.' or unit == 'A.U.':
+ unit = 1.0
elif not unit[0].isdigit():
unit = '1'+unit
try:
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <li...@us...> - 2008-12-10 12:35:04
|
Revision: 586
http://pyphant.svn.sourceforge.net/pyphant/?rev=586&view=rev
Author: liehr
Date: 2008-12-10 12:34:54 +0000 (Wed, 10 Dec 2008)
Log Message:
-----------
Bugfix Skeletonize worker
The Skeletonize worker correctly handles curved and regular features
correctly by selecting all pixel for which rules I, II and III apply.
These pixels are checked one by one for rule IV and an additional fifth rule (a pixel can be removed if was not
located diagonally to a corner feature pixel in the previous iteration).
Pixel which do not pass this test in the first run are checked within a
second run against rules IV and V.
Modified Paths:
--------------
trunk/src/workers/ImageProcessing/ImageProcessing/SkeletonizeFeature.py
trunk/src/workers/ImageProcessing/ImageProcessing/tests/TestSkeletonizeFeature.py
Added Paths:
-----------
trunk/doc/demo/features.png
Removed Paths:
-------------
trunk/src/workers/ImageProcessing/ImageProcessing/tests/demo.png
Added: trunk/doc/demo/features.png
===================================================================
--- trunk/doc/demo/features.png (rev 0)
+++ trunk/doc/demo/features.png 2008-12-10 12:34:54 UTC (rev 586)
@@ -0,0 +1,14 @@
+\x89PNG
+
+ |
|
From: <li...@us...> - 2008-12-11 10:14:26
|
Revision: 587
http://pyphant.svn.sourceforge.net/pyphant/?rev=587&view=rev
Author: liehr
Date: 2008-12-11 10:14:14 +0000 (Thu, 11 Dec 2008)
Log Message:
-----------
Readfmf.py prints error messages of fmf-parser to stdout.
Modified Paths:
--------------
trunk/doc/demo/readfmf.py
trunk/src/workers/fmfile/fmfile/FMFLoader.py
Modified: trunk/doc/demo/readfmf.py
===================================================================
--- trunk/doc/demo/readfmf.py 2008-12-10 12:34:54 UTC (rev 586)
+++ trunk/doc/demo/readfmf.py 2008-12-11 10:14:14 UTC (rev 587)
@@ -1,4 +1,8 @@
import sys
+import logging
+logging.basicConfig(level=logging.WARNING,
+ format="%(asctime)s - %(levelname)s:%(name)s:%(thread)d:%(module)s.%(funcName)s(l %(lineno)d):%(message)s")
+
from fmfile.FMFLoader import FMFLoader
worker = FMFLoader()
Modified: trunk/src/workers/fmfile/fmfile/FMFLoader.py
===================================================================
--- trunk/src/workers/fmfile/fmfile/FMFLoader.py 2008-12-10 12:34:54 UTC (rev 586)
+++ trunk/src/workers/fmfile/fmfile/FMFLoader.py 2008-12-11 10:14:14 UTC (rev 587)
@@ -44,7 +44,6 @@
import logging
_logger = logging.getLogger("pyphant")
-
def normation(normationStr):
try:
unit = PhysicalQuantity(str(normationStr))
@@ -345,7 +344,10 @@
dimensions_for_fields = {}
errors_for_fields = {}
for i, (fieldLongname, spec) in enumerate(config.items()):
- match = re.search(colspec_re, spec)
+ try:
+ match = re.search(colspec_re, spec)
+ except TypeError,e:
+ _logger.error("""Cannot interpret definition of data column "%s", which is given as "%s"!""" % (fieldLongname,spec))
unit = match.group('unit')
if unit != None:
unit = unit[1:-1]
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <zk...@us...> - 2008-12-16 10:48:20
|
Revision: 588
http://pyphant.svn.sourceforge.net/pyphant/?rev=588&view=rev
Author: zklaus
Date: 2008-12-16 10:48:16 +0000 (Tue, 16 Dec 2008)
Log Message:
-----------
Refactured function config2tables of FMFLoader in order to parse item types more easily.
Function config2tables also parses quantities without symbol and booleans.
Modified Paths:
--------------
trunk/doc/demo/example.fmf
trunk/src/workers/fmfile/fmfile/FMFLoader.py
Modified: trunk/doc/demo/example.fmf
===================================================================
--- trunk/doc/demo/example.fmf 2008-12-11 10:14:14 UTC (rev 587)
+++ trunk/doc/demo/example.fmf 2008-12-16 10:48:16 UTC (rev 588)
@@ -32,6 +32,14 @@
Complex number with zero real part : 2J
Complex number with zero imaginary part: 1+0J
list of complex: 1+2j, 1+2J
+[Boolean values]
+true1: True
+true2: true
+true3: TRUE
+false1: False
+false2: false
+false3: FALSE
+list of booleans: True, true, TRUE, False, false, FALSE
[Physical Quantities]
number: N = 2
voltage: U = 1V
@@ -50,6 +58,23 @@
trailing amplitude, relative error: \omega = (1 +- 1%) 2 ohm
estimated parameter: p = 1 \pm 0.1
another estimated parameter: p = 1 \pm 1%
+list of quantities: number: N = 2, U = 1V, T_C = 22 degC
+[Simplified quantities]
+voltage: 1V
+temperature in Celsius: 22 degC
+resistance: 2.0 kg*m^2*A^-2*s^-3
+[Simplified Quantities with error]
+voltage: 1 V +- 1 mV
+current: 1 A +/- 0.001 A
+energy: 1 J \pm 1 mJ
+work: 1 W +- 0.1%
+voltage in brackets: (1 +- 0.001) V
+current in brackets: (1 +- 0.1%) A
+trailing amplitude: (1 +- 0.01) 2 ohm
+trailing amplitude, relative error: (1 +- 1%) 2 ohm
+estimated parameter: 1 \pm 0.1
+another estimated parameter: 1 \pm 1%
+list of quantities: 1V, 22 degC,(1 +- 1%) 2 ohm
[*table definitions]
table: T
mixed: M
Modified: trunk/src/workers/fmfile/fmfile/FMFLoader.py
===================================================================
--- trunk/src/workers/fmfile/fmfile/FMFLoader.py 2008-12-11 10:14:14 UTC (rev 587)
+++ trunk/src/workers/fmfile/fmfile/FMFLoader.py 2008-12-16 10:48:16 UTC (rev 588)
@@ -240,6 +240,49 @@
return config2tables(preParsedData, config)
def config2tables(preParsedData, config):
+ def parseVariable(oldVal):
+ shortname, value = tuple([s.strip() for s in oldVal.split('=')])
+ value, error = parseQuantity(value)
+ return (shortname, value, error)
+
+ def parseQuantity(value):
+ pm = re.compile(ur"(?:\\pm|\+-|\+/-)")
+ try:
+ value, error = [s.strip() for s in pm.split(value)]
+ except:
+ error = None
+ if value.startswith('('):
+ value = float(value[1:])
+ error, unit = [s.strip() for s in error.split(')')]
+ unit = str2unit(unit)
+ value *= unit
+ else:
+ value = str2unit(value)
+ if error != None:
+ if error.endswith('%'):
+ error = value*float(error[:-1])/100.0
+ else:
+ try:
+ error = float(error)*unit
+ except:
+ error = str2unit(error)
+ return value, error
+
+ def parseBool(value):
+ if value.lower() == 'true':
+ return True
+ elif value.lower() == 'false':
+ return False
+ raise AttributeError
+
+ converters = [ parseVariable,
+ parseQuantity,
+ int,
+ float,
+ complex,
+ parseBool,
+ ]
+
def str2unit(unit):
if unit.startswith('.'):
unit = '0'+unit
@@ -252,54 +295,18 @@
return unit
def item2value(section, key):
- pm = re.compile(ur"(?:\\pm|\+-|\+/-)")
oldVal = section[key]
- try:
- shortname, value = tuple([s.strip() for s in oldVal.split('=')])
+ if type(oldVal)==type([]):
+ for c in converters:
+ try:
+ return map(c,oldVal)
+ except:
+ pass
+ for c in converters:
try:
- value, error = [s.strip() for s in pm.split(value)]
+ return c(oldVal)
except:
- error = None
- if value.startswith('('):
- value = float(value[1:])
- error, unit = [s.strip() for s in error.split(')')]
- unit = str2unit(unit)
- value *= unit
- else:
- value = str2unit(value)
- if error != None:
- if error.endswith('%'):
- error = value*float(error[:-1])/100.0
- else:
- try:
- error = float(error)*unit
- except:
- error = str2unit(error)
- return (shortname, value, error)
- except:
- if type(oldVal)==type([]):
- try:
- return map(int,oldVal)
- except:
- try:
- return map(float,oldVal)
- except:
- try:
- return map(complex,oldVal)
- except:
- pass
- else:
- try:
- return int(oldVal)
- except:
- try:
- return float(oldVal)
- except:
- try:
- return complex(oldVal)
- except:
- pass
-
+ pass
return oldVal
if config.has_key('*table definitions'):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <li...@us...> - 2008-12-17 10:47:32
|
Revision: 590
http://pyphant.svn.sourceforge.net/pyphant/?rev=590&view=rev
Author: liehr
Date: 2008-12-17 10:47:27 +0000 (Wed, 17 Dec 2008)
Log Message:
-----------
FMFLoader supports parsing of timestamps on basis of the mx.DateTime.ISO module.
All datetime strings, which are conform to ISO 8601,
are normalized to 'YYYY-MM-DD HH-MM-SS.ss'.
Modified Paths:
--------------
trunk/doc/demo/example.fmf
trunk/src/workers/fmfile/fmfile/FMFLoader.py
Modified: trunk/doc/demo/example.fmf
===================================================================
--- trunk/doc/demo/example.fmf 2008-12-17 10:46:43 UTC (rev 589)
+++ trunk/doc/demo/example.fmf 2008-12-17 10:47:27 UTC (rev 590)
@@ -75,6 +75,15 @@
estimated parameter: 1 \pm 0.1
another estimated parameter: 1 \pm 1%
list of quantities: 1V, 22 degC,(1 +- 1%) 2 ohm
+[Datetime stamps]
+date: 2008-12-16
+week date: 2008-W47-1
+list of dates: 2008-11-17,2008-1-3,2006-2-17,2008-W47-1
+datetime: 2008-12-16T16:51
+another datetime: 2008-12-16 16:51
+datetime with second: 2008-12-16T16:51:05
+datetime UTC: 2008-12-16T16:51Z
+datetime+2h: 2006-04-23 14:25:51+02:00
[*table definitions]
table: T
mixed: M
Modified: trunk/src/workers/fmfile/fmfile/FMFLoader.py
===================================================================
--- trunk/src/workers/fmfile/fmfile/FMFLoader.py 2008-12-17 10:46:43 UTC (rev 589)
+++ trunk/src/workers/fmfile/fmfile/FMFLoader.py 2008-12-17 10:47:27 UTC (rev 590)
@@ -41,6 +41,7 @@
from pyphant.core import (Worker, Connectors,
Param, DataContainer)
from pyphant.quantities.PhysicalQuantities import PhysicalQuantity,isPhysicalUnit,isPhysicalQuantity
+import mx.DateTime.ISO
import logging
_logger = logging.getLogger("pyphant")
@@ -281,6 +282,7 @@
float,
complex,
parseBool,
+ lambda d: str(mx.DateTime.ISO.ParseAny(d))
]
def str2unit(unit):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <li...@us...> - 2008-12-19 19:02:41
|
Revision: 591
http://pyphant.svn.sourceforge.net/pyphant/?rev=591&view=rev
Author: liehr
Date: 2008-12-19 19:02:36 +0000 (Fri, 19 Dec 2008)
Log Message:
-----------
Bugfix: Correct parsing of arbitrary units (a.u.)
Refactured function str2unit() which is used for parsing metaparameter and
data definitions.
Modified Paths:
--------------
trunk/doc/demo/example.fmf
trunk/src/workers/fmfile/fmfile/FMFLoader.py
Modified: trunk/doc/demo/example.fmf
===================================================================
--- trunk/doc/demo/example.fmf 2008-12-17 10:47:27 UTC (rev 590)
+++ trunk/doc/demo/example.fmf 2008-12-19 19:02:36 UTC (rev 591)
@@ -40,13 +40,31 @@
false2: false
false3: FALSE
list of booleans: True, true, TRUE, False, false, FALSE
-[Physical Quantities]
+[Quantities]
+voltage: 1V
+temperature in Celsius: 22 degC
+resistance: 2.0 kg*m^2*A^-2*s^-3
+arbitrary units: 10 a.u.
+[Quantities with error]
+voltage: 1 V +- 1 mV
+current: 1 A +/- 0.001 A
+energy: 1 J \pm 1 mJ
+work: 1 W +- 0.1%
+voltage in brackets: (1 +- 0.001) V
+current in brackets: (1 +- 0.1%) A
+trailing amplitude: (1 +- 0.01) 2 ohm
+trailing amplitude, relative error: (1 +- 1%) 2 ohm
+estimated parameter: 1 \pm 0.1
+another estimated parameter: 1 \pm 1%
+list of quantities: 1V, 22 degC,(1 +- 1%) 2 ohm
+[Variables]
number: N = 2
voltage: U = 1V
temperature in Celsius: T_C = 22 degC
temperature in Fahrenheit: T = 22 degF
resistance: \omega = 2.0 kg*m^2*A^-2*s^-3
resistance 2: \omega = 2.0 kg*m**2*A**-2*s**-3
+normed variable: n = 10 a.u.
[Physical Quantities with error]
voltage: U = 1 V +- 1 mV
current: I = 1 A +/- 0.001 A
@@ -59,22 +77,6 @@
estimated parameter: p = 1 \pm 0.1
another estimated parameter: p = 1 \pm 1%
list of quantities: number: N = 2, U = 1V, T_C = 22 degC
-[Simplified quantities]
-voltage: 1V
-temperature in Celsius: 22 degC
-resistance: 2.0 kg*m^2*A^-2*s^-3
-[Simplified Quantities with error]
-voltage: 1 V +- 1 mV
-current: 1 A +/- 0.001 A
-energy: 1 J \pm 1 mJ
-work: 1 W +- 0.1%
-voltage in brackets: (1 +- 0.001) V
-current in brackets: (1 +- 0.1%) A
-trailing amplitude: (1 +- 0.01) 2 ohm
-trailing amplitude, relative error: (1 +- 1%) 2 ohm
-estimated parameter: 1 \pm 0.1
-another estimated parameter: 1 \pm 1%
-list of quantities: 1V, 22 degC,(1 +- 1%) 2 ohm
[Datetime stamps]
date: 2008-12-16
week date: 2008-W47-1
Modified: trunk/src/workers/fmfile/fmfile/FMFLoader.py
===================================================================
--- trunk/src/workers/fmfile/fmfile/FMFLoader.py 2008-12-17 10:47:27 UTC (rev 590)
+++ trunk/src/workers/fmfile/fmfile/FMFLoader.py 2008-12-19 19:02:36 UTC (rev 591)
@@ -240,6 +240,25 @@
config = FMFConfigObj(d.encode('utf-8').splitlines(), encoding='utf-8')
return config2tables(preParsedData, config)
+def str2unit(unit):
+ if unit.startswith('.'):
+ unit = '0'+unit
+ elif unit == '%':
+ unit = 0.01
+ elif unit.endswith('a.u.'):
+ try:
+ unit = float(unit[:-4])
+ except:
+ unit = 1.0
+ elif not unit[0].isdigit():
+ unit = '1'+unit
+ try:
+ unit = unit.replace('^', '**')
+ unit = PhysicalQuantity(unit.encode('utf-8'))
+ except:
+ unit = float(unit)
+ return unit
+
def config2tables(preParsedData, config):
def parseVariable(oldVal):
shortname, value = tuple([s.strip() for s in oldVal.split('=')])
@@ -285,17 +304,6 @@
lambda d: str(mx.DateTime.ISO.ParseAny(d))
]
- def str2unit(unit):
- if unit.startswith('.'):
- unit = '0'+unit
- elif not unit[0].isdigit():
- unit = '1'+unit
- try:
- unit = PhysicalQuantity(unit.encode('utf-8').replace('^','**'))
- except:
- unit = float(unit)
- return unit
-
def item2value(section, key):
oldVal = section[key]
if type(oldVal)==type([]):
@@ -359,20 +367,7 @@
_logger.error("""Cannot interpret definition of data column "%s", which is given as "%s"!""" % (fieldLongname,spec))
unit = match.group('unit')
if unit != None:
- unit = unit[1:-1]
- if unit.startswith('.'):
- unit = '0'+unit
- elif unit == '%':
- unit = 0.01
- elif unit == 'a.u.':
- unit = 1.0
- elif not unit[0].isdigit():
- unit = '1'+unit
- try:
- unit = unit.replace('^', '**')
- unit = PhysicalQuantity(unit.encode('utf-8'))
- except:
- unit = float(unit)
+ unit = str2unit(unit[1:-1])
else:
unit = 1.0
fieldShortname=match.group('shortname')
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <li...@us...> - 2008-12-19 19:03:24
|
Revision: 592
http://pyphant.svn.sourceforge.net/pyphant/?rev=592&view=rev
Author: liehr
Date: 2008-12-19 19:03:18 +0000 (Fri, 19 Dec 2008)
Log Message:
-----------
Added astronomical unit (AU) to the Quantities modul.
Modified Paths:
--------------
trunk/doc/demo/example.fmf
trunk/src/pyphant/pyphant/quantities/PhysicalQuantities.py
Modified: trunk/doc/demo/example.fmf
===================================================================
--- trunk/doc/demo/example.fmf 2008-12-19 19:02:36 UTC (rev 591)
+++ trunk/doc/demo/example.fmf 2008-12-19 19:03:18 UTC (rev 592)
@@ -45,6 +45,7 @@
temperature in Celsius: 22 degC
resistance: 2.0 kg*m^2*A^-2*s^-3
arbitrary units: 10 a.u.
+distance from Earth to Sun: 1 AU
[Quantities with error]
voltage: 1 V +- 1 mV
current: 1 A +/- 0.001 A
Modified: trunk/src/pyphant/pyphant/quantities/PhysicalQuantities.py
===================================================================
--- trunk/src/pyphant/pyphant/quantities/PhysicalQuantities.py 2008-12-19 19:02:36 UTC (rev 591)
+++ trunk/src/pyphant/pyphant/quantities/PhysicalQuantities.py 2008-12-19 19:03:18 UTC (rev 592)
@@ -801,6 +801,7 @@
_addUnit('nmi', '1852.*m', 'Nautical mile')
_addUnit('Ang', '1.e-10*m', 'Angstrom')
_addUnit('lyr', 'c*yr', 'light year')
+_addUnit('AU', '149597870691*m', 'astronomical unit')
_addUnit('Bohr', '4*pi*eps0*hbar**2/me/e**2', 'Bohr radius')
# Area units
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <zk...@us...> - 2009-04-06 22:07:01
|
Revision: 634
http://pyphant.svn.sourceforge.net/pyphant/?rev=634&view=rev
Author: zklaus
Date: 2009-04-06 22:06:52 +0000 (Mon, 06 Apr 2009)
Log Message:
-----------
Merge branch 'master' into svn-trunk
* master:
Removed trailing white spaces.
New place for file with ideas for knowledge manager.
Added Paths:
-----------
trunk/doc/knowledge-ideas.org
Removed Paths:
-------------
trunk/src/pyphant/pyphant/core/knowledge-ideas.org
Added: trunk/doc/knowledge-ideas.org
===================================================================
--- trunk/doc/knowledge-ideas.org (rev 0)
+++ trunk/doc/knowledge-ideas.org 2009-04-06 22:06:52 UTC (rev 634)
@@ -0,0 +1,26 @@
+
+
+Ideas:
+
+
+* reloading HDF5 files in order to refresh ids
+
+* enable configuration of cache directory
+
+* proxy server specification for downloads
+
+* gather information about known ids from KnowledgeManager (also remote)
+
+ e.g. longname, shortname, ..
+
+* choose standard port for HTTP server
+
+* restrict access to temporary directory for HTTPs do_GET
+
+* registerDataContainer, optional: store HDF5 with DataContainer permanently
+
+* request Pyphant recipes via a unique id
+
+ handle them like DataContainers
+
+* Special syntax for doc strings for 'epydoc', 'happydoc', 'doxygen', ..?
Deleted: trunk/src/pyphant/pyphant/core/knowledge-ideas.org
===================================================================
--- trunk/src/pyphant/pyphant/core/knowledge-ideas.org 2009-04-03 14:33:58 UTC (rev 633)
+++ trunk/src/pyphant/pyphant/core/knowledge-ideas.org 2009-04-06 22:06:52 UTC (rev 634)
@@ -1,39 +0,0 @@
-
-
-Ideas:
-
-*
- Before caching an entire file, test whether a KnowledgeManager runs
- on the remote side. If yes, ask for the file.
-
-* Download auf Wunsch erzwingen, falls remote Datei ge\xE4ndert?
- Alternativ: KnowledgeManager Cache l\xF6schen lassen, siehe urllib.urlcleanup()
-
-* Was tun, wenn id nicht auffindbar?
-
- - anderen KnowledgeManager fragen, der sich
- entweder aus der URL ergibt oder
- der extra registriert ist
-
-* Referenzen (Index) innerhalb HDF5-Dateien auffrischen?
-
-* Dictionaries/Caches
-
- - id -> Referenzen (URLs)
- - Referenzen -> lokale Kopien (urllib macht das schon!)
- - id -> (Referenz, Knotenreferenz)
-
-
-* Cache Verzeichnis
-Bei Initialisieren des KnowledgeManagers Cache Verzeichnis angeben und
-bei urlretreive nutzen
-
-* Proxy-Server-Angabe f\xFCr KM-Zugriff
-
-* Threaded HTTPServer
-
-http://www.doughellmann.com/PyMOTW/BaseHTTPServer/index.html
-
-* HTTP server Thread stoppen
-
-* Inhaltsverzeichnis mit Infos von remote Knowledgemanager abfragen f\xFCr GUI
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <zk...@us...> - 2009-05-11 07:26:09
|
Revision: 644
http://pyphant.svn.sourceforge.net/pyphant/?rev=644&view=rev
Author: zklaus
Date: 2009-05-11 07:25:59 +0000 (Mon, 11 May 2009)
Log Message:
-----------
Merge branch 'master' into svn-trunk
* master:
Fix: Adapted viewOSC to new worker naming api.
Fix: ComputeFunctional worker was incorrectly called ExtremumFinder.
Modified Paths:
--------------
trunk/doc/demo/viewOSC.py
trunk/src/workers/OSC/OSC/ComputeFunctional.py
Modified: trunk/doc/demo/viewOSC.py
===================================================================
--- trunk/doc/demo/viewOSC.py 2009-05-10 19:25:28 UTC (rev 643)
+++ trunk/doc/demo/viewOSC.py 2009-05-11 07:25:59 UTC (rev 644)
@@ -35,7 +35,7 @@
__version__ = "$Revision: 29 $"
import matplotlib
-matplotlib.use('wxagg') # This MUST stay above 'import pylab'!
+matplotlib.use('wxagg') # This MUST stay in front of 'import pylab'!
import threading, pylab
from pyphant.visualizers.ImageVisualizer import ImageVisualizer
@@ -122,10 +122,10 @@
def setParameters(recipe, freqRange=None, scale=None):
if freqRange != None:
- worker = recipe.getWorkers("Slicing")[0]
+ worker = recipe.getWorker("Slicing")
worker.paramDim1.value=freqRange
if scale != None:
- worker = recipe.getWorkers("Multi Resolution Analyser","Slicing")[0]
+ worker = recipe.getWorker("MRA")
worker.paramScale.value=scale
def initPylab(postscript):
@@ -166,13 +166,13 @@
pylab.show()
def compareAbsorption(recipe, curvNo, noIndicators):
- worker = recipe.getWorkers("Slicing")[0]
+ worker = recipe.getWorker("Slicing")
noisyAbsorption = worker.plugExtract.getResult()
- worker = recipe.getWorkers("Coat Thickness Model")[0]
+ worker = recipe.getWorker("ThicknessModeller")
simulation = worker.plugCalcAbsorption.getResult()
- worker = recipe.getWorkers("Multi Resolution Analyser","Slicing")[0]
+ worker = recipe.getWorker("MRA")
minimaPos = worker.plugMra.getResult().inUnitsOf(simulation.dimensions[1])
- worker = recipe.getWorkers("Add Column")[0]
+ worker = recipe.getWorker("AddColumn")
table = worker.plugCompute.getResult(subscriber=TextSubscriber("Add Column"))
xPos = table[u"horizontal_table_position"]
yPos = table[u"vertical_table_position"]
@@ -200,13 +200,13 @@
pylab.xlabel(simulation.dimensions[1].label)
def noisyAbsorption(recipe, curvNo, noIndicators):
- worker = recipe.getWorkers("Slicing")[0]
+ worker = recipe.getWorker("Slicing")
noisyAbsorption = worker.plugExtract.getResult()
- worker = recipe.getWorkers("Coat Thickness Model")[0]
+ worker = recipe.getWorker("ThicknessModeller")[0]
simulation = worker.plugCalcAbsorption.getResult()
- worker = recipe.getWorkers("Multi Resolution Analyser","Slicing")[0]
+ worker = recipe.getWorker("MRA")
minimaPos = worker.plugMra.getResult().inUnitsOf(simulation.dimensions[1])
- worker = recipe.getWorkers("Add Column")[0]
+ worker = recipe.getWorker("AddColumn")
table = worker.plugCompute.getResult(subscriber=TextSubscriber("Add Column"))
xPos = table[u"horizontal_table_position"]
yPos = table[u"vertical_table_position"]
@@ -227,9 +227,9 @@
pylab.ylabel(simulation.label)
def thicknessMap(recipe, curvNo):
- worker = recipe.getWorkers("Osc Mapper")[0]
+ worker = recipe.getWorker("OscMapper")
oscMap = worker.plugMapHeights.getResult()
- worker = recipe.getWorkers("Add Column")[0]
+ worker = recipe.getWorker("AddColumn")
table = worker.plugCompute.getResult(subscriber=TextSubscriber("Add Column"))
xPos = table[u"horizontal_table_position"]
yPos = table[u"vertical_table_position"]
@@ -238,13 +238,13 @@
pylab.plot([xPos.data[index]],[yPos.data[index]],'xk',scalex=False,scaley=False)
def functional(recipe, curvNo, noIndicators):
- worker = recipe.getWorkers("Compute Functional")[0]
+ worker = recipe.getWorker("Compute Functional")[0]
functional = worker.plugCompute.getResult()
- worker = recipe.getWorkers("Coat Thickness Model")[0]
+ worker = recipe.getWorker("ThicknessModeller")[0]
simulation = worker.plugCalcAbsorption.getResult()
- worker = recipe.getWorkers("Multi Resolution Analyser","Slicing")[0]
+ worker = recipe.getWorker("MRA")
minimaPos = worker.plugMra.getResult().inUnitsOf(simulation.dimensions[1])
- worker = recipe.getWorkers("Add Column")[0]
+ worker = recipe.getWorker("AddColumn")
table = worker.plugCompute.getResult(subscriber=TextSubscriber("Add Column"))
thickness = table[u"thickness"]
index = curvNo2Index(table[u"pixel"], curvNo)
@@ -258,13 +258,13 @@
label ="$%s$"%minimaPos.shortname)
def simulation(recipe, curvNo, noIndicators):
- worker = recipe.getWorkers("Coat Thickness Model")[0]
+ worker = recipe.getWorker("ThicknessModeller")[0]
simulation = worker.plugCalcAbsorption.getResult()
- worker = recipe.getWorkers("Add Column")[0]
+ worker = recipe.getWorker("AddColumn")
table = worker.plugCompute.getResult(subscriber=TextSubscriber("Add Column"))
thickness = table[u"thickness"]
index = curvNo2Index(table[u"pixel"], curvNo)
- worker = recipe.getWorkers("Multi Resolution Analyser","Slicing")[0]
+ worker = recipe.getWorker("MRA")
minimaPos = worker.plugMra.getResult().inUnitsOf(simulation.dimensions[1])
visualizer = ImageVisualizer(simulation, False)
ordinate = simulation.dimensions[1].data
@@ -276,16 +276,16 @@
label ="$%s$"%minimaPos.shortname)
def dumpMinima(recipe):
- worker = recipe.getWorkers("Coat Thickness Model")[0]
+ worker = recipe.getWorker("ThicknessModeller")
simulation = worker.plugCalcAbsorption.getResult()
- worker = recipe.getWorkers("Add Column")[0]
+ worker = recipe.getWorker("AddColumn")
table = worker.plugCompute.getResult(subscriber=TextSubscriber("Add Column"))
index = table[u"pixel"]
xPos = table[u"horizontal_table_position"]
yPos = table[u"vertical_table_position"]
thickness = table[u"thickness"]
cols = [index, xPos, yPos, thickness]
- worker = recipe.getWorkers("Multi Resolution Analyser","Slicing")[0]
+ worker = recipe.getWorker("MRA")
minimaPos = worker.plugMra.getResult().inUnitsOf(simulation.dimensions[1])
import numpy
data = numpy.vstack([ c.data for c in cols]
Modified: trunk/src/workers/OSC/OSC/ComputeFunctional.py
===================================================================
--- trunk/src/workers/OSC/OSC/ComputeFunctional.py 2009-05-10 19:25:28 UTC (rev 643)
+++ trunk/src/workers/OSC/OSC/ComputeFunctional.py 2009-05-11 07:25:59 UTC (rev 644)
@@ -47,7 +47,7 @@
import copy
-class ExtremumFinder(Worker.Worker):
+class ComputeFunctional(Worker.Worker):
API = 2
VERSION = 1
REVISION = "$Revision$"[11:-1]
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <zk...@us...> - 2010-02-02 11:21:32
|
Revision: 664
http://pyphant.svn.sourceforge.net/pyphant/?rev=664&view=rev
Author: zklaus
Date: 2010-02-02 11:21:26 +0000 (Tue, 02 Feb 2010)
Log Message:
-----------
Merge branch 'master' into svn-trunk
* master:
Change: Adapted viewOSC.py to new naming convention.
Fix: wxPyphant not closing correctly
Modified Paths:
--------------
trunk/doc/demo/viewOSC.py
trunk/src/pyphant/pyphant/wxgui2/wxPyphantApplication.py
Modified: trunk/doc/demo/viewOSC.py
===================================================================
--- trunk/doc/demo/viewOSC.py 2010-02-01 17:45:00 UTC (rev 663)
+++ trunk/doc/demo/viewOSC.py 2010-02-02 11:21:26 UTC (rev 664)
@@ -174,8 +174,8 @@
minimaPos = worker.plugMra.getResult().inUnitsOf(simulation.dimensions[1])
worker = recipe.getWorker("AddColumn")
table = worker.plugCompute.getResult(subscriber=TextSubscriber("Add Column"))
- xPos = table[u"horizontal_table_position"]
- yPos = table[u"vertical_table_position"]
+ xPos = table[u"x-position"]
+ yPos = table[u"y-position"]
thickness = table[u"thickness"]
index = curvNo2Index(table[u"pixel"], curvNo)
result = "$%s_{%s}$(%s %s,%s %s)=%s %s" % (thickness[index].shortname,curvNo,
Modified: trunk/src/pyphant/pyphant/wxgui2/wxPyphantApplication.py
===================================================================
--- trunk/src/pyphant/pyphant/wxgui2/wxPyphantApplication.py 2010-02-01 17:45:00 UTC (rev 663)
+++ trunk/src/pyphant/pyphant/wxgui2/wxPyphantApplication.py 2010-02-02 11:21:26 UTC (rev 664)
@@ -301,6 +301,7 @@
self._wxPyphantApp._knowledgeNode.stop()
except AttributeError:
pass
+ self._wxPyphantApp._excframe.Destroy()
self.Destroy()
def editCompositeWorker(self, worker):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <zk...@us...> - 2010-02-21 20:52:06
|
Revision: 668
http://pyphant.svn.sourceforge.net/pyphant/?rev=668&view=rev
Author: zklaus
Date: 2010-02-21 20:51:58 +0000 (Sun, 21 Feb 2010)
Log Message:
-----------
Merge branch 'master' into svn-trunk
* master:
Module SQLiteWrapper adapted to additional base unit bit.
Conflicts resolved, but merged version still has bugs.
Refacturing: Removed intermediate module PhysicalQuantities, such that class Quantity is directly loaded from module quantities.
Refactoring: Renamed Function isPhysicalUnit to isUnit.
Refacturing: Renamed class PhysicalQuantity to Quantity.
Enh.: Added scenario for testing datetime with uncertainty.
Enh: Demo script readfmf.py accepts command 'parse <FMF-value>'.
Refactured: Function item2value takes a simple string as argument and not a pair of dictionary with associated key.
Refactured: Function item2value takes a simple string as argument and not a pair of dictionary with associated key.
Bugfix: File example.fmf does not specify complex numbers with capital J anymore.
Bugfix: Items are correctly discriminated between complex numbers and quantities of unit Joule.
Defined 1Byte=8Bit.
Enh.: Added binary Units bit and B.
Test for converting value 1EUR to 1USD is only run, if up to date exchange rates have been fetched.
Enh: Added binary units.
Bugfix: Monetary values cannot have prefixes with powers lower than 1000.
Enh.: If fields cannot be reshaped, because they consists of strings. A warning is given.
Modified Paths:
--------------
trunk/doc/demo/example.fmf
trunk/doc/demo/readfmf.py
trunk/src/pyphant/pyphant/core/DataContainer.py
trunk/src/pyphant/pyphant/core/FieldContainer.py
trunk/src/pyphant/pyphant/core/H5FileHandler.py
trunk/src/pyphant/pyphant/core/KnowledgeManager.py
trunk/src/pyphant/pyphant/core/PyTablesPersister.py
trunk/src/pyphant/pyphant/core/SQLiteWrapper.py
trunk/src/pyphant/pyphant/quantities/ParseQuantities.py
trunk/src/pyphant/pyphant/quantities/__init__.py
trunk/src/pyphant/pyphant/tests/TestAutoFocus.py
trunk/src/pyphant/pyphant/tests/TestDataContainer.py
trunk/src/pyphant/pyphant/tests/TestH5FileHandler.py
trunk/src/pyphant/pyphant/tests/TestParseQuantities.py
trunk/src/pyphant/pyphant/tests/TestPyTablesPersister.py
trunk/src/pyphant/pyphant/tests/TestSQLiteWrapper.py
trunk/src/pyphant/pyphant/visualizers/Chart.py
trunk/src/pyphant/pyphant/visualizers/External.py
trunk/src/pyphant/pyphant/visualizers/ImageVisualizer.py
trunk/src/workers/ImageProcessing/ImageProcessing/AutoFocus.py
trunk/src/workers/ImageProcessing/ImageProcessing/DistanceMapper.py
trunk/src/workers/ImageProcessing/ImageProcessing/ImageLoaderWorker.py
trunk/src/workers/ImageProcessing/ImageProcessing/NDImageWorker.py
trunk/src/workers/ImageProcessing/ImageProcessing/SlopeCalculator.py
trunk/src/workers/ImageProcessing/ImageProcessing/tests/TestApplyMask.py
trunk/src/workers/ImageProcessing/ImageProcessing/tests/TestDistanceMapper.py
trunk/src/workers/ImageProcessing/ImageProcessing/tests/TestImageLoader.py
trunk/src/workers/ImageProcessing/ImageProcessing/tests/TestMedianiser.py
trunk/src/workers/ImageProcessing/ImageProcessing/tests/TestSkeletonizeFeature.py
trunk/src/workers/ImageProcessing/ImageProcessing/tests/TestSlopeCalculator.py
trunk/src/workers/ImageProcessing/ImageProcessing/tests/TestThresholdingWorker.py
trunk/src/workers/OSC/OSC/CompareFields.py
trunk/src/workers/OSC/OSC/ComputeFunctional.py
trunk/src/workers/OSC/OSC/ErrorEstimator.py
trunk/src/workers/OSC/OSC/EstimateParameter.py
trunk/src/workers/OSC/OSC/ExtremumFinder.py
trunk/src/workers/OSC/OSC/MRA.py
trunk/src/workers/OSC/OSC/OscAbsorption.py
trunk/src/workers/OSC/OSC/OscCurrent.py
trunk/src/workers/OSC/OSC/OscLoader.py
trunk/src/workers/OSC/OSC/OscVisualisers.py
trunk/src/workers/OSC/OSC/Slicing.py
trunk/src/workers/OSC/OSC/Smoother.py
trunk/src/workers/OSC/OSC/ThicknessModeller.py
trunk/src/workers/OSC/OSC/tests/TestExtremumFinder.py
trunk/src/workers/OSC/OSC/tests/TestMRA.py
trunk/src/workers/OSC/OSC/tests/TestOscAbsorption.py
trunk/src/workers/Statistics/Statistics/tests/TestHistogram.py
trunk/src/workers/fmfile/fmfile/FMFLoader.py
trunk/src/workers/fmfile/fmfile/tests/TestFMFLoader.py
trunk/src/workers/tools/tools/ParameterRun.py
trunk/src/workers/tools/tools/tests/TestEmd5Source.py
Added Paths:
-----------
trunk/src/pyphant/pyphant/tests/TestQuantities.py
Removed Paths:
-------------
trunk/src/pyphant/pyphant/quantities/PhysicalQuantities.py
Property Changed:
----------------
trunk/doc/demo/readfmf.py
Modified: trunk/doc/demo/example.fmf
===================================================================
--- trunk/doc/demo/example.fmf 2010-02-12 16:21:58 UTC (rev 667)
+++ trunk/doc/demo/example.fmf 2010-02-21 20:51:58 UTC (rev 668)
@@ -28,10 +28,10 @@
float with Exponential: -1.1E10
list of floats: 1.0, .1, 1e-10, -1.1E10
complex: 1+2j
-Complex: 1+2J
-Complex number with zero real part : 2J
-Complex number with zero imaginary part: 1+0J
-list of complex: 1+2j, 1+2J
+Complex: 1.1+2j
+Complex number with zero real part : 2j
+Complex number with zero imaginary part: 1+0j
+list of complex: 1+2j, 1.1+2j
[Boolean values]
true1: True
true2: true
@@ -101,7 +101,7 @@
[*data: T]
H_2 1 1. 1e1 1+0j nan inf
O_2 2 .2 2E1 2+.1j NaN INF
-O 2 2 .2 2E1 2+.1J NAN Inf
+O 2 2 .2 2E1 2.+2j NAN Inf
[*data definitions: M]
String: S
Complex: C
Modified: trunk/doc/demo/readfmf.py
===================================================================
--- trunk/doc/demo/readfmf.py 2010-02-12 16:21:58 UTC (rev 667)
+++ trunk/doc/demo/readfmf.py 2010-02-21 20:51:58 UTC (rev 668)
@@ -1,15 +1,61 @@
-import sys
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# Copyright (c) 2008, Rectorate of the University of Freiburg
+# Copyright (c) 2009, Andreas W. Liehr (li...@us...)
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+# * Neither the name of the Freiburg Materials Research Center,
+# University of Freiburg nor the names of its contributors may be used to
+# endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
+# OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+
import logging
+from optparse import OptionParser
+
logging.basicConfig(level=logging.WARNING,
format="%(asctime)s - %(levelname)s:%(name)s:%(thread)d:%(module)s.%(funcName)s(l %(lineno)d):%(message)s")
-from fmfile.FMFLoader import FMFLoader
+from fmfile.FMFLoader import FMFLoader,item2value
-worker = FMFLoader()
-if len(sys.argv) == 1:
+parser = OptionParser(usage="""usage: %prog path2FMFfile
+ %prog parse FMFvalue""")
+
+(options, args) = parser.parse_args()
+if len(args) == 0:
filenames = ['example.fmf']
+elif args[0] in ('parse',u'parse'):
+ value = ' '.join(args[1:])
+ result = item2value(value)
+ print "Value \"%s\" is interpreted as %s:" % (value,type(result))
+ print result
+ from sys import exit
+ exit(0)
else:
- filenames = sys.argv[1:]
+ filenames = args
+
+worker = FMFLoader()
for filename in filenames:
worker.paramFilename.value=filename
result = worker.plugLoadFMF.getResult()
Property changes on: trunk/doc/demo/readfmf.py
___________________________________________________________________
Added: svn:executable
+ *
Modified: trunk/src/pyphant/pyphant/core/DataContainer.py
===================================================================
--- trunk/src/pyphant/pyphant/core/DataContainer.py 2010-02-12 16:21:58 UTC (rev 667)
+++ trunk/src/pyphant/pyphant/core/DataContainer.py 2010-02-21 20:51:58 UTC (rev 668)
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
-# Copyright (c) 2006-2008, Rectorate of the University of Freiburg
+# Copyright (c) 2006-2009, Rectorate of the University of Freiburg
+# Copyright (c) 2009, Andreas W. Liehr (li...@us...)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
@@ -70,8 +71,8 @@
import copy, hashlib, threading, numpy, StringIO
import os, platform, datetime, socket, urlparse
-from pyphant.quantities.PhysicalQuantities import (isPhysicalQuantity,
- PhysicalQuantity)
+from pyphant.quantities import (isQuantity,
+ Quantity)
import Helpers
import logging
@@ -195,7 +196,7 @@
\t .data \t- Table of samples stored in a numpy.ndarray.
\t .desc \t- Description numpy.dtype of the ndarray.
-\t .units \t- List of PhysicalQuantities objects denoting the units of
+\t .units \t- List of quantities.objects denoting the units of
\t\t\t the columns.
\t .longname \t- Notation of the data, e.g. 'database query',
\t\t\t which is used for the automatic annotation of charts.
@@ -338,12 +339,12 @@
al.append(('SCColumn', column))
else:
try:
- phq = PhysicalQuantity(e)
+ phq = Quantity(e)
al.append(('PhysQuant', phq))
continue
except:
try:
- number = PhysicalQuantity(e+' m')
+ number = Quantity(e+' m')
al.append(('Number', eval(e)))
continue
except: pass
@@ -594,7 +595,7 @@
<atomar> := <value> <CompareOp> <value>
where <value> is either a SC Column accessed as
"longname" or "shortname" (including the double quotes)
- or a number or a string representing a PhysicalQuantity
+ or a number or a string representing a Quantity
(e.g. 300nm). And <CompareOp> can be ==, !=, <, <=, >, >=.
Then a valid expression <expression> is:
- <atomar>
@@ -613,7 +614,7 @@
- or
If expression is a nested tuple, syntax is as follows:
<value> is either ('SCColumn', FieldContainer instance)
- or ('PhysQuant', PhysicalQuantity instance)
+ or ('PhysQuant', Quantity instance)
or ('Number', int float etc.)
<CompareOp> is in ['==', '!=', ...]
A valid nested tuple <nt> can be:
@@ -661,7 +662,7 @@
rightvalue = None
if left[0] == 'SCColumn' and right[0] == 'SCColumn':
number = right[1].unit/left[1].unit
- if isPhysicalQuantity(number):
+ if isQuantity(number):
raise TypeError(
'Cannot compare "' + left[1].longname + '" to "'
+ right[1].longname + '".'
@@ -670,7 +671,7 @@
rightvalue = right[1].data*number
elif left[0] == 'SCColumn':
number = right[1]/left[1].unit
- if isPhysicalQuantity(number):
+ if isQuantity(number):
raise TypeError(
'Cannot compare "' + left[1].longname
+ '" to ' + str(right[1]) + '".'
@@ -679,7 +680,7 @@
rightvalue = number
elif right[0] == 'SCColumn':
number = left[1]/right[1].unit
- if isPhysicalQuantity(number):
+ if isQuantity(number):
raise TypeError(
"Cannot compare " + str(left[1]) + ' to "'
+ right[1].longname + '".'
Modified: trunk/src/pyphant/pyphant/core/FieldContainer.py
===================================================================
--- trunk/src/pyphant/pyphant/core/FieldContainer.py 2010-02-12 16:21:58 UTC (rev 667)
+++ trunk/src/pyphant/pyphant/core/FieldContainer.py 2010-02-21 20:51:58 UTC (rev 668)
@@ -1,7 +1,8 @@
# -*- coding: utf-8 -*-
from __future__ import with_statement
-# Copyright (c) 2006-2008, Rectorate of the University of Freiburg
+# Copyright (c) 2006-2009, Rectorate of the University of Freiburg
+# Copyright (c) 2009, Andreas W. Liehr (li...@us...)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
@@ -59,7 +60,7 @@
import scipy, copy, hashlib, threading, numpy, StringIO
import os, platform, datetime, socket, urlparse
-from pyphant.quantities.PhysicalQuantities import (isPhysicalQuantity, PhysicalQuantity,_prefixes)
+from pyphant.quantities import (isQuantity, Quantity,_prefixes)
from DataContainer import DataContainer, enc, _logger
from types import NoneType
@@ -136,14 +137,14 @@
def slice2ind(arg, dim):
if isinstance(arg, type("")):
- sl = [ "0"+a for a in arg.split(':')] #Hack for PhysicalQuantities, which does not recognize .6 as a number.
+ sl = [ "0"+a for a in arg.split(':')] #Hack for quantities. which does not recognize .6 as a number.
unit = dim.unit
try:
- hi = PhysicalQuantity(sl[1])
+ hi = Quantity(sl[1])
try:
- li = PhysicalQuantity(sl[0])
+ li = Quantity(sl[0])
except:
- li = PhysicalQuantity(float(sl[0]),hi.unit)
+ li = Quantity(float(sl[0]),hi.unit)
try:
li, hi = [ i.inUnitsOf(unit.unit).value/unit.value for i in [li,hi] ]
except TypeError:
@@ -182,7 +183,7 @@
\t\t\t shortname=u"\\Psi",rescale=False)
\t Class describing sampled fields:
\t .data\t\t- Numpy.array representing the sampled field.
-\t .unit\t\t- PhysicalQuantity object denoting the unit of the sampled field.
+\t .unit\t\t- Quantity object denoting the unit of the sampled field.
\t .dimensions\t- List of FieldContainer instances
\t\t\t describing the dimensions of the sampled field.
\t .data \t- Sampled field stored as numpy.array, which is rescaled to reasonable basic units if option rescale is chosen.
@@ -210,10 +211,10 @@
unit = unit.replace('^', '**')
if isinstance(unit, unicode):
unit = unit.encode('utf-8')
- self.unit = PhysicalQuantity(unit)
+ self.unit = Quantity(unit)
except:
try:
- self.unit = PhysicalQuantity("1"+unit)
+ self.unit = Quantity("1"+unit)
except:
self.unit = unit
self.error = error
@@ -244,7 +245,7 @@
dependency = ''
label = u"%s $%s%s$ / %s" % (self.longname.title(), self.shortname, dependency, self.unit)
try:
- if not isPhysicalQuantity(self.unit) and self.unit == 1:
+ if not isQuantity(self.unit) and self.unit == 1:
label = u"%s $%s%s$ / a.u." % (self.longname.title(),self.shortname,dependency)
except:
pass #just a ScientificPython bug
@@ -252,7 +253,7 @@
label=property(_getLabel)
def _getShortLabel(self):
- if not isPhysicalQuantity(self.unit) and self.unit == 1:
+ if not isQuantity(self.unit) and self.unit == 1:
if self.longname == 'index':
label = u"%s $%s$" % (self.longname.title(),self.shortname)
else:
@@ -311,11 +312,11 @@
super(FieldContainer, self).seal(id)
def inUnitsOf(self, other):
- if not isPhysicalQuantity(self.unit):
- if isPhysicalQuantity(other.unit):
+ if not isQuantity(self.unit):
+ if isQuantity(other.unit):
raise ValueError("Incompatible Units: self.unit = <%s>, other.unit = <%s>"%(self.unit, other.unit))
factor = float(self.unit)/float(other.unit)
- elif not isPhysicalQuantity(other.unit):
+ elif not isQuantity(other.unit):
raise ValueError("Incompatible Units: self.unit = <%s>, other.unit = <%s>"%(self.unit, other.unit))
else:
if not self.unit.isCompatible(other.unit.unit):
@@ -329,7 +330,7 @@
return newSelf
def rescale(self):
- if isPhysicalQuantity(self.unit):
+ if isQuantity(self.unit):
oldUnit = self.unit.inBaseUnits()
else:
return
@@ -391,7 +392,7 @@
error = self.error
otherData = other.data
otherError = other.error
- if (isPhysicalQuantity(self.unit) or isPhysicalQuantity(other.unit)):
+ if (isQuantity(self.unit) or isQuantity(other.unit)):
try:
if not (self.unit.inBaseUnits().unit == other.unit.inBaseUnits().unit):
_logger.debug('The units are different.')
@@ -470,8 +471,8 @@
for i in xrange(len(self._dimensions)):
if not self._dimensions[i] == other.dimensions[i]:
return NotImplemented
- if isPhysicalQuantity(self.unit):
- if not isPhysicalQuantity(other.unit):
+ if isQuantity(self.unit):
+ if not isQuantity(other.unit):
return NotImplemented
if not self.unit.isCompatible(other.unit.unit):
return NotImplemented
@@ -481,7 +482,7 @@
else:
data = other.data+(self.data*self.unit.value*self.unit.unit.conversionFactorTo(other.unit.unit))/other.unit.value
unit = other.unit
- elif isPhysicalQuantity(other.unit):
+ elif isQuantity(other.unit):
return NotImplemented
else:
data = (self.data*self.unit) + (other.data*other.unit)
@@ -510,8 +511,8 @@
for i in xrange(len(self._dimensions)):
if not self._dimensions[i] == other.dimensions[i]:
return NotImplemented
- if isPhysicalQuantity(self.unit):
- if not (isPhysicalQuantity(other.unit) and self.unit.isCompatible(other.unit.unit)):
+ if isQuantity(self.unit):
+ if not (isQuantity(other.unit) and self.unit.isCompatible(other.unit.unit)):
return NotImplemented
if self.unit >= other.unit:
data = self.data - (other.data*other.unit.value*other.unit.unit.conversionFactorTo(self.unit.unit))/self.unit.value
@@ -520,7 +521,7 @@
data = ((self.data*self.unit.value*self.unit.unit.conversionFactorTo(other.unit.unit))/other.unit.value) - other.data
unit = other.unit
else:
- if isPhysicalQuantity(other.unit):
+ if isQuantity(other.unit):
return NotImplemented
data = (self.data*self.unit) - (other.data*other.unit)
unit = 1.0
Modified: trunk/src/pyphant/pyphant/core/H5FileHandler.py
===================================================================
--- trunk/src/pyphant/pyphant/core/H5FileHandler.py 2010-02-12 16:21:58 UTC (rev 667)
+++ trunk/src/pyphant/pyphant/core/H5FileHandler.py 2010-02-21 20:51:58 UTC (rev 668)
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
-# Copyright (c) 2006-2008, Rectorate of the University of Freiburg
+# Copyright (c) 2006-2010, Rectorate of the University of Freiburg
+# Copyright (c) 2009-2010, Andreas W. Liehr (li...@us...)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
@@ -39,7 +40,7 @@
import tables
from pyphant.core import DataContainer
from tables import StringCol
-from pyphant.quantities.PhysicalQuantities import PhysicalQuantity
+from pyphant.quantities import Quantity
import scipy
import logging
import os
Modified: trunk/src/pyphant/pyphant/core/KnowledgeManager.py
===================================================================
--- trunk/src/pyphant/pyphant/core/KnowledgeManager.py 2010-02-12 16:21:58 UTC (rev 667)
+++ trunk/src/pyphant/pyphant/core/KnowledgeManager.py 2010-02-21 20:51:58 UTC (rev 668)
@@ -392,7 +392,7 @@
use (SQLiteWrapper instance).any_value
or (KM instance).any_value to skip value check
'storage': str types (==)
- 'unit': PhysicalUnit or number or PhysicalQuantity (==, FC only)
+ 'unit': PhysicalUnit or number or Quantity (==, FC only)
'dimensions': list of FC search dicts
(see above definitions, FC only)
'columns': list of FC search dicts (see above definitions, SC only)
@@ -410,7 +410,7 @@
--> [('name1', ), ('name2', ), ...]
Get id and shortname of all FCs that are parametrized by
a time dimension along the primary axis:
- tunit = PhysicalQuantity(1, 's')
+ tunit = Quantity(1, 's')
get_andsearch_result(['id', 'shortname'],
{'type':'field',
'dimensions':[{'unit':tunit}]})
Modified: trunk/src/pyphant/pyphant/core/PyTablesPersister.py
===================================================================
--- trunk/src/pyphant/pyphant/core/PyTablesPersister.py 2010-02-12 16:21:58 UTC (rev 667)
+++ trunk/src/pyphant/pyphant/core/PyTablesPersister.py 2010-02-21 20:51:58 UTC (rev 668)
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
-# Copyright (c) 2006-2008, Rectorate of the University of Freiburg
+# Copyright (c) 2006-2009, Rectorate of the University of Freiburg
+# Copyright (c) 2009, Andreas W. Liehr (li...@us...)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
@@ -65,7 +66,7 @@
import sys
from pyphant.core import (CompositeWorker, DataContainer)
from tables import StringCol, Col
-from pyphant.quantities.PhysicalQuantities import PhysicalQuantity
+from pyphant.quantities import Quantity
from ImageProcessing.AutoFocus import FocusSlice # For loading FCs...
import scipy
import logging
Modified: trunk/src/pyphant/pyphant/core/SQLiteWrapper.py
===================================================================
--- trunk/src/pyphant/pyphant/core/SQLiteWrapper.py 2010-02-12 16:21:58 UTC (rev 667)
+++ trunk/src/pyphant/pyphant/core/SQLiteWrapper.py 2010-02-21 20:51:58 UTC (rev 668)
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
-# Copyright (c) 2006-2009, Rectorate of the University of Freiburg
+# Copyright (c) 2006-2010, Rectorate of the University of Freiburg
+# Copyright (c) 2010, Andreas W. Liehr (li...@us...)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
@@ -41,17 +42,19 @@
import sqlite3
import time
from pyphant.core.Helpers import (utf82uc, uc2utf8, emd52dict)
-from pyphant.quantities.PhysicalQuantities import (PhysicalQuantity,
- PhysicalUnit)
+from pyphant.quantities import (Quantity,PhysicalUnit,_base_units)
from types import (FloatType, IntType, LongType, StringTypes)
def quantity2powers(quantity):
- if isinstance(quantity, PhysicalQuantity):
- return tuple(quantity.unit.powers)
+ numberOfBaseUnits = len(_base_units)
+ if isinstance(quantity, Quantity):
+ result = tuple(quantity.unit.powers)
+ assert len(result) == numberOfBaseUnits, "Expecting %i base units, but got a tupple of %i unit powers insteat." % (numberOfBaseUnits,len(result))
+ return result
elif isinstance(quantity, (FloatType, IntType, LongType)):
- return (0, ) * 10
+ return (0, ) * numberOfBaseUnits
else:
- raise ValueError("Expected (PhysicalQuantity, FloatType, IntType, "\
+ raise ValueError("Expected (Quantity, FloatType, IntType, "\
"LongType) but got %s instead."\
% (type(quantity), ))
@@ -68,11 +71,11 @@
def quantity2dbase(quantity):
if isinstance(quantity, (FloatType, IntType, LongType)):
return quantity.__repr__()
- elif isinstance(quantity, PhysicalQuantity):
+ elif isinstance(quantity, Quantity):
return "P%s;%s" % (quantity.value.__repr__(),
quantity.getUnitName())
else:
- raise ValueError("Expected (PhysicalQuantity, FloatType, IntType, "\
+ raise ValueError("Expected (Quantity, FloatType, IntType, "\
"LongType) but got %s instead."\
% (type(quantity), ))
@@ -80,7 +83,7 @@
if isinstance(dbase, StringTypes):
if dbase.startswith("P"):
tmp = dbase[1:].split(';')
- return PhysicalQuantity(str2number(tmp[0]), tmp[1])
+ return Quantity(str2number(tmp[0]), tmp[1])
else:
return str2number(dbase)
else:
@@ -273,7 +276,8 @@
('rad', 'INT'),
('sr', 'INT'),
('EUR', 'INT'),
- ('', 'UNIQUE(m, g, s, A, K, mol, cd, rad, sr, EUR)')]
+ ('bit', 'INT'),
+ ('', 'UNIQUE(m, g, s, A, K, mol, cd, rad, sr, EUR,bit)')]
create_table('km_base_units', columns, self.cursor)
#create triggers:
create_trigger('trigger_del_fc', 'DELETE', 'km_fc',
@@ -307,14 +311,14 @@
insert_dict['unit'] = quantity2dbase(summary['unit'])
try:
exe("INSERT OR ABORT INTO km_base_units "\
- "(m, g, s, A, K, mol, cd, rad, sr, EUR) "\
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ "(m, g, s, A, K, mol, cd, rad, sr, EUR, bit) "\
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
quantity2powers(summary['unit']))
l_row_id = self.cursor.lastrowid
except sqlite3.IntegrityError:
exe("SELECT bu_id FROM km_base_units WHERE m=? AND g=? "\
"AND s=? AND A=? AND K=? AND mol=? AND cd=? AND rad=? "\
- "AND sr=? AND EUR=?", quantity2powers(summary['unit']))
+ "AND sr=? AND EUR=? AND bit=?", quantity2powers(summary['unit']))
tmp = self.cursor.fetchone()
assert tmp != None
l_row_id = tmp[0]
@@ -397,17 +401,17 @@
return key
def translate_unit_search(self, value):
- if isinstance(value, PhysicalQuantity):
+ if isinstance(value, Quantity):
value = value.unit.powers
elif isinstance(value, (IntType, LongType, FloatType)):
- value = [0] * 10
+ value = [0] * len(_base_units)
elif isinstance(value, PhysicalUnit):
value = value.powers
else:
raise ValueError(value)
expr = '(bu_id IN (SELECT bu_id FROM km_base_units WHERE '\
'm=? AND g=? AND s=? AND A=? AND K=? AND mol=? '\
- 'AND cd=? AND rad=? AND sr=? AND EUR=?))'
+ 'AND cd=? AND rad=? AND sr=? AND EUR=? AND bit=?))'
return (expr, value, True)
def translate_attr_search(self, value, type):
@@ -539,7 +543,7 @@
use (SQLiteWrapper instance).any_value
or (KM instance).any_value to skip value check
'storage': str types (==)
- 'unit': PhysicalUnit or number or PhysicalQuantity (==, FC only)
+ 'unit': PhysicalUnit or number or Quantity (==, FC only)
'dimensions': list of FC search dicts
(see above definitions, FC only)
'dim_of': str types: emd5 of parent FC (==, FC only)
@@ -559,7 +563,7 @@
--> [('name1', ), ('name2', ), ...]
Get id and shortname of all FCs that are parametrized by
a time dimension along the primary axis:
- tunit = PhysicalQuantity(1, 's')
+ tunit = Quantity(1, 's')
get_andsearch_result(['id', 'shortname'],
{'type':'field',
'dimensions':[{'unit':tunit}]})
Modified: trunk/src/pyphant/pyphant/quantities/ParseQuantities.py
===================================================================
--- trunk/src/pyphant/pyphant/quantities/ParseQuantities.py 2010-02-12 16:21:58 UTC (rev 667)
+++ trunk/src/pyphant/pyphant/quantities/ParseQuantities.py 2010-02-21 20:51:58 UTC (rev 668)
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
-# Copyright (c) 2008, Rectorate of the University of Freiburg
+# Copyright (c) 2008-2009, Rectorate of the University of Freiburg
+# Copyright (c) 2009-2010, Andreas W. Liehr (li...@us...)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
@@ -37,10 +38,12 @@
__version__ = "$Revision$"
# $Source$
-from PhysicalQuantities import PhysicalQuantity
import mx.DateTime.ISO
+from pyphant.quantities import Quantity
def str2unit(unit):
+ """The function str2unit returns either a qu...
[truncated message content] |
|
From: <zk...@us...> - 2010-03-18 11:41:27
|
Revision: 672
http://pyphant.svn.sourceforge.net/pyphant/?rev=672&view=rev
Author: zklaus
Date: 2010-03-18 11:41:19 +0000 (Thu, 18 Mar 2010)
Log Message:
-----------
Merge branch 'master' into svn-trunk
* master:
Enh: Added maxima to mra anaylsis and incorporated it into the parameter estimation.
Modified Paths:
--------------
trunk/doc/demo/viewOSC.py
trunk/src/workers/OSC/OSC/ComputeFunctional.py
trunk/src/workers/OSC/OSC/EstimateParameter.py
trunk/src/workers/OSC/OSC/MRA.py
trunk/src/workers/OSC/OSC/tests/TestMRA.py
Modified: trunk/doc/demo/viewOSC.py
===================================================================
--- trunk/doc/demo/viewOSC.py 2010-03-14 14:26:07 UTC (rev 671)
+++ trunk/doc/demo/viewOSC.py 2010-03-18 11:41:19 UTC (rev 672)
@@ -171,7 +171,8 @@
worker = recipe.getWorker("ThicknessModeller")
simulation = worker.plugCalcAbsorption.getResult()
worker = recipe.getWorker("MRA Exp")
- minimaPos = worker.plugMra.getResult().inUnitsOf(simulation.dimensions[1])
+ minimaPos = worker.plugMra.getResult()[r'\lambda_{min}'].inUnitsOf(simulation.dimensions[1])
+ maximaPos = worker.plugMra.getResult()[r'\lambda_{max}'].inUnitsOf(simulation.dimensions[1])
worker = recipe.getWorker("AddColumn")
table = worker.plugCompute.getResult(subscriber=TextSubscriber("Add Column"))
xPos = table[u"x-position"]
@@ -196,6 +197,12 @@
label ="$\\Delta%s$"%minimaPos.shortname, linestyle='dashed')
pylab.vlines(minimaPos.data[:,index]-minimaPos.error[:,index],0.1,1.0,
label ="$\\Delta%s$"%minimaPos.shortname, linestyle='dashed')
+ pylab.vlines(maximaPos.data[:,index],0.1,1.0,
+ label ="$%s$"%maximaPos.shortname)
+ pylab.vlines(minimaPos.data[:,index]+maximaPos.error[:,index],0.1,1.0,
+ label ="$\\Delta%s$"%maximaPos.shortname, linestyle='dashed')
+ pylab.vlines(maximaPos.data[:,index]-maximaPos.error[:,index],0.1,1.0,
+ label ="$\\Delta%s$"%maximaPos.shortname, linestyle='dashed')
pylab.title(result)
pylab.xlabel(simulation.dimensions[1].label)
@@ -205,7 +212,8 @@
worker = recipe.getWorker("ThicknessModeller")[0]
simulation = worker.plugCalcAbsorption.getResult()
worker = recipe.getWorker("MRA Exp")
- minimaPos = worker.plugMra.getResult().inUnitsOf(simulation.dimensions[1])
+ minimaPos = worker.plugMra.getResult()[r'\lambda_{min}'].inUnitsOf(simulation.dimensions[1])
+ maximaPos = worker.plugMra.getResult()[r'\lambda_{max}'].inUnitsOf(simulation.dimensions[1])
worker = recipe.getWorker("AddColumn")
table = worker.plugCompute.getResult(subscriber=TextSubscriber("Add Column"))
xPos = table[u"x-position"]
@@ -222,6 +230,8 @@
if not noIndicators:
pylab.vlines(minimaPos.data[:,index],0.1,1.0,
label ="$%s$"%minimaPos.shortname)
+ pylab.vlines(maximaPos.data[:,index],0.1,1.0,
+ label ="$%s$"%maximaPos.shortname)
pylab.title(result)
pylab.xlabel(simulation.dimensions[1].label)
pylab.ylabel(simulation.label)
@@ -239,11 +249,12 @@
def functional(recipe, curvNo, noIndicators):
worker = recipe.getWorker("Compute Functional")
- functional = worker.plugCompute.getResult()
+ functional = worker.plugCompute.getResult()[r'F_{\lambda_{min}}']
worker = recipe.getWorker("ThicknessModeller")
simulation = worker.plugCalcAbsorption.getResult()
worker = recipe.getWorker("MRA Exp")
- minimaPos = worker.plugMra.getResult().inUnitsOf(simulation.dimensions[1])
+ minimaPos = worker.plugMra.getResult()[r'\lambda_{min}'].inUnitsOf(simulation.dimensions[1])
+ maximaPos = worker.plugMra.getResult()[r'\lambda_{max}'].inUnitsOf(simulation.dimensions[1])
worker = recipe.getWorker("AddColumn")
table = worker.plugCompute.getResult(subscriber=TextSubscriber("Add Column"))
thickness = table[u"thickness"]
@@ -253,6 +264,8 @@
ordinate = functional.dimensions[1].data
pylab.hlines(minimaPos.data[:,index],ordinate.min(),ordinate.max(),
label ="$%s$"%minimaPos.shortname)
+ pylab.hlines(maximaPos.data[:,index],ordinate.min(),ordinate.max(),
+ label ="$%s$"%maximaPos.shortname)
abscissae = functional.dimensions[0].data
pylab.vlines(thickness.data[index],abscissae.min(),abscissae.max(),
label ="$%s$"%minimaPos.shortname)
@@ -265,7 +278,8 @@
thickness = table[u"thickness"]
index = curvNo2Index(table[u"pixel"], curvNo)
worker = recipe.getWorker("MRA Exp")
- minimaPos = worker.plugMra.getResult().inUnitsOf(simulation.dimensions[1])
+ minimaPos = worker.plugMra.getResult()[r'\lambda_{min}'].inUnitsOf(simulation.dimensions[1])
+ maximaPos = worker.plugMra.getResult()[r'\lambda_{max}'].inUnitsOf(simulation.dimensions[1])
visualizer = ImageVisualizer(simulation, False)
ordinate = simulation.dimensions[1].data
if not noIndicators:
@@ -274,6 +288,8 @@
abscissae = simulation.dimensions[0].data
pylab.vlines(minimaPos.data[:,index],abscissae.min(),abscissae.max(),
label ="$%s$"%minimaPos.shortname)
+ pylab.vlines(maximaPos.data[:,index],abscissae.min(),abscissae.max(),
+ label ="$%s$"%maximaPos.shortname)
def dumpMinima(recipe):
worker = recipe.getWorker("ThicknessModeller")
@@ -286,7 +302,7 @@
thickness = table[u"thickness"]
cols = [index, xPos, yPos, thickness]
worker = recipe.getWorker("MRA Exp")
- minimaPos = worker.plugMra.getResult().inUnitsOf(simulation.dimensions[1])
+ minimaPos = worker.plugMra.getResult()[r'\lambda_{min}'].inUnitsOf(simulation.dimensions[1])
import numpy
data = numpy.vstack([ c.data for c in cols]
+ numpy.vsplit(minimaPos.data, len(minimaPos.data))).transpose()
Modified: trunk/src/workers/OSC/OSC/ComputeFunctional.py
===================================================================
--- trunk/src/workers/OSC/OSC/ComputeFunctional.py 2010-03-14 14:26:07 UTC (rev 671)
+++ trunk/src/workers/OSC/OSC/ComputeFunctional.py 2010-03-18 11:41:19 UTC (rev 672)
@@ -53,7 +53,7 @@
REVISION = "$Revision$"[11:-1]
name = "Compute Functional"
- _sockets = [("field", Connectors.TYPE_IMAGE)]
+ _sockets = [("field", Connectors.TYPE_ARRAY)]
_params = [("extentX", u"Extension of x-axis [%%]", 10, None),
("extentY", u"Extension of y-axis [%%]", 10, None)]
@@ -92,13 +92,15 @@
subscriber %= percentage
result = DataContainer.FieldContainer(functional.transpose(),
dimensions=[yDim, xDim],
- longname = 'functional',
- shortname= 'F'
+ longname = 'functional of %s'%field.longname,
+ shortname= 'F_{%s}'%field.shortname
)
return result
- @Worker.plug(Connectors.TYPE_IMAGE)
+ @Worker.plug(Connectors.TYPE_ARRAY)
def compute(self, field, subscriber=1):
- functional = self.computeDistances(field, subscriber)
- functional.seal()
- return functional
+ functionals = DataContainer.SampleContainer([self.computeDistances(column, subscriber) for column in field],
+ longname='Functionals of %s'%field.longname,
+ shortname='F_{%s}'%field.shortname)
+ functionals.seal()
+ return functionals
Modified: trunk/src/workers/OSC/OSC/EstimateParameter.py
===================================================================
--- trunk/src/workers/OSC/OSC/EstimateParameter.py 2010-03-14 14:26:07 UTC (rev 671)
+++ trunk/src/workers/OSC/OSC/EstimateParameter.py 2010-03-18 11:41:19 UTC (rev 672)
@@ -51,20 +51,34 @@
REVISION = "$Revision$"[11:-1]
name = "Estimate Parameter"
- _sockets = [("model", Connectors.TYPE_IMAGE),
- ("experimental", Connectors.TYPE_IMAGE)]
- _params = [("extentX", u"Extension of x-axis [%%]", 10, None),
+ _sockets = [("model", Connectors.TYPE_ARRAY),
+ ("experimental", Connectors.TYPE_ARRAY)]
+ _params = [("minima_model", u"Minima in the model", [u"Minima"], None),
+ ("maxima_model", u"Maxima in the model", [u"Maxima"], None),
+ ("minima_experimental", u"Minima in the experiment", [u"Minima"], None),
+ ("maxima_experimental", u"Maxima in the experiment", [u"Maxima"], None),
+ ("extentX", u"Extension of x-axis [%%]", 10, None),
("extentY", u"Extension of y-axis [%%]", 10, None)]
- def calculateThickness(self, row, model, error=None):
+ def refreshParams(self, subscriber=None):
+ if self.socketModel.isFull():
+ templ = self.socketModel.getResult( subscriber )
+ self.paramMinima_model.possibleValues = templ.longnames.keys()
+ self.paramMaxima_model.possibleValues = templ.longnames.keys()
+ if self.socketExperimental.isFull():
+ templ = self.socketExperimental.getResult( subscriber )
+ self.paramMinima_experimental.possibleValues = templ.longnames.keys()
+ self.paramMaxima_experimental.possibleValues = templ.longnames.keys()
+
+ def calculateThickness(self, row_minima, row_maxima, minima_model, maxima_model,
+ minima_error=None, maxima_error=None):
"""
Given a vector of minima (row) and a 2 dimensional model,
this estimates the corresponding parameter.
"""
- if len(row)==0:
+ if len(row_minima)+len(row_maxima)==0:
return numpy.nan
- data = model.data.transpose()
- def calc(row, col, error):
+ def calc(row, model, col, error):
if error:
weight=0
for c,e in zip(row, error):
@@ -78,38 +92,68 @@
else:
return sum([col[numpy.argmin((model.dimensions[0].data-c)**2)]
for c in row])
- i = numpy.argmin(numpy.array([calc(row, col, error) for col in data]))
- return model.dimensions[1].data[i]
+ minima_data = minima_model.data.transpose()
+ maxima_data = maxima_model.data.transpose()
+ i = numpy.argmin(numpy.array([calc(row_minima, minima_model, minima_col, minima_error)
+ +calc(row_maxima, maxima_model, maxima_col, maxima_error)
+ for minima_col, maxima_col in
+ zip(minima_data, maxima_data)]))
+ assert(minima_model.dimensions[1].data[i]==maxima_model.dimensions[1].data[i])
+ return minima_model.dimensions[1].data[i]
@Worker.plug(Connectors.TYPE_IMAGE)
def compute(self, model, experimental, subscriber=1):
- renormedExp = experimental.inUnitsOf(model.dimensions[0])
- minima = renormedExp.data.transpose()
- if renormedExp.error != None:
- error = iter(renormedExp.error.transpose())
+ minima_model = model[self.paramMinima_model.value]
+ maxima_model = model[self.paramMaxima_model.value]
+ minima_experimental = experimental[
+ self.paramMinima_experimental.value
+ ].inUnitsOf(
+ minima_model.dimensions[0]
+ )
+ maxima_experimental = experimental[
+ self.paramMaxima_experimental.value
+ ].inUnitsOf(
+ maxima_model.dimensions[0]
+ )
+ minima = minima_experimental.data.transpose()
+ if minima_experimental.error != None:
+ minima_error = iter(minima_experimental.error.transpose())
else:
- error = None
+ minima_error = None
+ maxima = maxima_experimental.data.transpose()
+ if maxima_experimental.error != None:
+ maxima_error = iter(maxima_experimental.error.transpose())
+ else:
+ maxima_error = None
parameter = []
inc = 100.0/float(len(minima))
acc = inc
subscriber %= acc
- for row in minima:
- if error:
- filteredError = filter(
- lambda c: not numpy.isnan(c), error.next())
+ for row_minima, row_maxima in zip(minima, maxima):
+ if minima_error:
+ filtered_minima_error = filter(
+ lambda c: not numpy.isnan(c), minima_error.next())
else:
- filteredError = None
+ filtered_minima_error = None
+ if maxima_error:
+ filtered_maxima_error = filter(
+ lambda c: not numpy.isnan(c), maxima_error.next())
+ else:
+ filtered_maxima_error = None
parameter.append(self.calculateThickness(
- filter(lambda c: not numpy.isnan(c), row),
- model,
- filteredError
+ filter(lambda c: not numpy.isnan(c), row_minima),
+ filter(lambda c: not numpy.isnan(c), row_maxima),
+ minima_model,
+ maxima_model,
+ filtered_minima_error,
+ filtered_maxima_error
))
acc += inc
subscriber %= acc
result = DataContainer.FieldContainer(
numpy.array(parameter),
- longname = model.dimensions[-1].longname,
- shortname = model.dimensions[-1].shortname,
- unit = model.dimensions[-1].unit)
+ longname = minima_model.dimensions[-1].longname,
+ shortname = minima_model.dimensions[-1].shortname,
+ unit = minima_model.dimensions[-1].unit)
result.seal()
return result
Modified: trunk/src/workers/OSC/OSC/MRA.py
===================================================================
--- trunk/src/workers/OSC/OSC/MRA.py 2010-03-14 14:26:07 UTC (rev 671)
+++ trunk/src/workers/OSC/OSC/MRA.py 2010-03-18 11:41:19 UTC (rev 672)
@@ -1,8 +1,9 @@
# -*- coding: utf-8 -*-
-# Copyright (c) 2008-2009, Rectorate of the University of Freiburg
+# Copyright (c) 2008-2010, Rectorate of the University of Freiburg
# Copyright (c) 2009, Andreas W. Liehr (li...@us...)
-# All rights reserved.
+# Copyright (c) 2010, Klaus Zimmermann (zk...@us...)
+# all rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
@@ -49,12 +50,29 @@
from scipy.special import ive
from scipy.signal import convolve
+def findMaxima(fieldData, lastExtrema=None):
+ leftLess = fieldData[:-2] < fieldData[1:-1]
+ leftEqual = fieldData[:-2] == fieldData[1:-1]
+ rightLess = fieldData[2:] < fieldData[1:-1]
+ rightEqual = fieldData[2:] == fieldData[1:-1]
+ maxima_c = numpy.logical_and(leftLess, rightLess)
+ maxima_le = numpy.logical_and(leftLess, rightEqual)
+ maxima_re = numpy.logical_and(rightLess, leftEqual)
+ maxima_e = numpy.logical_and(maxima_le[:-1], maxima_re[1:])
+ maxima = numpy.logical_or(maxima_c[1:], maxima_e).nonzero()[0]
+ if lastExtrema==None or len(maxima)==0 or len(lastExtrema)==len(maxima):
+ return maxima
+ trackedMaxima = []
+ for lastMaximum in lastExtrema:
+ distance = (maxima-lastMaximum)**2
+ trackedMaxima.append(distance.argmin())
+ return maxima[trackedMaxima]
+
def findMinima(fieldData, lastExtrema=None):
leftGreater = fieldData[:-2] > fieldData[1:-1]
leftEqual = fieldData[:-2] == fieldData[1:-1]
rightGreater = fieldData[2:] > fieldData[1:-1]
rightEqual = fieldData[2:] == fieldData[1:-1]
-
minima_c = numpy.logical_and(leftGreater, rightGreater)
minima_le = numpy.logical_and(leftGreater, rightEqual)
minima_re = numpy.logical_and(rightGreater, leftEqual)
@@ -75,17 +93,6 @@
kernel = ive(numpy.arange(-n, n), sigma)
return convolve(field.data, kernel, mode='same')
-#def mra1d(dim, field, n):
-# mrr = [convolveMRA(field, sigma) for sigma in
-# numpy.linspace(1, n,10).tolist()]
-# mrr.insert(0,field.data)
-# firstMinima = lastMinima = findMinima(mrr[-1], None)
-# for row in reversed(mrr[:-1]):
-# lastMinima = findMinima(row, lastMinima)
-# pos = dim.data[numpy.array(lastMinima)+1]
-# error = numpy.abs(pos - dim.data[numpy.array(firstMinima)+1])
-# return pos, error
-
class MraError(RuntimeError):
def __init__(self, msg, convolvedField):
RuntimeError.__init__(self, msg)
@@ -95,20 +102,30 @@
sigmaSpace = numpy.linspace(n, 1, 10)
convolvedField = convolveMRA(field, sigmaSpace[0])
firstMinima = lastMinima = findMinima(convolvedField, None)
- if len(firstMinima)==0:
- raise MraError("No Minima found at sigma level %s"%sigmaSpace[0],
+ firstMaxima = lastMaxima = findMaxima(convolvedField, None)
+ if len(firstMinima)==0 and len(firstMaxima)==0:
+ raise MraError("No Extrema found at sigma level %s"%sigmaSpace[0],
convolvedField)
for sigma in sigmaSpace[1:]:
convolvedField = convolveMRA(field, sigma)
lastMinima = findMinima(convolvedField, lastMinima)
- if len(lastMinima)==0:
- import pylab
- pylab.plot(convolvedField)
- pylab.show()
- pos = dim.data[numpy.array(lastMinima)+1]
- error = numpy.abs(pos - dim.data[numpy.array(firstMinima)+1])
- return pos, error
+ lastMaxima = findMaxima(convolvedField, lastMaxima)
+ pos_minima = dim.data[numpy.array(lastMinima)+1]
+ error_minima = numpy.abs(pos_minima - dim.data[numpy.array(firstMinima)+1])
+ pos_maxima = dim.data[numpy.array(lastMaxima)+1]
+ error_maxima = numpy.abs(pos_maxima - dim.data[numpy.array(firstMaxima)+1])
+ return ((pos_minima, error_minima), (pos_maxima, error_maxima))
+def pos_error_to_data_container(p_e):
+ n = max(map(lambda (p,e): len(p), p_e))
+ m = len(p_e)
+ pos = numpy.ones((m,n),'float')*numpy.NaN
+ error = pos.copy()
+ for i in xrange(m):
+ for j in xrange(len(p_e[i][0])):
+ pos[i,j] = p_e[i][0][j]
+ error[i,j] = p_e[i][1][j]
+ return n, pos, error
class MRA(Worker.Worker):
API = 2
@@ -121,7 +138,7 @@
("longname",u"Name of result",'default',None),
("symbol",u"Symbol of result",'default',None)]
- @Worker.plug(Connectors.TYPE_IMAGE)
+ @Worker.plug(Connectors.TYPE_ARRAY)
def mra(self, field, subscriber=0):
dim = field.dimensions[-1]
try:
@@ -139,30 +156,36 @@
try:
p_e.append(mra1d(dim, field1d, sigmaMax))
except MraError:
- p_e.append(([],[]))
+ p_e.append((([],[]),([],[])))
acc += inc
subscriber %= acc
- n = max(map(lambda (p,e): len(p), p_e))
- m = len(p_e)
- pos = numpy.ones((m,n),'float')*numpy.NaN
- error = pos.copy()
- for i in xrange(m):
- for j in xrange(len(p_e[i][0])):
- pos[i,j] = p_e[i][0][j]
- error[i,j] = p_e[i][1][j]
- dims = [DataContainer.generateIndex(0,n), field.dimensions[0]]
+ minima, maxima = zip(*p_e)
+ n_min, pos_min, err_min = pos_error_to_data_container(minima)
+ n_max, pos_max, err_max = pos_error_to_data_container(maxima)
+ dims_min = [DataContainer.generateIndex(0,n_min), field.dimensions[0]]
+ dims_max = [DataContainer.generateIndex(0,n_max), field.dimensions[0]]
else:
- pos, error = mra1d(dim, field, sigmaMax)
- n = len(pos)
- dims = [DataContainer.generateIndex(0,n)]
+ (pos_min, err_min), (pos_max, err_max) = mra1d(dim, field, sigmaMax)
+ dims_min = [DataContainer.generateIndex(0,len(pos_min))]
+ dims_max = [DataContainer.generateIndex(0,len(pos_max))]
subscriber %= 100.
- roots = DataContainer.FieldContainer(pos.transpose(),
- error = error.transpose(),
- unit = dim.unit,
- dimensions = dims,
- mask = numpy.isnan(pos).transpose(),
- longname="%s of the local %s of %s" % (dim.longname,"minima",field.longname),
- shortname="%s_0" % dim.shortname)
+ minima = DataContainer.FieldContainer(pos_min.transpose(),
+ error = err_min.transpose(),
+ unit = dim.unit,
+ dimensions = dims_min,
+ mask = numpy.isnan(pos_min).transpose(),
+ longname="%s of the local %s of %s" % (dim.longname,"minima",field.longname),
+ shortname="%s_{min}" % dim.shortname)
+ maxima = DataContainer.FieldContainer(pos_max.transpose(),
+ error = err_max.transpose(),
+ unit = dim.unit,
+ dimensions = dims_max,
+ mask = numpy.isnan(pos_max).transpose(),
+ longname="%s of the local %s of %s" % (dim.longname,"maxima",field.longname),
+ shortname="%s_{max}" % dim.shortname)
+ roots = DataContainer.SampleContainer([minima, maxima],
+ longname="%s of the local %s of %s" % (dim.longname,"extrema",field.longname),
+ shortname="%s_{extrem}" % dim.shortname)
if self.paramLongname.value != 'default':
roots.longname = self.paramLongname.value
if self.paramSymbol.value != 'default':
Modified: trunk/src/workers/OSC/OSC/tests/TestMRA.py
===================================================================
--- trunk/src/workers/OSC/OSC/tests/TestMRA.py 2010-03-14 14:26:07 UTC (rev 671)
+++ trunk/src/workers/OSC/OSC/tests/TestMRA.py 2010-03-18 11:41:19 UTC (rev 672)
@@ -87,8 +87,26 @@
w.paramScale.value = "1.0m"
result = w.mra(self.V)
#Testing
- numpy.testing.assert_array_almost_equal(result.data,expectedResult.data,4)
+ numpy.testing.assert_array_almost_equal(result[r'x_{min}'].data,expectedResult.data,4)
+ def testMaxima(self):
+ """Test the correct computation of all local minima for a bistable potential."""
+ #Predict result
+ x0,curv,mask = fixedPoints(numpy.array([self.LAMBDA]),kappa1=self.kappa1)
+ expectedResult = DC.FieldContainer(numpy.extract(curv[0]>0,x0[0]),
+ unit = self.xField.unit,
+ longname = 'position of the local minima of electric potential',
+ shortname = 'x_0')
+ #Retrieve result from worker
+ w = MRA.MRA(None)
+ w.paramScale.value = "1.0m"
+ V = copy.deepcopy(self.V)
+ V.data*=-1
+ result = w.mra(V)
+ #Testing
+ numpy.testing.assert_array_almost_equal(result[r'x_{max}'].data,expectedResult.data,4)
+
+
class TestExtremumFinderTable(unittest.TestCase):
"""Sets up a mirror symmetric bistable potential with a continuous
distretisation and computes its local extrema and the respective
@@ -142,7 +160,7 @@
w = MRA.MRA(None)
w.paramScale.value = "1.0m"
#Retrieve result from worker
- result = copy.deepcopy(w.mra(self.V))
+ result = copy.deepcopy(w.mra(self.V))['x_{min}']
result.error=None
self.test(result,expectedResult,1e-2,1e-2)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <zk...@us...> - 2010-06-17 16:17:53
|
Revision: 685
http://pyphant.svn.sourceforge.net/pyphant/?rev=685&view=rev
Author: zklaus
Date: 2010-06-17 16:17:44 +0000 (Thu, 17 Jun 2010)
Log Message:
-----------
Merge branch 'master' into svn-trunk
* master:
Enh: rich comparison for Quantity
Enh: Added ZStack Visualizer
Enh: Refactored ZStack and AutoFocus
Enh: Emd5Src
Fix: SQLiteWrapper, SliceSelector
Fix: Removed unused workers
Enh: Feedback during update
Fix: WebInterface order_by
Cosm: gitignore
Fix: Handle broken toolboxes
Fix: Typo
Enh: NDImage Worker
Enh: Improved ZStack
Modified Paths:
--------------
trunk/.gitignore
trunk/src/pyphant/pyphant/cli/pyphant_exec.py
trunk/src/pyphant/pyphant/core/Connectors.py
trunk/src/pyphant/pyphant/core/EventDispatcher.py
trunk/src/pyphant/pyphant/core/Param.py
trunk/src/pyphant/pyphant/core/PyTablesPersister.py
trunk/src/pyphant/pyphant/core/SQLiteWrapper.py
trunk/src/pyphant/pyphant/core/WebInterface.py
trunk/src/pyphant/pyphant/core/ZStackManager.py
trunk/src/pyphant/pyphant/quantities/__init__.py
trunk/src/pyphant/pyphant/tests/TestQuantities.py
trunk/src/pyphant/pyphant/tests/TestZStacks.py
trunk/src/pyphant/pyphant/visualizers/__init__.py
trunk/src/pyphant/pyphant/wxgui2/paramvisualization/ListSelect.py
trunk/src/pyphant/pyphant/wxgui2/paramvisualization/ParamVisReg.py
trunk/src/pyphant/pyphant/wxgui2/wxPyphantApplication.py
trunk/src/workers/ImageProcessing/ImageProcessing/AutoFocus.py
trunk/src/workers/ImageProcessing/ImageProcessing/NDImageWorker.py
trunk/src/workers/ImageProcessing/ImageProcessing/SliceSelector.py
trunk/src/workers/ImageProcessing/ImageProcessing/__init__.py
trunk/src/workers/tools/tools/Emd5Src.py
trunk/src/workers/tools/tools/__init__.py
trunk/src/workers/tools/tools/tests/TestEmd5Source.py
Added Paths:
-----------
trunk/src/pyphant/pyphant/visualizers/ZStackVisualizer.py
trunk/src/workers/ImageProcessing/ImageProcessing/MarkAF.py
trunk/src/workers/tools/tools/FCSource.py
trunk/src/workers/tools/tools/SCSource.py
Removed Paths:
-------------
trunk/src/pyphant/pyphant/core/RecipeAlg.py
trunk/src/pyphant/pyphant/tests/TestAutoFocus.py
trunk/src/pyphant/pyphant/tests/resources/recipes/AutoFocus.h5
trunk/src/pyphant/pyphant/tests/resources/recipes/MeasureFocus.h5
trunk/src/pyphant/pyphant/tests/resources/recipes/pre-MF-no-median.h5
trunk/src/workers/ImageProcessing/ImageProcessing/MeasureFocus.py
trunk/src/workers/ImageProcessing/ImageProcessing/ZStacks.py
trunk/src/workers/tools/tools/BatchExtractor.py
trunk/src/workers/tools/tools/BatchHead.py
trunk/src/workers/tools/tools/BatchTail.py
trunk/src/workers/tools/tools/ParameterRun.py
Modified: trunk/.gitignore
===================================================================
--- trunk/.gitignore 2010-05-26 20:45:06 UTC (rev 684)
+++ trunk/.gitignore 2010-06-17 16:17:44 UTC (rev 685)
@@ -17,3 +17,4 @@
*.out
*.bst
*.bbl
+.ropeproject/
Modified: trunk/src/pyphant/pyphant/cli/pyphant_exec.py
===================================================================
--- trunk/src/pyphant/pyphant/cli/pyphant_exec.py 2010-05-26 20:45:06 UTC (rev 684)
+++ trunk/src/pyphant/pyphant/cli/pyphant_exec.py 2010-06-17 16:17:44 UTC (rev 685)
@@ -59,10 +59,10 @@
w = recipe.getWorker(sSpec[0])
s = getattr(w, sSpec[-1])
src = Emd5Src.Emd5Src(recipe)
- src.paramDc.value=emd5
+ src.paramEmd5.value=emd5
if s.isFull():
s.pullPlug()
- s.insert(src.plugLoad)
+ s.insert(src.plugGetDataContainer)
pSpec = order[1][0].split('.')
d = recipe.getWorker(pSpec[0])
plug = getattr(d, pSpec[1])
Modified: trunk/src/pyphant/pyphant/core/Connectors.py
===================================================================
--- trunk/src/pyphant/pyphant/core/Connectors.py 2010-05-26 20:45:06 UTC (rev 684)
+++ trunk/src/pyphant/pyphant/core/Connectors.py 2010-06-17 16:17:44 UTC (rev 685)
@@ -48,6 +48,7 @@
TYPE_INT = type(2)
TYPE_STRING = type("")
SUBTYPE_FILE = "filename"
+SUBTYPE_INSTANT = "instant"
TYPE_INACTIVE = type(None)
TYPE_BOOL = type(True)
DEFAULT_DATA_TYPE = TYPE_ARRAY
Modified: trunk/src/pyphant/pyphant/core/EventDispatcher.py
===================================================================
--- trunk/src/pyphant/pyphant/core/EventDispatcher.py 2010-05-26 20:45:06 UTC (rev 684)
+++ trunk/src/pyphant/pyphant/core/EventDispatcher.py 2010-06-17 16:17:44 UTC (rev 685)
@@ -47,6 +47,14 @@
except KeyError:
self._listeners[eventType] = [listener]
+ # The following method is a quick workaround for the shortcoming
+ # of this EventDispatcher which offers no control, in which
+ # order listeners for the same event are called and the
+ # event interface is not specified at all, so there is no
+ # functionality like event.skip()
+ def registerExclusiveListener(self, listener, eventType):
+ self._listeners[eventType] = [listener]
+
def unregisterListener(self, listener, eventType=None):
if eventType:
self._listeners[eventType].remove( listener )
Modified: trunk/src/pyphant/pyphant/core/Param.py
===================================================================
--- trunk/src/pyphant/pyphant/core/Param.py 2010-05-26 20:45:06 UTC (rev 684)
+++ trunk/src/pyphant/pyphant/core/Param.py 2010-06-17 16:17:44 UTC (rev 685)
@@ -47,18 +47,40 @@
return Param(worker, paramName, displayName, values, subtype)
+class ParamChangeExpected(object):
+ def __init__(self, param, expectedValue):
+ self.param = param
+ self.expectedValue = expectedValue
+
+
+class PossibleValuesChangeExpected(object):
+ def __init__(self, param, expectedPVs, update=False):
+ self.param = param
+ self.expectedPVs = expectedPVs
+ self.update = update
+
+
class ParamChangeRequested(object):
def __init__(self, param, oldValue, newValue):
self.param = param
self.oldValue = oldValue
self.newValue = newValue
+
class ParamChanged(object):
def __init__(self, param, oldValue, newValue):
self.param = param
self.oldValue = oldValue
self.newValue = newValue
+
+class ParamOverridden(object):
+ def __init__(self, param, oldValue, newValue):
+ self.param = param
+ self.oldValue = oldValue
+ self.newValue = newValue
+
+
class VetoParamChange(ValueError):
def __init__(self, paramChangeEvent):
ValueError.__init__(self, "Veto: change %s from %s to %s." %
@@ -67,6 +89,7 @@
paramChangeEvent.newValue))
self.paramChangeEvent = paramChangeEvent
+
class Param(Connectors.Socket):
def __getValue(self):
if self.isFull():
@@ -75,7 +98,10 @@
return self._value
def overrideValue(self, value):
+ oldValue = self._value
self._value = value
+ self._eventDispatcher.dispatchEvent(
+ ParamOverridden(self, oldValue, value))
def __setValue(self, value):
oldValue = self.value
Modified: trunk/src/pyphant/pyphant/core/PyTablesPersister.py
===================================================================
--- trunk/src/pyphant/pyphant/core/PyTablesPersister.py 2010-05-26 20:45:06 UTC (rev 684)
+++ trunk/src/pyphant/pyphant/core/PyTablesPersister.py 2010-06-17 16:17:44 UTC (rev 685)
@@ -68,7 +68,6 @@
from tables import StringCol, Col
from pyphant.quantities import Quantity
from pyphant.quantities import Quantity as PhysicalQuantity
-from ImageProcessing.AutoFocus import FocusSlice # For loading FCs...
import scipy
import logging
_logger = logging.getLogger("pyphant")
Deleted: trunk/src/pyphant/pyphant/core/RecipeAlg.py
===================================================================
--- trunk/src/pyphant/pyphant/core/RecipeAlg.py 2010-05-26 20:45:06 UTC (rev 684)
+++ trunk/src/pyphant/pyphant/core/RecipeAlg.py 2010-06-17 16:17:44 UTC (rev 685)
@@ -1,148 +0,0 @@
-#!/usr/bin/env python2.5
-# -*- coding: utf-8 -*-
-
-# Copyright (c) 2006-2009, Rectorate of the University of Freiburg
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above copyright
-# notice, this list of conditions and the following disclaimer in the
-# documentation and/or other materials provided with the distribution.
-# * Neither the name of the Freiburg Materials Research Center,
-# University of Freiburg nor the names of its contributors may be used to
-# endorse or promote products derived from this software without specific
-# prior written permission.
-#
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
-# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
-# OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
-
-u"""Provides ZStackManager
-"""
-
-__id__ = "$Id$".replace('$','')
-__author__ = "$Author$".replace('$','')
-__version__ = "$Revision$".replace('$','')
-# $Source$
-
-from pyphant.core.KnowledgeManager import KnowledgeManager
-from pyphant.core.PyTablesPersister import loadRecipeFromHDF5File
-from tools import Emd5Src
-import os
-kmanager = KnowledgeManager.getInstance()
-
-
-class RecipeAlg(object):
- def __init__(self, recipe_fname, result_worker,
- result_plug, params={}):
- self.recipe_fname = recipe_fname
- self.recipe = loadRecipeFromHDF5File(recipe_fname)
- self.params = params
- self.rwn = result_worker
- self.rpn = result_plug
- self.result_plug = self.recipe.getWorker(
- result_worker).getPlug(result_plug)
-
- def get_result(self, input_ids, id_only=False, temporary=False):
- from pyphant.core.Helpers import utf82uc
- search_dict = {'attributes':{
- 'recipe':utf82uc(self.recipe_fname),
- 'result_worker':utf82uc(self.rwn),
- 'result_plug':utf82uc(self.rpn),
- 'applied_to':utf82uc(input_ids.__repr__()),
- 'params':utf82uc(self.params.__repr__())}}
- result_ids = kmanager.search(['id'], search_dict)
- if len(result_ids) > 0 and not temporary:
- if id_only:
- return result_ids[0][0]
- else:
- return kmanager.getDataContainer(result_ids[0][0])
- else:
- # Fill open sockets:
- for wname, sockets in input_ids.iteritems():
- worker = self.recipe.getWorker(wname)
- for sname, emd5 in sockets.iteritems():
- socket = worker.getSocket(sname)
- dummy = Emd5Src.Emd5Src()
- dummy.paramSelectby.value = u"enter emd5"
- dummy.paramEnteremd5.value = emd5
- socket.insert(dummy.getPlugs()[0])
- # Set parameters:
- for wname, wparams in self.params.iteritems():
- for pname, pvalue in wparams.iteritems():
- self.recipe.getWorker(wname).getParam(pname).value = pvalue
- # Get Result
- result_dc = self.result_plug.getResult()
- # Pull plugs
- for wname, sockets in input_ids.iteritems():
- worker = self.recipe.getWorker(wname)
- for sname, emd5 in sockets.iteritems():
- worker.getSocket(sname).pullPlug()
- result_dc.attributes['recipe'] = utf82uc(self.recipe_fname)
- result_dc.attributes['applied_to'] = utf82uc(input_ids.__repr__())
- result_dc.attributes['params'] = utf82uc(self.params.__repr__())
- result_dc.attributes['result_plug'] = utf82uc(self.rpn)
- result_dc.attributes['result_worker'] = utf82uc(self.rwn)
- kmanager.registerDataContainer(result_dc, temporary=temporary)
- if id_only:
- return result_dc.id
- else:
- return result_dc
-
- def get_batch_result_id(self, input_ids, column='emd5', update_attrs={},
- subscriber=0, start=1, end=100, temporary=False):
- subscriber %= start
- from pyphant.core.Helpers import utf82uc
- search_dict = {'attributes':{
- 'batch_recipe':utf82uc(self.recipe_fname),
- 'result_worker':utf82uc(self.rwn),
- 'result_plug':utf82uc(self.rpn),
- 'applied_to':utf82uc(input_ids.__repr__()),
- 'params':utf82uc(self.params.__repr__())}}
- result_ids = kmanager.search(['id'], search_dict)
- if len(result_ids) > 0:
- subscriber %= end
- return result_ids[0][0]
- import copy
- input_scs = dict([(wname, dict([(sname, kmanager.getDataContainer(emd5)) \
- for sname, emd5 in sockets.iteritems()])) \
- for wname, sockets in input_ids.iteritems()])
- out_column = []
- ref_sc = input_scs.values()[0].values()[0]
- output_sc = copy.deepcopy(ref_sc)
- import numpy
- sharpruns = len(ref_sc[column].data)
- import math
- for index in xrange(sharpruns):
- subscriber %= 1 + math.floor(start + float((end - start) * index) \
- / sharpruns)
- ids = dict([(wname, dict([(sname, unicode(isc[column].data[index])) \
- for sname, isc in sockets.iteritems()])) \
- for wname, sockets in input_scs.iteritems()])
- out_column.append(self.get_result(ids, id_only=True))
- output_sc[column].data = numpy.array(out_column)
- output_sc.longname = "%s_%s" % (os.path.basename(self.recipe_fname),
- ref_sc.longname)
- output_sc.attributes['batch_recipe'] = utf82uc(self.recipe_fname)
- output_sc.attributes['applied_to'] = utf82uc(input_ids.__repr__())
- output_sc.attributes['result_plug'] = utf82uc(self.rpn)
- output_sc.attributes['result_worker'] = utf82uc(self.rwn)
- output_sc.attributes['params'] = utf82uc(self.params.__repr__())
- output_sc.attributes.update(update_attrs)
- output_sc.seal()
- kmanager.registerDataContainer(output_sc, temporary=temporary)
- subscriber %= end
- return output_sc.id
Modified: trunk/src/pyphant/pyphant/core/SQLiteWrapper.py
===================================================================
--- trunk/src/pyphant/pyphant/core/SQLiteWrapper.py 2010-05-26 20:45:06 UTC (rev 684)
+++ trunk/src/pyphant/pyphant/core/SQLiteWrapper.py 2010-06-17 16:17:44 UTC (rev 685)
@@ -189,9 +189,10 @@
one_to_one_result_keys = one_to_one_search_keys + ['date', 'id', 'type']
common_search_keys = one_to_one_search_keys + ['id', 'attributes',
'date_from', 'date_to']
- fc_search_keys = common_search_keys + ['unit', 'dimensions', 'dim_of', 'col_of']
+ fc_search_keys = common_search_keys + ['unit', 'dimensions',
+ 'dim_of', 'col_of']
sc_search_keys = common_search_keys + ['columns']
- sortable_keys = common_keys + ['id', 'storage', 'type']
+ sortable_keys = common_keys + ['storage', 'type']
any_value = AnyValue()
def __init__(self, database, timeout=60.0):
Modified: trunk/src/pyphant/pyphant/core/WebInterface.py
===================================================================
--- trunk/src/pyphant/pyphant/core/WebInterface.py 2010-05-26 20:45:06 UTC (rev 684)
+++ trunk/src/pyphant/pyphant/core/WebInterface.py 2010-06-17 16:17:44 UTC (rev 685)
@@ -593,6 +593,8 @@
+ [key for key in common_keys \
if qry[key] == self.anystr] \
+ ['id']
+ if not order_by in missing_keys:
+ order_by = 'date'
search_result = self.kn.km.search(
missing_keys, search_dict, order_by=order_by,
order_asc=order_asc, limit=limit, offset=offset)
Modified: trunk/src/pyphant/pyphant/core/ZStackManager.py
===================================================================
--- trunk/src/pyphant/pyphant/core/ZStackManager.py 2010-05-26 20:45:06 UTC (rev 684)
+++ trunk/src/pyphant/pyphant/core/ZStackManager.py 2010-06-17 16:17:44 UTC (rev 685)
@@ -45,7 +45,6 @@
import scipy
import Image
from pyphant.core.KnowledgeManager import KnowledgeManager
-from pyphant.core.RecipeAlg import RecipeAlg
import os
kmanager = KnowledgeManager.getInstance()
@@ -53,8 +52,8 @@
class ZStack(object):
def __init__(self, sc_id=None, name=None, xml_file=None, temporary=False):
"""Initializes a ZStack from an existing id or a local source"""
- self.temporary = temporary
assert (sc_id is None) is not (xml_file is None)
+ self.temporary = temporary
self._recipe_path = None
if sc_id is not None:
self.repr_sc = kmanager.getDataContainer(sc_id)
@@ -137,11 +136,13 @@
'zvi_filename':img_meta['zvi_filename'],
'zvalue':zvalue,
'timestamp':img_meta['timestamp'],
- 'zid':img_meta['zid']}
+ 'zid':img_meta['zid'],
+ 'ZStackType':'RawImage',
+ 'vmin':0, 'vmax':255}
img_fc = FieldContainer(data=data,
longname=os.path.basename(
img_meta['img_filename']),
- shortname="img",
+ shortname="i",
dimensions=dimensions, attributes=fcattr)
img_fc.seal()
kmanager.registerDataContainer(img_fc, temporary=temporary)
@@ -153,7 +154,8 @@
shortname='z', unit=Quantity(1.0, 'mum'))
filefc = FieldContainer(scipy.array(files), longname='filename',
shortname='f')
- emd5fc = FieldContainer(scipy.array(emd5s), longname='emd5', shortname='i')
+ emd5fc = FieldContainer(scipy.array(emd5s), longname='emd5',
+ shortname='i')
if pdial is not None:
pdial.Destroy()
return zfc, filefc, emd5fc
@@ -175,55 +177,16 @@
return None
attributes = {}
attributes['ztol'] = ZStack._estimate_ztol(zfc)
- attributes['isZStack'] = 'yes'
+ attributes['ZStackType'] = 'RawSC'
ssc = SampleContainer([zfc, filefc, emd5fc],
name,
- "z-stack",
+ "z",
attributes)
ssc.seal()
kmanager.registerDataContainer(ssc, temporary=self.temporary)
return ssc
- def _set_recipe_path(self, rpath):
- self._recipe_path = os.path.realpath(rpath)
- def _get_recipe_path(self):
- return self._recipe_path
- recipe_path = property(_get_recipe_path, _set_recipe_path)
-
- def _get_mf_id(self, gradient_alg, label_alg, human, subscriber=0):
- assert self._recipe_path is not None
- uattr = {'isZStack':'no'}
- in_ids = {'grey_invert':{'image':self.repr_sc.id}}
- gradient_id = gradient_alg.get_batch_result_id(
- in_ids, update_attrs=uattr, subscriber=subscriber,
- start=1, end=30, temporary=self.temporary)
- in_ids = {'threshold':{'image':gradient_id}}
- label_id = label_alg.get_batch_result_id(
- in_ids, update_attrs=uattr, subscriber=subscriber,
- start=31, end=66, temporary=self.temporary)
- mf_alg = RecipeAlg(os.path.join(self.recipe_path, 'MeasureFocus.h5'),
- 'MeasureFocus', 'measure_focus',
- {'MeasureFocus':{'humanOutput':human}})
- in_ids = {'MeasureFocus':{'image':gradient_id,
- 'labels':label_id}}
- return mf_alg.get_batch_result_id(
- in_ids, update_attrs=uattr, subscriber=subscriber,
- start=67, end=100, temporary=self.temporary)
-
- def get_statistics(self, gradient_alg, label_alg, subscriber=0):
- mf_id = self._get_mf_id(gradient_alg, label_alg, False, subscriber)
- af_alg = RecipeAlg(os.path.join(self.recipe_path, 'AutoFocus.h5'),
- 'AutoFocus', 'AutoFocusWorker')
- in_ids = {'AutoFocus':{'focusSC':mf_id}}
- af_sc = af_alg.get_result(in_ids, temporary=self.temporary)
- return af_sc
-
- def get_human_imgs(self, gradient_alg, label_alg, subscriber=0):
- mf_id = self._get_mf_id(gradient_alg, label_alg, True, subscriber)
- return kmanager.getDataContainer(mf_id)
-
-
class ZStackManager(object):
def addZStack(self, zstack):
"""Adds a given zstack to the pool"""
@@ -231,8 +194,17 @@
def getZStacks(self):
"""Returns a list of all ZStacks in the pool"""
- search_dict = {'type':'sample', 'attributes':{'isZStack':'yes'}}
+ search_dict = {'type':'sample', 'attributes':{'ZStackType':'RawSC'}}
search_result = kmanager.search(['id'], search_dict)
if len(search_result) == 0:
return []
return [ZStack(zs_id[0]) for zs_id in search_result]
+
+ def getZStackByName(self, name):
+ search_dict = {'type':'sample', 'attributes':{'ZStackType':'RawSC'},
+ 'longname':name}
+ sresult = kmanager.search(['id'], search_dict)
+ if sresult == []:
+ raise ValueError("There is no ZStack called %s!" \
+ % name)
+ return ZStack(sc_id=sresult[0][0])
Modified: trunk/src/pyphant/pyphant/quantities/__init__.py
===================================================================
--- trunk/src/pyphant/pyphant/quantities/__init__.py 2010-05-26 20:45:06 UTC (rev 684)
+++ trunk/src/pyphant/pyphant/quantities/__init__.py 2010-06-17 16:17:44 UTC (rev 685)
@@ -241,6 +241,46 @@
def __rsub__(self, other):
return self._sum(other, -1, 1)
+ def __eq__(self, other):
+ if isQuantity(other) and self.isCompatible(other.unit):
+ return self.__cmp__(other) == 0
+ else:
+ return False
+
+ def __ne__(self, other):
+ if isQuantity(other) and self.isCompatible(other.unit):
+ return self.__cmp__(other) != 0
+ else:
+ return True
+
+ def __le__(self, other):
+ if isQuantity(other) and self.isCompatible(other.unit):
+ return self.__cmp__(other) <= 0
+ else:
+ return False
+
+ def __ge__(self, other):
+ if isQuantity(other) and self.isCompatible(other.unit):
+ return self.__cmp__(other) >= 0
+ elif other is None:
+ return True
+ else:
+ return False
+
+ def __lt__(self, other):
+ if isQuantity(other) and self.isCompatible(other.unit):
+ return self.__cmp__(other) < 0
+ else:
+ return False
+
+ def __gt__(self, other):
+ if isQuantity(other) and self.isCompatible(other.unit):
+ return self.__cmp__(other) > 0
+ elif other is None:
+ return True
+ else:
+ return False
+
def __cmp__(self, other):
normed = self.inBaseUnits() # Minimizing numerical errors
diff = normed._sum(other, 1, -1)
Deleted: trunk/src/pyphant/pyphant/tests/TestAutoFocus.py
===================================================================
--- trunk/src/pyphant/pyphant/tests/TestAutoFocus.py 2010-05-26 20:45:06 UTC (rev 684)
+++ trunk/src/pyphant/pyphant/tests/TestAutoFocus.py 2010-06-17 16:17:44 UTC (rev 685)
@@ -1,229 +0,0 @@
-#!/usr/bin/env python2.5
-# -*- coding: utf-8 -*-
-
-# Copyright (c) 2006-2010, Rectorate of the University of Freiburg
-# Copyright (c) 2009-2010, Andreas W. Liehr (li...@us...)
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above copyright
-# notice, this list of conditions and the following disclaimer in the
-# documentation and/or other materials provided with the distribution.
-# * Neither the name of the Freiburg Materials Research Center,
-# University of Freiburg nor the names of its contributors may be used to
-# endorse or promote products derived from this software without specific
-# prior written permission.
-#
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
-# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
-# OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
-
-u"""Provides unittest classes for AutoFocus worker.
-"""
-
-__id__ = "$Id$".replace('$','')
-__author__ = "$Author$".replace('$','')
-__version__ = "$Revision$".replace('$','')
-# $Source$
-
-import unittest
-import pkg_resources
-pkg_resources.require("pyphant")
-from pyphant.quantities import Quantity
-from pyphant.core.DataContainer import FieldContainer, SampleContainer
-from ImageProcessing import AutoFocus as AF
-import numpy
-from pyphant.core.KnowledgeManager import KnowledgeManager
-
-
-class CubeTestCase(unittest.TestCase):
- def setUp(self):
- self.cube1 = AF.Cube([slice(0, 10),
- slice(0, 10),
- slice(0, 10)])
- self.cube2 = AF.Cube([slice(3, 5),
- slice(4, 6),
- slice(-5, 7)])
- def tearDown(self):
- pass
-
- def testEq(self):
- cube1c = AF.Cube(self.cube1.slices)
- assert self.cube1 == cube1c
- assert not self.cube1.__eq__(self.cube2)
-
- def testAnd(self):
- expected = AF.Cube([slice(3, 5), slice(4, 6), slice(0, 7)])
- assert self.cube1 & self.cube2 == expected
-
- def testOr(self):
- expected = AF.Cube([slice(0, 10), slice(0, 10), slice(-5, 10)])
- assert self.cube1 | self.cube2 == expected
-
- def testVolume(self):
- assert self.cube1.getVolume() == 1000
- assert self.cube2.getVolume() == 48
- assert AF.Cube([slice(0, 0),
- slice(0, 1000),
- slice(0, 1000)]).getVolume() == 0
-
- def testSubCube(self):
- expected = AF.Cube([slice(3,5 ), slice(-5, 7)])
- assert self.cube2.getSubCube([0, 2]) == expected
-
- def testGetEdgeLength(self):
- assert self.cube2.getEdgeLength(0) == 2
- assert self.cube2.getEdgeLength(1) == 2
- assert self.cube2.getEdgeLength(2) == 12
-
- def testSub(self):
- expected = AF.Cube([slice(-3, 7),
- slice(-4, 6),
- slice(5, 15)])
- assert self.cube1 - self.cube2 == expected
-
- def testCenter(self):
- expected = (5.0, 5.0, 5.0)
- assert self.cube1.getCenter() == expected
-
-
-class ZTubeTestCase(unittest.TestCase):
- def setUp(self):
- slices = [slice(0, 10), slice(0, 10)]
- mask = numpy.ones((20, 20), dtype=bool)
- mask_fc = FieldContainer(mask)
- mask_fc.seal()
- km = KnowledgeManager.getInstance()
- km.registerDataContainer(mask_fc, temporary=True)
- mask_parent = mask_fc.id
- fslice = AF.FocusSlice(slices, 10.0, mask_parent, slices, 1, 1)
- self.ztube = AF.ZTube(fslice, 0, 1, 0.5, 0.5)
- testslices1 = [slice(3, 12), slice(2, 9)]
- mask1 = numpy.ones((9, 7), dtype=bool)
- self.testfslice1 = AF.FocusSlice(testslices1, 12.0, mask_parent,
- testslices1, 1, 1)
- testslices2 = [slice(7, 17), slice(8, 16)]
- mask2 = numpy.ones((10, 8), dtype=bool)
- self.testfslice2 = AF.FocusSlice(testslices2, 8.0, mask_parent,
- testslices2, 1, 1)
-
- def tearDown(self):
- pass
-
- def testMatching(self):
- assert self.ztube.match(self.testfslice1, 1)
- assert not self.ztube.match(self.testfslice2, 1.01)
- expectedyx = AF.Cube([slice(0, 12),
- slice(0, 10)])
- expectedz = AF.Cube([slice(-1, 2)])
- assert self.ztube.yxCube == expectedyx
- assert self.ztube.zCube == expectedz
- assert self.ztube.focusedFSlice == self.testfslice1
- assert self...
[truncated message content] |
|
From: <zk...@us...> - 2010-07-18 18:51:22
|
Revision: 698
http://pyphant.svn.sourceforge.net/pyphant/?rev=698&view=rev
Author: zklaus
Date: 2010-07-18 18:51:16 +0000 (Sun, 18 Jul 2010)
Log Message:
-----------
Merge branch 'master' into svn-trunk
* master:
Fix: Fix typo, remove debug print.
Fix: Add proper handling of maskless fields to PlotFrame; better unit handling.
Enh: Add legend to viewOSC script.
Modified Paths:
--------------
trunk/doc/demo/viewOSC.py
trunk/src/pyphant/pyphant/visualizers/ConfigurablePlot.py
trunk/src/workers/OSC/OSC/EstimateParameterFromValues.py
Modified: trunk/doc/demo/viewOSC.py
===================================================================
--- trunk/doc/demo/viewOSC.py 2010-07-14 10:41:43 UTC (rev 697)
+++ trunk/doc/demo/viewOSC.py 2010-07-18 18:51:16 UTC (rev 698)
@@ -182,7 +182,7 @@
residuum = (simulation.dimensions[0].data-thickness.data[index])**2
absorption = simulation.data[residuum.argmin(),:]
pylab.plot(simulation.dimensions[1].data,
- absorption,label="$%s$"%simulation.shortname)
+ absorption,label="$%s$ functional"%simulation.shortname)
title = "Functional based: " + title_template % (thickness[index].shortname,
thickness.data[index],
thickness.unit.unit.name())
@@ -194,7 +194,7 @@
residuum = (simulation.dimensions[0].data-thickness.data[index])**2
absorption = simulation.data[residuum.argmin(),:]
pylab.plot(simulation.dimensions[1].data,
- absorption,label="$%s$"%simulation.shortname)
+ absorption,label="$%s$ immediate"%simulation.shortname)
title += "\nImmediate: " + title_template % (thickness[index].shortname,
thickness.data[index],
thickness.unit.unit.name())
@@ -223,6 +223,7 @@
label ="$\\Delta%s$"%maximaPos.shortname, linestyle='dashed')
pylab.title(title)
pylab.xlabel(simulation.dimensions[1].label)
+ pylab.legend(loc="lower left")
def noisyAbsorption(recipe, curvNo, noIndicators):
worker = recipe.getWorker("Slicing")
Modified: trunk/src/pyphant/pyphant/visualizers/ConfigurablePlot.py
===================================================================
--- trunk/src/pyphant/pyphant/visualizers/ConfigurablePlot.py 2010-07-14 10:41:43 UTC (rev 697)
+++ trunk/src/pyphant/pyphant/visualizers/ConfigurablePlot.py 2010-07-18 18:51:16 UTC (rev 698)
@@ -49,8 +49,8 @@
from pyphant.core import DataContainer
from pyphant.wxgui2.DataVisReg import DataVisReg
from pyphant.quantities import isQuantity, Quantity
+from pyphant.quantities.ParseQuantities import str2unit
-
class PlotPanel (wx.PyPanel):
"""The PlotPanel has a Figure and a Canvas. OnSize events simply set a
flag, and the actual resizing of the figure is triggered by an Idle event."""
@@ -122,10 +122,15 @@
if not isinstance(aspect, Quantity):
self.ax.set_aspect(aspect)
try:
- mask = numpy.logical_not(self.c.mask)
- x = self.x.data[mask]
- y = self.y.data[mask]
- c = self.c.data[mask]
+ if self.c.mask!=None:
+ mask = numpy.logical_not(self.c.mask)
+ x = self.x.data[mask]
+ y = self.y.data[mask]
+ c = self.c.data[mask]
+ else:
+ x = self.x.data
+ y = self.y.data
+ c = self.c.data
self.scat = self.ax.scatter(x,y,
s=numpy.pi*(self.radius/self.x.unit)**2,
c=c,
@@ -231,9 +236,9 @@
self.vmin_text.Value=str(vmin)
vmax = numpy.nanmax(field.data).round()*field.unit
self.vmax_text.Value=str(vmax)
- self.plot_panel.vmin = Quantity(self.vmin_text.Value)
- self.plot_panel.vmax = Quantity(self.vmax_text.Value)
- self.plot_panel.radius = Quantity(self.radius_text.Value)
+ self.plot_panel.vmin = str2unit(self.vmin_text.Value)
+ self.plot_panel.vmax = str2unit(self.vmax_text.Value)
+ self.plot_panel.radius = str2unit(self.radius_text.Value)
self.plot_panel.draw()
self.GetSizer().Fit(self)
Modified: trunk/src/workers/OSC/OSC/EstimateParameterFromValues.py
===================================================================
--- trunk/src/workers/OSC/OSC/EstimateParameterFromValues.py 2010-07-14 10:41:43 UTC (rev 697)
+++ trunk/src/workers/OSC/OSC/EstimateParameterFromValues.py 2010-07-18 18:51:16 UTC (rev 698)
@@ -75,14 +75,14 @@
minima_model = model[self.paramMinima_model.value]
maxima_model = model[self.paramMaxima_model.value]
minima_experimental = experimental[self.paramMinima_experimental.value]
- minima_experimantal = minima_experimental.inUnitsOf(minima_model)
+ minima_experimental = minima_experimental.inUnitsOf(minima_model)
minima = minima_experimental.data.transpose()
if minima_experimental.error != None:
minima_error = iter(minima_experimental.error.transpose())
else:
minima_error = None
maxima_experimental = experimental[self.paramMaxima_experimental.value]
- maxima_experimantal = maxima_experimental.inUnitsOf(maxima_model)
+ maxima_experimental = maxima_experimental.inUnitsOf(maxima_model)
maxima = maxima_experimental.data.transpose()
if maxima_experimental.error != None:
maxima_error = iter(maxima_experimental.error.transpose())
@@ -119,7 +119,6 @@
grades.append(numpy.nan)
continue
grades.append(grade)
- print grades[-1]
grades = numpy.array(grades)
i = numpy.nanargmin(grades)
if numpy.isnan(i):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <zk...@us...> - 2010-09-13 08:56:43
|
Revision: 699
http://pyphant.svn.sourceforge.net/pyphant/?rev=699&view=rev
Author: zklaus
Date: 2010-09-13 08:56:34 +0000 (Mon, 13 Sep 2010)
Log Message:
-----------
Merge branch 'master' into svn-trunk
* master:
removed unneeded variable setup
Changed pyphant/Core/Helper.py to use getpass.
Bugfix: Logo is loaded from base64 encoded string.
Added splash screen: This version needs to be started in src/pyphant/pyphant/wxgui2 or doc/logo in order to find the splash screen image.
pyphantLogo module with docstring.
Base64 coded pyphant logo.
Fix: ZStacks: refractive index
Fix: Restore parameters to DCSource workers
Cosm: Added line feed to README
Modified Paths:
--------------
trunk/doc/demo/README
trunk/src/pyphant/pyphant/core/Helpers.py
trunk/src/pyphant/pyphant/core/ZStackManager.py
trunk/src/pyphant/pyphant/tests/TestZStacks.py
trunk/src/pyphant/pyphant/wxgui2/wxPyphantApplication.py
trunk/src/workers/tools/tools/DCSource.py
trunk/src/workers/tools/tools/FCSource.py
trunk/src/workers/tools/tools/SCSource.py
Added Paths:
-----------
trunk/doc/logo/
trunk/doc/logo/mklogo.py
trunk/doc/logo/pyphant-shade-Information-Analysis-Framework-ARTS-small.png
trunk/doc/logo/pyphantLogo.py
trunk/src/pyphant/pyphant/wxgui2/pyphantLogo.py
Modified: trunk/doc/demo/README
===================================================================
--- trunk/doc/demo/README 2010-07-18 18:51:16 UTC (rev 698)
+++ trunk/doc/demo/README 2010-09-13 08:56:34 UTC (rev 699)
@@ -2,4 +2,5 @@
wxPythant demo.h5
#Start scripting example with
-./simpleScripting.py
\ No newline at end of file
+./simpleScripting.py
+
Added: trunk/doc/logo/mklogo.py
===================================================================
--- trunk/doc/logo/mklogo.py (rev 0)
+++ trunk/doc/logo/mklogo.py 2010-09-13 08:56:34 UTC (rev 699)
@@ -0,0 +1,49 @@
+copyright="""# -*- coding: utf-8 -*-
+
+# Copyright (c) 2010, Andreas W. Liehr (li...@us...)
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+# * Neither the name of the Freiburg Materials Research Center,
+# University of Freiburg nor the names of its contributors may be used to
+# endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
+# OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+
+"""
+
+"""Creates pyphantLogo.py, a python modul including a base 64 encoded PNG file of the Pyphant logo."""
+
+import base64
+picname = 'pyphant-shade-Information-Analysis-Framework-ARTS-small.png'
+file = open(picname,'rb')
+logo = file.read()
+file.close()
+pic_b64 = logo.encode('base64')
+
+file = open("pyphantLogo.py",'w')
+file.write(copyright)
+file.write("\"\"\""+
+"""Python modul including a base 64 encoded PNG file of the Pyphant logo based on %s.""" % picname +"\"\"\"\n\n"
+ )
+file.write("pic_b64 = \"\"\"%s\"\"\"\n" % pic_b64)
+file.close()
Added: trunk/doc/logo/pyphant-shade-Information-Analysis-Framework-ARTS-small.png
===================================================================
--- trunk/doc/logo/pyphant-shade-Information-Analysis-Framework-ARTS-small.png (rev 0)
+++ trunk/doc/logo/pyphant-shade-Information-Analysis-Framework-ARTS-small.png 2010-09-13 08:56:34 UTC (rev 699)
@@ -0,0 +1,978 @@
+\x89PNG
+
+ |