You can subscribe to this list here.
2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(13) |
Nov
(50) |
Dec
(40) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2008 |
Jan
(49) |
Feb
(72) |
Mar
(18) |
Apr
(27) |
May
(40) |
Jun
(52) |
Jul
(26) |
Aug
(8) |
Sep
(12) |
Oct
(26) |
Nov
(13) |
Dec
(14) |
2009 |
Jan
(13) |
Feb
(7) |
Mar
(8) |
Apr
(11) |
May
(4) |
Jun
(2) |
Jul
(7) |
Aug
(1) |
Sep
(3) |
Oct
|
Nov
(1) |
Dec
(1) |
2010 |
Jan
(1) |
Feb
(8) |
Mar
(3) |
Apr
(9) |
May
(16) |
Jun
(8) |
Jul
(7) |
Aug
|
Sep
(1) |
Oct
|
Nov
|
Dec
|
2011 |
Jan
|
Feb
|
Mar
|
Apr
|
May
(1) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
(6) |
Dec
(12) |
From: <zk...@us...> - 2009-01-20 12:27:47
|
Revision: 598 http://pyphant.svn.sourceforge.net/pyphant/?rev=598&view=rev Author: zklaus Date: 2009-01-20 12:27:32 +0000 (Tue, 20 Jan 2009) Log Message: ----------- Set default output format of visualization tests to Postscript. Modified Paths: -------------- trunk/src/pyphant/pyphant/tests/TestChart.py trunk/src/pyphant/pyphant/tests/TestImageVisualizer.py Modified: trunk/src/pyphant/pyphant/tests/TestChart.py =================================================================== --- trunk/src/pyphant/pyphant/tests/TestChart.py 2009-01-20 12:19:28 UTC (rev 597) +++ trunk/src/pyphant/pyphant/tests/TestChart.py 2009-01-20 12:27:32 UTC (rev 598) @@ -52,7 +52,7 @@ from pyphant.core import DataContainer as DC import OSC.tests.TestExtremumFinder as TEF -outputFormat = 'png' +outputFormat = 'ps' class TestLinePlot(unittest.TestCase): """Create a one-dimensional field and check the problem-free generation of a line plot.""" Modified: trunk/src/pyphant/pyphant/tests/TestImageVisualizer.py =================================================================== --- trunk/src/pyphant/pyphant/tests/TestImageVisualizer.py 2009-01-20 12:19:28 UTC (rev 597) +++ trunk/src/pyphant/pyphant/tests/TestImageVisualizer.py 2009-01-20 12:27:32 UTC (rev 598) @@ -53,9 +53,6 @@ from pyphant.visualizers.ImageVisualizer import ImageVisualizer from pyphant.core import DataContainer as DC -import matplotlib -matplotlib.rcParams['backend'] = 'Agg' - class TestImageVisualizer(unittest.TestCase): """Create a two-dimensional field and check the problem-free generation of a labelled image.""" def setUp(self): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zk...@us...> - 2009-01-20 12:19:41
|
Revision: 597 http://pyphant.svn.sourceforge.net/pyphant/?rev=597&view=rev Author: zklaus Date: 2009-01-20 12:19:28 +0000 (Tue, 20 Jan 2009) Log Message: ----------- Output format of visualization tests can be set via module variable. Modified Paths: -------------- trunk/src/pyphant/pyphant/tests/TestChart.py Modified: trunk/src/pyphant/pyphant/tests/TestChart.py =================================================================== --- trunk/src/pyphant/pyphant/tests/TestChart.py 2009-01-20 11:03:42 UTC (rev 596) +++ trunk/src/pyphant/pyphant/tests/TestChart.py 2009-01-20 12:19:28 UTC (rev 597) @@ -52,6 +52,8 @@ from pyphant.core import DataContainer as DC import OSC.tests.TestExtremumFinder as TEF +outputFormat = 'png' + class TestLinePlot(unittest.TestCase): """Create a one-dimensional field and check the problem-free generation of a line plot.""" def setUp(self): @@ -60,7 +62,7 @@ self.kappa1=0.0 self.tmpdir = tempfile.gettempdir() self.visualizer = LineChart - + def testVisualization(self): X = numpy.linspace(-1.5,1.5,self.n) self.lambDim = 1.0 @@ -75,7 +77,7 @@ attributes={'title':'testVisualization'}) self.V.seal() visualizer = self.visualizer(self.V,show=False) - filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'%s.pdf' % visualizer.name) + filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'%s.%s' % (visualizer.name,outputFormat)) visualizer.figure.savefig(filename.replace(' ','')) def testErrorVisualization(self): @@ -93,7 +95,7 @@ self.V.error = 0.1*numpy.abs(self.V.data) self.V.seal() visualizer = self.visualizer(self.V,show=False) - filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'%s.pdf' % visualizer.name) + filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'%s.%s' % (visualizer.name,outputFormat)) visualizer.figure.savefig(filename.replace(' ','')) def testIntersectionXArray(self): @@ -120,7 +122,7 @@ self.V.seal() visualizer = self.visualizer(self.V,show=False) - filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'%s.pdf' % visualizer.name) + filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'%s.%s' % (visualizer.name,outputFormat)) visualizer.figure.savefig(filename.replace(' ','')) @@ -148,7 +150,7 @@ attributes={'title':'testIntersectionXVector'}) self.V.seal() visualizer = self.visualizer(self.V,show=False) - filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'%s.pdf' % visualizer.name) + filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'%s.%s' % (visualizer.name,outputFormat)) visualizer.figure.savefig(filename.replace(' ','')) def testTableIncludingNan(self): @@ -173,7 +175,7 @@ attributes={'title':'testTableIncludingNan'}) fixedPoints.seal() visualizer = self.visualizer(fixedPoints,show=False) - filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(fixedPoints.id)[0]+'%s.pdf' % visualizer.name) + filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(fixedPoints.id)[0]+'%s.%s' % (visualizer.name,outputFormat)) visualizer.figure.savefig(filename.replace(' ','')) def testTableIncludingNanAndErrors(self): @@ -199,7 +201,7 @@ fixedPoints.error = 0.1 * fixedPoints.data fixedPoints.seal() visualizer = self.visualizer(fixedPoints,show=False) - filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(fixedPoints.id)[0]+'%s.pdf' % visualizer.name) + filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(fixedPoints.id)[0]+'%s.%s' % (visualizer.name,outputFormat)) visualizer.figure.savefig(filename.replace(' ','')) class TestScatterPlot(TestLinePlot): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zk...@us...> - 2009-01-20 10:50:52
|
Revision: 595 http://pyphant.svn.sourceforge.net/pyphant/?rev=595&view=rev Author: zklaus Date: 2009-01-20 10:50:41 +0000 (Tue, 20 Jan 2009) Log Message: ----------- Added hack for non X environments. Modified Paths: -------------- trunk/src/pyphant/pyphant/visualizers/__init__.py Modified: trunk/src/pyphant/pyphant/visualizers/__init__.py =================================================================== --- trunk/src/pyphant/pyphant/visualizers/__init__.py 2009-01-20 10:36:24 UTC (rev 594) +++ trunk/src/pyphant/pyphant/visualizers/__init__.py 2009-01-20 10:50:41 UTC (rev 595) @@ -40,6 +40,9 @@ import os,sys import matplotlib matplotlib.rcParams['backend']='WXAgg' +import platform +if platform.system()=='Linux' and not 'DISPLAY' in os.environ: + matplotlib.rcParams['backend'] = 'Agg' #matplotlib.rcParams['text.usetex']=True #matplotlib.rcParams['text.latex.unicode']=True #matplotlib.rcParams['text.latex.preamble']=(r"\usepackage[utf8]{inputenc}",r"\usepackage{amsmath}") This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zk...@us...> - 2009-01-20 10:36:29
|
Revision: 594 http://pyphant.svn.sourceforge.net/pyphant/?rev=594&view=rev Author: zklaus Date: 2009-01-20 10:36:24 +0000 (Tue, 20 Jan 2009) Log Message: ----------- Changed TestImageVisualizer to run without X. Modified Paths: -------------- trunk/src/pyphant/pyphant/tests/TestImageVisualizer.py Modified: trunk/src/pyphant/pyphant/tests/TestImageVisualizer.py =================================================================== --- trunk/src/pyphant/pyphant/tests/TestImageVisualizer.py 2009-01-20 10:23:01 UTC (rev 593) +++ trunk/src/pyphant/pyphant/tests/TestImageVisualizer.py 2009-01-20 10:36:24 UTC (rev 594) @@ -53,6 +53,9 @@ from pyphant.visualizers.ImageVisualizer import ImageVisualizer from pyphant.core import DataContainer as DC +import matplotlib +matplotlib.rcParams['backend'] = 'Agg' + class TestImageVisualizer(unittest.TestCase): """Create a two-dimensional field and check the problem-free generation of a labelled image.""" def setUp(self): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zk...@us...> - 2009-01-20 10:23:08
|
Revision: 593 http://pyphant.svn.sourceforge.net/pyphant/?rev=593&view=rev Author: zklaus Date: 2009-01-20 10:23:01 +0000 (Tue, 20 Jan 2009) Log Message: ----------- Added ConfigObj and egenix-mx-base as dependencies to fmfile. Modified Paths: -------------- trunk/src/workers/fmfile/setup.py Modified: trunk/src/workers/fmfile/setup.py =================================================================== --- trunk/src/workers/fmfile/setup.py 2008-12-19 19:03:18 UTC (rev 592) +++ trunk/src/workers/fmfile/setup.py 2009-01-20 10:23:01 UTC (rev 593) @@ -20,7 +20,9 @@ version = VERSION, author = __author__, description = __doc__, - install_requires=['pyphant>=0.4alpha3'], + install_requires=['pyphant>=0.4alpha3', + 'ConfigObj', + 'egenix-mx-base'], packages = ['fmfile'], entry_points = """ [pyphant.workers] 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: <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-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-17 10:46:49
|
Revision: 589 http://pyphant.svn.sourceforge.net/pyphant/?rev=589&view=rev Author: liehr Date: 2008-12-17 10:46:43 +0000 (Wed, 17 Dec 2008) Log Message: ----------- Arbitrary units can only be abbreviated as 'a.u.'. Modified Paths: -------------- trunk/src/workers/fmfile/fmfile/FMFLoader.py Modified: trunk/src/workers/fmfile/fmfile/FMFLoader.py =================================================================== --- trunk/src/workers/fmfile/fmfile/FMFLoader.py 2008-12-16 10:48:16 UTC (rev 588) +++ trunk/src/workers/fmfile/fmfile/FMFLoader.py 2008-12-17 10:46:43 UTC (rev 589) @@ -362,7 +362,7 @@ unit = '0'+unit elif unit == '%': unit = 0.01 - elif unit == 'a.u.' or unit == 'A.U.': + elif unit == 'a.u.': unit = 1.0 elif not unit[0].isdigit(): unit = '1'+unit 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-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: <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: <zk...@us...> - 2008-12-09 14:49:05
|
Revision: 585 http://pyphant.svn.sourceforge.net/pyphant/?rev=585&view=rev Author: zklaus Date: 2008-12-09 14:48:56 +0000 (Tue, 09 Dec 2008) Log Message: ----------- Bugfix: Moved visualizer tests into general test package pyphant.tests. Added Paths: ----------- trunk/src/pyphant/pyphant/tests/TestChart.py trunk/src/pyphant/pyphant/tests/TestImageVisualizer.py Removed Paths: ------------- trunk/src/pyphant/pyphant/visualizers/tests/TestChart.py trunk/src/pyphant/pyphant/visualizers/tests/TestImageVisualizer.py Copied: trunk/src/pyphant/pyphant/tests/TestChart.py (from rev 584, trunk/src/pyphant/pyphant/visualizers/tests/TestChart.py) =================================================================== --- trunk/src/pyphant/pyphant/tests/TestChart.py (rev 0) +++ trunk/src/pyphant/pyphant/tests/TestChart.py 2008-12-09 14:48:56 UTC (rev 585) @@ -0,0 +1,215 @@ +# -*- coding: utf-8 -*- + +# Copyright (c) 2008, 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 unittests for ImageVisualizers. Because it is difficult to check the correct visualization of a image, it is just checked, wether the visualizers run without assertions.""" + +__id__ = "$Id$" +__author__ = "$Author$" +__version__ = "$Revision$" +# $Source$ + + +import sys, os.path +import tempfile +import unittest +sys.path.append("..") + +import pkg_resources + +pkg_resources.require("Pyphant") +pkg_resources.require("Pyphant_OSC") + +import numpy +from pyphant.visualizers.Chart import LineChart,ScatterPlot +from pyphant.core import DataContainer as DC +import OSC.tests.TestExtremumFinder as TEF + +class TestLinePlot(unittest.TestCase): + """Create a one-dimensional field and check the problem-free generation of a line plot.""" + def setUp(self): + self.m = 10 + self.n = 100 + self.kappa1=0.0 + self.tmpdir = tempfile.gettempdir() + self.visualizer = LineChart + + def testVisualization(self): + X = numpy.linspace(-1.5,1.5,self.n) + self.lambDim = 1.0 + xField = DC.FieldContainer(X, + unit = '1 m', + longname = 'position', + shortname = 'x') + self.V = DC.FieldContainer(-self.lambDim/2* X**2 + X**4/4-X*self.kappa1, + unit='1 V',dimensions=[xField], + longname = 'electric potential', + shortname=r'\varphi', + attributes={'title':'testVisualization'}) + self.V.seal() + visualizer = self.visualizer(self.V,show=False) + filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'%s.pdf' % visualizer.name) + visualizer.figure.savefig(filename.replace(' ','')) + + def testErrorVisualization(self): + X = numpy.linspace(-1.5,1.5,self.n) + self.lambDim = 1.0 + xField = DC.FieldContainer(X, + unit = '1 m', + longname = 'position', + shortname = 'x') + self.V = DC.FieldContainer(-self.lambDim/2* X**2 + X**4/4-X*self.kappa1, + unit='1 V',dimensions=[xField], + longname = 'electric potential', + shortname=r'\varphi', + attributes={'title':'testErrorVisualization'}) + self.V.error = 0.1*numpy.abs(self.V.data) + self.V.seal() + visualizer = self.visualizer(self.V,show=False) + filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'%s.pdf' % visualizer.name) + visualizer.figure.savefig(filename.replace(' ','')) + + def testIntersectionXArray(self): + X,LAMB = numpy.meshgrid(numpy.linspace(-1.5,1.5,self.n), + numpy.linspace(-1.0,1.0,self.m)) + self.lambDim = numpy.linspace(-1.0,1.0,self.m) + self.xDim = numpy.linspace(-1.5,1.5,self.n) + lambField = DC.FieldContainer(self.lambDim, + unit = '1 V / m**3', + longname='parameter', + shortname='\lambda') + xField = DC.FieldContainer(self.xDim, + unit = '1 m', + longname = 'position', + shortname = 'x') + #Prepare potential + V = [] + for i in xrange(len(lambField.data)): + u = X[i] + V.append(-lambField.data[i]/2* u**2 + u**4/4-u*self.kappa1) + self.V = DC.FieldContainer(numpy.array(V),unit='1 V',dimensions=[lambField,xField], + longname = 'electric potential', + shortname=r'\varphi') + + self.V.seal() + visualizer = self.visualizer(self.V,show=False) + filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'%s.pdf' % visualizer.name) + visualizer.figure.savefig(filename.replace(' ','')) + + + def testIntersectionXVector(self): + X,LAMB = numpy.meshgrid(numpy.linspace(-1.5,1.5,self.n), + numpy.linspace(-1.0,1.0,self.m)) + self.lambDim = LAMB[:,0] + self.xDim = numpy.linspace(-1.5,1.5,self.n) + lambField = DC.FieldContainer(self.lambDim, + unit = '1 V / m**3', + longname='parameter', + shortname=r'\lambda') + xField = DC.FieldContainer(self.xDim, + unit = '1 m', + longname = 'position', + shortname = 'x') + #Prepare potential + V = [] + for i in xrange(len(lambField.data)): + u = X[i] + V.append(-lambField.data[i]/2* u**2 + u**4/4-u*self.kappa1) + self.V = DC.FieldContainer(numpy.array(V),unit='1 V',dimensions=[lambField, xField], + longname = 'electric potential', + shortname=r'\varphi', + attributes={'title':'testIntersectionXVector'}) + self.V.seal() + visualizer = self.visualizer(self.V,show=False) + filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'%s.pdf' % visualizer.name) + visualizer.figure.savefig(filename.replace(' ','')) + + def testTableIncludingNan(self): + X,LAMB = numpy.meshgrid(numpy.linspace(-1.5,1.5,self.n), + numpy.linspace(-1.0,1.0,self.m)) + self.lambDim = LAMB[:,0] + self.xDim = numpy.linspace(-1.5,1.5,self.n) + lambField = DC.FieldContainer(self.lambDim, + unit = '1 V / m**3', + longname='parameter', + shortname=r'\lambda') + xField = DC.FieldContainer(self.xDim, + unit = '1 m', + longname = 'position', + shortname = 'x') + x0,curv,mask = TEF.fixedPoints(lambField.data,kappa1=self.kappa1) + fixedPoints = DC.FieldContainer(numpy.array(x0).transpose(), + unit = xField.unit, + dimensions=[DC.generateIndex(0,3), lambField], + longname = 'position of the local extrema of electric potential', + shortname = 'x_0', + attributes={'title':'testTableIncludingNan'}) + fixedPoints.seal() + visualizer = self.visualizer(fixedPoints,show=False) + filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(fixedPoints.id)[0]+'%s.pdf' % visualizer.name) + visualizer.figure.savefig(filename.replace(' ','')) + + def testTableIncludingNanAndErrors(self): + X,LAMB = numpy.meshgrid(numpy.linspace(-1.5,1.5,self.n), + numpy.linspace(-1.0,1.0,self.m)) + self.lambDim = LAMB[:,0] + self.xDim = numpy.linspace(-1.5,1.5,self.n) + lambField = DC.FieldContainer(self.lambDim, + unit = '1 V / m**3', + longname='parameter', + shortname=r'\lambda') + xField = DC.FieldContainer(self.xDim, + unit = '1 m', + longname = 'position', + shortname = 'x') + x0,curv,mask = TEF.fixedPoints(lambField.data,kappa1=self.kappa1) + fixedPoints = DC.FieldContainer(numpy.array(x0).transpose(), + unit = xField.unit, + dimensions=[DC.generateIndex(0,3), lambField], + longname = 'position of the local extrema of electric potential', + shortname = 'x_0', + attributes={'title':'testTableIncludingNanAndErrors'}) + fixedPoints.error = 0.1 * fixedPoints.data + fixedPoints.seal() + visualizer = self.visualizer(fixedPoints,show=False) + filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(fixedPoints.id)[0]+'%s.pdf' % visualizer.name) + visualizer.figure.savefig(filename.replace(' ','')) + +class TestScatterPlot(TestLinePlot): + """Create a one-dimensional field and check the problem-free generation of a scatter plot.""" + def setUp(self): + self.m = 10 + self.n = 100 + self.kappa1=0.0 + self.tmpdir = tempfile.gettempdir() + self.visualizer = ScatterPlot + +if __name__ == '__main__': + unittest.main() Copied: trunk/src/pyphant/pyphant/tests/TestImageVisualizer.py (from rev 584, trunk/src/pyphant/pyphant/visualizers/tests/TestImageVisualizer.py) =================================================================== --- trunk/src/pyphant/pyphant/tests/TestImageVisualizer.py (rev 0) +++ trunk/src/pyphant/pyphant/tests/TestImageVisualizer.py 2008-12-09 14:48:56 UTC (rev 585) @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- + +# Copyright (c) 2008, 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 unittests for ImageVisualizers. Because it is difficult +to check the correct visualization of a image, it is just checked, +wether the visualizers run without assertions.""" + +__id__ = "$Id$" +__author__ = "$Author$" +__version__ = "$Revision$" +# $Source$ + + +import sys, os.path +import tempfile +import unittest +sys.path.append("..") + +import pkg_resources + +pkg_resources.require("Pyphant") +pkg_resources.require("Pyphant_OSC") + +import numpy +from pyphant.visualizers.ImageVisualizer import ImageVisualizer +from pyphant.core import DataContainer as DC + +class TestImageVisualizer(unittest.TestCase): + """Create a two-dimensional field and check the problem-free generation of a labelled image.""" + def setUp(self): + self.n = 100 + self.m = 10 + self.kappa1=0.0 + self.errLevelPos = 6 + self.errLevelCurv= 5 + self.tmpdir = tempfile.gettempdir() + + def testVisualization(self): + X,LAMB = numpy.meshgrid(numpy.linspace(-1.5,1.5,self.n), + numpy.linspace(-1.0,1.0,self.m)) + self.lambDim = numpy.linspace(-1.0,1.0,self.m) + self.xDim = numpy.linspace(-1.5,1.5,self.n) + lambField = DC.FieldContainer(self.lambDim, + unit = '1 V / m**3', + longname='parameter', + shortname='\lambda') + xField = DC.FieldContainer(self.xDim, + unit = '1 m', + longname = 'position', + shortname = 'x') + #Prepare potential + V = [] + for i in xrange(len(lambField.data)): + u = X[i] + V.append(-lambField.data[i]/2* u**2 + u**4/4-u*self.kappa1) + self.V = DC.FieldContainer(numpy.array(V),unit='1 V',dimensions=[lambField,xField], + longname = 'electric potential', + shortname=r'\varphi') + + self.V.seal() + #Visualise result + visualizer = ImageVisualizer(self.V,show=False) + filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'.pdf') + visualizer.figure.savefig(filename) + +if __name__ == '__main__': + unittest.main() Deleted: trunk/src/pyphant/pyphant/visualizers/tests/TestChart.py =================================================================== --- trunk/src/pyphant/pyphant/visualizers/tests/TestChart.py 2008-12-09 14:47:29 UTC (rev 584) +++ trunk/src/pyphant/pyphant/visualizers/tests/TestChart.py 2008-12-09 14:48:56 UTC (rev 585) @@ -1,215 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright (c) 2008, 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 unittests for ImageVisualizers. Because it is difficult to check the correct visualization of a image, it is just checked, wether the visualizers run without assertions.""" - -__id__ = "$Id$" -__author__ = "$Author$" -__version__ = "$Revision$" -# $Source$ - - -import sys, os.path -import tempfile -import unittest -sys.path.append("..") - -import pkg_resources - -pkg_resources.require("Pyphant") -pkg_resources.require("Pyphant_OSC") - -import numpy -from pyphant.visualizers.Chart import LineChart,ScatterPlot -from pyphant.core import DataContainer as DC -import OSC.tests.TestExtremumFinder as TEF - -class TestLinePlot(unittest.TestCase): - """Create a one-dimensional field and check the problem-free generation of a line plot.""" - def setUp(self): - self.m = 10 - self.n = 100 - self.kappa1=0.0 - self.tmpdir = tempfile.gettempdir() - self.visualizer = LineChart - - def testVisualization(self): - X = numpy.linspace(-1.5,1.5,self.n) - self.lambDim = 1.0 - xField = DC.FieldContainer(X, - unit = '1 m', - longname = 'position', - shortname = 'x') - self.V = DC.FieldContainer(-self.lambDim/2* X**2 + X**4/4-X*self.kappa1, - unit='1 V',dimensions=[xField], - longname = 'electric potential', - shortname=r'\varphi', - attributes={'title':'testVisualization'}) - self.V.seal() - visualizer = self.visualizer(self.V,show=False) - filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'%s.pdf' % visualizer.name) - visualizer.figure.savefig(filename.replace(' ','')) - - def testErrorVisualization(self): - X = numpy.linspace(-1.5,1.5,self.n) - self.lambDim = 1.0 - xField = DC.FieldContainer(X, - unit = '1 m', - longname = 'position', - shortname = 'x') - self.V = DC.FieldContainer(-self.lambDim/2* X**2 + X**4/4-X*self.kappa1, - unit='1 V',dimensions=[xField], - longname = 'electric potential', - shortname=r'\varphi', - attributes={'title':'testErrorVisualization'}) - self.V.error = 0.1*numpy.abs(self.V.data) - self.V.seal() - visualizer = self.visualizer(self.V,show=False) - filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'%s.pdf' % visualizer.name) - visualizer.figure.savefig(filename.replace(' ','')) - - def testIntersectionXArray(self): - X,LAMB = numpy.meshgrid(numpy.linspace(-1.5,1.5,self.n), - numpy.linspace(-1.0,1.0,self.m)) - self.lambDim = numpy.linspace(-1.0,1.0,self.m) - self.xDim = numpy.linspace(-1.5,1.5,self.n) - lambField = DC.FieldContainer(self.lambDim, - unit = '1 V / m**3', - longname='parameter', - shortname='\lambda') - xField = DC.FieldContainer(self.xDim, - unit = '1 m', - longname = 'position', - shortname = 'x') - #Prepare potential - V = [] - for i in xrange(len(lambField.data)): - u = X[i] - V.append(-lambField.data[i]/2* u**2 + u**4/4-u*self.kappa1) - self.V = DC.FieldContainer(numpy.array(V),unit='1 V',dimensions=[lambField,xField], - longname = 'electric potential', - shortname=r'\varphi') - - self.V.seal() - visualizer = self.visualizer(self.V,show=False) - filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'%s.pdf' % visualizer.name) - visualizer.figure.savefig(filename.replace(' ','')) - - - def testIntersectionXVector(self): - X,LAMB = numpy.meshgrid(numpy.linspace(-1.5,1.5,self.n), - numpy.linspace(-1.0,1.0,self.m)) - self.lambDim = LAMB[:,0] - self.xDim = numpy.linspace(-1.5,1.5,self.n) - lambField = DC.FieldContainer(self.lambDim, - unit = '1 V / m**3', - longname='parameter', - shortname=r'\lambda') - xField = DC.FieldContainer(self.xDim, - unit = '1 m', - longname = 'position', - shortname = 'x') - #Prepare potential - V = [] - for i in xrange(len(lambField.data)): - u = X[i] - V.append(-lambField.data[i]/2* u**2 + u**4/4-u*self.kappa1) - self.V = DC.FieldContainer(numpy.array(V),unit='1 V',dimensions=[lambField, xField], - longname = 'electric potential', - shortname=r'\varphi', - attributes={'title':'testIntersectionXVector'}) - self.V.seal() - visualizer = self.visualizer(self.V,show=False) - filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'%s.pdf' % visualizer.name) - visualizer.figure.savefig(filename.replace(' ','')) - - def testTableIncludingNan(self): - X,LAMB = numpy.meshgrid(numpy.linspace(-1.5,1.5,self.n), - numpy.linspace(-1.0,1.0,self.m)) - self.lambDim = LAMB[:,0] - self.xDim = numpy.linspace(-1.5,1.5,self.n) - lambField = DC.FieldContainer(self.lambDim, - unit = '1 V / m**3', - longname='parameter', - shortname=r'\lambda') - xField = DC.FieldContainer(self.xDim, - unit = '1 m', - longname = 'position', - shortname = 'x') - x0,curv,mask = TEF.fixedPoints(lambField.data,kappa1=self.kappa1) - fixedPoints = DC.FieldContainer(numpy.array(x0).transpose(), - unit = xField.unit, - dimensions=[DC.generateIndex(0,3), lambField], - longname = 'position of the local extrema of electric potential', - shortname = 'x_0', - attributes={'title':'testTableIncludingNan'}) - fixedPoints.seal() - visualizer = self.visualizer(fixedPoints,show=False) - filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(fixedPoints.id)[0]+'%s.pdf' % visualizer.name) - visualizer.figure.savefig(filename.replace(' ','')) - - def testTableIncludingNanAndErrors(self): - X,LAMB = numpy.meshgrid(numpy.linspace(-1.5,1.5,self.n), - numpy.linspace(-1.0,1.0,self.m)) - self.lambDim = LAMB[:,0] - self.xDim = numpy.linspace(-1.5,1.5,self.n) - lambField = DC.FieldContainer(self.lambDim, - unit = '1 V / m**3', - longname='parameter', - shortname=r'\lambda') - xField = DC.FieldContainer(self.xDim, - unit = '1 m', - longname = 'position', - shortname = 'x') - x0,curv,mask = TEF.fixedPoints(lambField.data,kappa1=self.kappa1) - fixedPoints = DC.FieldContainer(numpy.array(x0).transpose(), - unit = xField.unit, - dimensions=[DC.generateIndex(0,3), lambField], - longname = 'position of the local extrema of electric potential', - shortname = 'x_0', - attributes={'title':'testTableIncludingNanAndErrors'}) - fixedPoints.error = 0.1 * fixedPoints.data - fixedPoints.seal() - visualizer = self.visualizer(fixedPoints,show=False) - filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(fixedPoints.id)[0]+'%s.pdf' % visualizer.name) - visualizer.figure.savefig(filename.replace(' ','')) - -class TestScatterPlot(TestLinePlot): - """Create a one-dimensional field and check the problem-free generation of a scatter plot.""" - def setUp(self): - self.m = 10 - self.n = 100 - self.kappa1=0.0 - self.tmpdir = tempfile.gettempdir() - self.visualizer = ScatterPlot - -if __name__ == '__main__': - unittest.main() Deleted: trunk/src/pyphant/pyphant/visualizers/tests/TestImageVisualizer.py =================================================================== --- trunk/src/pyphant/pyphant/visualizers/tests/TestImageVisualizer.py 2008-12-09 14:47:29 UTC (rev 584) +++ trunk/src/pyphant/pyphant/visualizers/tests/TestImageVisualizer.py 2008-12-09 14:48:56 UTC (rev 585) @@ -1,95 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright (c) 2008, 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 unittests for ImageVisualizers. Because it is difficult -to check the correct visualization of a image, it is just checked, -wether the visualizers run without assertions.""" - -__id__ = "$Id$" -__author__ = "$Author$" -__version__ = "$Revision$" -# $Source$ - - -import sys, os.path -import tempfile -import unittest -sys.path.append("..") - -import pkg_resources - -pkg_resources.require("Pyphant") -pkg_resources.require("Pyphant_OSC") - -import numpy -from pyphant.visualizers.ImageVisualizer import ImageVisualizer -from pyphant.core import DataContainer as DC - -class TestImageVisualizer(unittest.TestCase): - """Create a two-dimensional field and check the problem-free generation of a labelled image.""" - def setUp(self): - self.n = 100 - self.m = 10 - self.kappa1=0.0 - self.errLevelPos = 6 - self.errLevelCurv= 5 - self.tmpdir = tempfile.gettempdir() - - def testVisualization(self): - X,LAMB = numpy.meshgrid(numpy.linspace(-1.5,1.5,self.n), - numpy.linspace(-1.0,1.0,self.m)) - self.lambDim = numpy.linspace(-1.0,1.0,self.m) - self.xDim = numpy.linspace(-1.5,1.5,self.n) - lambField = DC.FieldContainer(self.lambDim, - unit = '1 V / m**3', - longname='parameter', - shortname='\lambda') - xField = DC.FieldContainer(self.xDim, - unit = '1 m', - longname = 'position', - shortname = 'x') - #Prepare potential - V = [] - for i in xrange(len(lambField.data)): - u = X[i] - V.append(-lambField.data[i]/2* u**2 + u**4/4-u*self.kappa1) - self.V = DC.FieldContainer(numpy.array(V),unit='1 V',dimensions=[lambField,xField], - longname = 'electric potential', - shortname=r'\varphi') - - self.V.seal() - #Visualise result - visualizer = ImageVisualizer(self.V,show=False) - filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'.pdf') - visualizer.figure.savefig(filename) - -if __name__ == '__main__': - unittest.main() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zk...@us...> - 2008-12-09 14:47:35
|
Revision: 584 http://pyphant.svn.sourceforge.net/pyphant/?rev=584&view=rev Author: zklaus Date: 2008-12-09 14:47:29 +0000 (Tue, 09 Dec 2008) Log Message: ----------- Bugfix: Fixed some tests that relied on obsolete FieldContainer layout. Modified Paths: -------------- trunk/src/pyphant/pyphant/visualizers/tests/TestChart.py trunk/src/pyphant/pyphant/visualizers/tests/TestImageVisualizer.py Modified: trunk/src/pyphant/pyphant/visualizers/tests/TestChart.py =================================================================== --- trunk/src/pyphant/pyphant/visualizers/tests/TestChart.py 2008-12-09 14:46:22 UTC (rev 583) +++ trunk/src/pyphant/pyphant/visualizers/tests/TestChart.py 2008-12-09 14:47:29 UTC (rev 584) @@ -37,7 +37,7 @@ # $Source$ -import sys +import sys, os.path import tempfile import unittest sys.path.append("..") @@ -75,7 +75,7 @@ attributes={'title':'testVisualization'}) self.V.seal() visualizer = self.visualizer(self.V,show=False) - filename = self.tmpdir+'/pyphant-'+DC.parseId(self.V.id)[0]+'%s.png' % visualizer.name + filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'%s.pdf' % visualizer.name) visualizer.figure.savefig(filename.replace(' ','')) def testErrorVisualization(self): @@ -93,18 +93,18 @@ self.V.error = 0.1*numpy.abs(self.V.data) self.V.seal() visualizer = self.visualizer(self.V,show=False) - filename = self.tmpdir+'/pyphant-'+DC.parseId(self.V.id)[0]+'%s.png' % visualizer.name + filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'%s.pdf' % visualizer.name) visualizer.figure.savefig(filename.replace(' ','')) def testIntersectionXArray(self): X,LAMB = numpy.meshgrid(numpy.linspace(-1.5,1.5,self.n), numpy.linspace(-1.0,1.0,self.m)) - self.lambDim = LAMB[:,0] - self.xDim = X + self.lambDim = numpy.linspace(-1.0,1.0,self.m) + self.xDim = numpy.linspace(-1.5,1.5,self.n) lambField = DC.FieldContainer(self.lambDim, unit = '1 V / m**3', longname='parameter', - shortname=r'\lambda') + shortname='\lambda') xField = DC.FieldContainer(self.xDim, unit = '1 m', longname = 'position', @@ -112,15 +112,15 @@ #Prepare potential V = [] for i in xrange(len(lambField.data)): - u = xField.data[i] + u = X[i] V.append(-lambField.data[i]/2* u**2 + u**4/4-u*self.kappa1) - self.V = DC.FieldContainer(numpy.array(V),unit='1 V',dimensions=[xField], + self.V = DC.FieldContainer(numpy.array(V),unit='1 V',dimensions=[lambField,xField], longname = 'electric potential', - shortname=r'\varphi', - attributes={'title':'testIntersectionXArray'}) + shortname=r'\varphi') + self.V.seal() visualizer = self.visualizer(self.V,show=False) - filename = self.tmpdir+'/pyphant-'+DC.parseId(self.V.id)[0]+'%s.png' % visualizer.name + filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'%s.pdf' % visualizer.name) visualizer.figure.savefig(filename.replace(' ','')) @@ -142,13 +142,13 @@ for i in xrange(len(lambField.data)): u = X[i] V.append(-lambField.data[i]/2* u**2 + u**4/4-u*self.kappa1) - self.V = DC.FieldContainer(numpy.array(V),unit='1 V',dimensions=[xField,lambField], + self.V = DC.FieldContainer(numpy.array(V),unit='1 V',dimensions=[lambField, xField], longname = 'electric potential', shortname=r'\varphi', attributes={'title':'testIntersectionXVector'}) self.V.seal() visualizer = self.visualizer(self.V,show=False) - filename = self.tmpdir+'/pyphant-'+DC.parseId(self.V.id)[0]+'%s.png' % visualizer.name + filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'%s.pdf' % visualizer.name) visualizer.figure.savefig(filename.replace(' ','')) def testTableIncludingNan(self): @@ -167,13 +167,13 @@ x0,curv,mask = TEF.fixedPoints(lambField.data,kappa1=self.kappa1) fixedPoints = DC.FieldContainer(numpy.array(x0).transpose(), unit = xField.unit, - dimensions=[lambField,DC.generateIndex(0,3)], + dimensions=[DC.generateIndex(0,3), lambField], longname = 'position of the local extrema of electric potential', shortname = 'x_0', attributes={'title':'testTableIncludingNan'}) fixedPoints.seal() visualizer = self.visualizer(fixedPoints,show=False) - filename = self.tmpdir+'/pyphant-'+DC.parseId(fixedPoints.id)[0]+'%s.png' % visualizer.name + filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(fixedPoints.id)[0]+'%s.pdf' % visualizer.name) visualizer.figure.savefig(filename.replace(' ','')) def testTableIncludingNanAndErrors(self): @@ -192,14 +192,14 @@ x0,curv,mask = TEF.fixedPoints(lambField.data,kappa1=self.kappa1) fixedPoints = DC.FieldContainer(numpy.array(x0).transpose(), unit = xField.unit, - dimensions=[lambField,DC.generateIndex(0,3)], + dimensions=[DC.generateIndex(0,3), lambField], longname = 'position of the local extrema of electric potential', shortname = 'x_0', attributes={'title':'testTableIncludingNanAndErrors'}) fixedPoints.error = 0.1 * fixedPoints.data fixedPoints.seal() visualizer = self.visualizer(fixedPoints,show=False) - filename = self.tmpdir+'/pyphant-'+DC.parseId(fixedPoints.id)[0]+'%s.png' % visualizer.name + filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(fixedPoints.id)[0]+'%s.pdf' % visualizer.name) visualizer.figure.savefig(filename.replace(' ','')) class TestScatterPlot(TestLinePlot): Modified: trunk/src/pyphant/pyphant/visualizers/tests/TestImageVisualizer.py =================================================================== --- trunk/src/pyphant/pyphant/visualizers/tests/TestImageVisualizer.py 2008-12-09 14:46:22 UTC (rev 583) +++ trunk/src/pyphant/pyphant/visualizers/tests/TestImageVisualizer.py 2008-12-09 14:47:29 UTC (rev 584) @@ -29,7 +29,9 @@ # 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 unittests for ImageVisualizers. Because it is difficult to check the correct visualization of a image, it is just checked, wether the visualizers run without assertions.""" +u"""Provides unittests for ImageVisualizers. Because it is difficult +to check the correct visualization of a image, it is just checked, +wether the visualizers run without assertions.""" __id__ = "$Id$" __author__ = "$Author$" @@ -37,7 +39,7 @@ # $Source$ -import sys +import sys, os.path import tempfile import unittest sys.path.append("..") @@ -79,14 +81,14 @@ for i in xrange(len(lambField.data)): u = X[i] V.append(-lambField.data[i]/2* u**2 + u**4/4-u*self.kappa1) - self.V = DC.FieldContainer(numpy.array(V),unit='1 V',dimensions=[xField,lambField], + self.V = DC.FieldContainer(numpy.array(V),unit='1 V',dimensions=[lambField,xField], longname = 'electric potential', shortname=r'\varphi') self.V.seal() #Visualise result visualizer = ImageVisualizer(self.V,show=False) - filename = self.tmpdir+'/pyphant-'+DC.parseId(self.V.id)[0]+'.png' + filename = os.path.join(self.tmpdir,'pyphant-'+DC.parseId(self.V.id)[0]+'.pdf') visualizer.figure.savefig(filename) if __name__ == '__main__': This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zk...@us...> - 2008-12-09 14:46:34
|
Revision: 583 http://pyphant.svn.sourceforge.net/pyphant/?rev=583&view=rev Author: zklaus Date: 2008-12-09 14:46:22 +0000 (Tue, 09 Dec 2008) Log Message: ----------- Made fetching of up to date currency exchange rates optional. Modified Paths: -------------- trunk/src/pyphant/pyphant/quantities/PhysicalQuantities.py Modified: trunk/src/pyphant/pyphant/quantities/PhysicalQuantities.py =================================================================== --- trunk/src/pyphant/pyphant/quantities/PhysicalQuantities.py 2008-12-08 14:42:45 UTC (rev 582) +++ trunk/src/pyphant/pyphant/quantities/PhysicalQuantities.py 2008-12-09 14:46:22 UTC (rev 583) @@ -53,6 +53,8 @@ table, so use this at your own risk. """ +rc = { 'fetchCurrencyRates' : False } + class NumberDict(dict): """ @@ -901,37 +903,40 @@ _addUnit('VAL', 'EUR/1936.27' ,'Vatican City, Lira') #Get daily updated exchange rates -import urllib -from xml.dom import minidom -url = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml" -currencyNames={'USD':'US dollar' , 'JPY':'Japanese yen', - 'BGN':'Bulgarian lev' , 'CZK':'Czech koruna', - 'DKK':'Danish krone' , 'EEK':'Estonian kroon', - 'GBP':'Pound sterling' ,'HUF':'Hungarian forint', - 'LTL':'Lithuanian litas','LVL':'Latvian lats', - 'PLN':'Polish zloty', 'RON':'New Romanian leu', - 'SEK':'Swedish krona', 'SKK':'Slovak koruna', - 'CHF':'Swiss franc', 'ISK':'Icelandic krona', - 'NOK':'Norwegian krone', 'HRK':'Croatian kuna', - 'RUB':'Russian rouble', 'TRY':'New Turkish lira', - 'AUD':'Australian dollar','BRL':'Brasilian real', - 'CAD':'Canadian dollar', 'CNY':'Chinese yuan renminbi', - 'HKD':'Hong Kong dollar','IDR':'Indonesian rupiah', - 'KRW':'South Korean won','MXN':'Mexican peso', - 'MYR':'Malaysian ringgit','NZD':'New Zealand dollar', - 'PHP':'Philippine peso', 'SGD':'Singapore dollar', - 'THB':'Thai baht', 'ZAR':'South African rand'} -try: - doc = minidom.parseString(urllib.urlopen(url).read()) - elements = doc.documentElement.getElementsByTagName('Cube') - for element in elements[2:]: - currency = element.getAttribute('currency').encode('utf8') - _addUnit(currency, - 'EUR/%s' % element.getAttribute('rate').encode('utf8'), - currencyNames[currency]) - print "Added exchange rate of %s for %s." % (elements[1].getAttribute('time'),[i.getAttribute('currency').encode('utf8') for i in elements[2:]]) -except: - print "WARNING: No daily exchange rates available." +if rc['fetchCurrencyRates']: + import urllib + from xml.dom import minidom + url = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml" + currencyNames={'USD':'US dollar' , 'JPY':'Japanese yen', + 'BGN':'Bulgarian lev' , 'CZK':'Czech koruna', + 'DKK':'Danish krone' , 'EEK':'Estonian kroon', + 'GBP':'Pound sterling' ,'HUF':'Hungarian forint', + 'LTL':'Lithuanian litas','LVL':'Latvian lats', + 'PLN':'Polish zloty', 'RON':'New Romanian leu', + 'SEK':'Swedish krona', 'SKK':'Slovak koruna', + 'CHF':'Swiss franc', 'ISK':'Icelandic krona', + 'NOK':'Norwegian krone', 'HRK':'Croatian kuna', + 'RUB':'Russian rouble', 'TRY':'New Turkish lira', + 'AUD':'Australian dollar','BRL':'Brasilian real', + 'CAD':'Canadian dollar', 'CNY':'Chinese yuan renminbi', + 'HKD':'Hong Kong dollar','IDR':'Indonesian rupiah', + 'KRW':'South Korean won','MXN':'Mexican peso', + 'MYR':'Malaysian ringgit','NZD':'New Zealand dollar', + 'PHP':'Philippine peso', 'SGD':'Singapore dollar', + 'THB':'Thai baht', 'ZAR':'South African rand'} + try: + doc = minidom.parseString(urllib.urlopen(url).read()) + elements = doc.documentElement.getElementsByTagName('Cube') + for element in elements[2:]: + currency = element.getAttribute('currency').encode('utf8') + _addUnit(currency, + 'EUR/%s' % element.getAttribute('rate').encode('utf8'), + currencyNames[currency]) + print "Added exchange rate of %s for %s." % (elements[1].getAttribute('time'), + [ i.getAttribute('currency').encode('utf8') + for i in elements[2:] ]) + except: + print "WARNING: No daily exchange rates available." def description(): """Return a string describing all available units.""" 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-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-05 12:22:06
|
Revision: 579 http://pyphant.svn.sourceforge.net/pyphant/?rev=579&view=rev Author: liehr Date: 2008-12-05 11:45:16 +0000 (Fri, 05 Dec 2008) Log Message: ----------- viewOSC plots error of minima estimation. Modified Paths: -------------- trunk/doc/demo/viewOSC.py Modified: trunk/doc/demo/viewOSC.py =================================================================== --- trunk/doc/demo/viewOSC.py 2008-11-14 15:08:55 UTC (rev 578) +++ trunk/doc/demo/viewOSC.py 2008-12-05 11:45:16 UTC (rev 579) @@ -192,6 +192,10 @@ if not noIndicators: pylab.vlines(minimaPos.data[:,index],0.1,1.0, label ="$%s$"%minimaPos.shortname) + pylab.vlines(minimaPos.data[:,index]+minimaPos.error[:,index],0.1,1.0, + 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.title(result) pylab.xlabel(simulation.dimensions[1].label) 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:03
|
Revision: 581 http://pyphant.svn.sourceforge.net/pyphant/?rev=581&view=rev Author: liehr Date: 2008-12-05 11:46:43 +0000 (Fri, 05 Dec 2008) Log Message: ----------- Parameter estimation takes measurement error into account. Modified Paths: -------------- trunk/src/workers/OSC/OSC/EstimateParameter.py Modified: trunk/src/workers/OSC/OSC/EstimateParameter.py =================================================================== --- trunk/src/workers/OSC/OSC/EstimateParameter.py 2008-12-05 11:45:47 UTC (rev 580) +++ trunk/src/workers/OSC/OSC/EstimateParameter.py 2008-12-05 11:46:43 UTC (rev 581) @@ -56,24 +56,40 @@ _params = [("extentX", u"Extension of x-axis [%%]", 10, None), ("extentY", u"Extension of y-axis [%%]", 10, None)] - def calculateThickness(self, row, model): + def calculateThickness(self, row, model,error=None): if len(row)==0: return numpy.nan data = model.data.transpose() - def calc(row, col): - return sum([col[numpy.argmin((model.dimensions[0].data-c)**2)] for c in row]) - i = numpy.argmin(numpy.array([calc(row, col) for col in data])) + def calc(row, col,error): + if error: + return sum([col[numpy.argmin(((model.dimensions[0].data-c)/e)**2)] + for c,e in zip(row,error)]) + 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] @Worker.plug(Connectors.TYPE_IMAGE) def compute(self, model, experimental, subscriber=1): - minima = experimental.inUnitsOf(model.dimensions[0]).data.transpose() + renormedExp = experimental.inUnitsOf(model.dimensions[0]) + minima = renormedExp.data.transpose() + if renormedExp.error != None: + error = iter(renormedExp.error.transpose()) + else: + error = None parameter = [] inc = 100.0/float(len(minima)) acc = inc subscriber %= acc for row in minima: - parameter.append(self.calculateThickness( filter(lambda c: not numpy.isnan(c), row), model)) + if error: + filteredError = filter(lambda c: not numpy.isnan(c), error.next()) + else: + filteredError = None + parameter.append(self.calculateThickness( filter(lambda c: not numpy.isnan(c), row), + model, + filteredError)) acc += inc subscriber %= acc result = DataContainer.FieldContainer(numpy.array(parameter), This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <li...@us...> - 2008-11-14 15:08:57
|
Revision: 578 http://pyphant.svn.sourceforge.net/pyphant/?rev=578&view=rev Author: liehr Date: 2008-11-14 15:08:55 +0000 (Fri, 14 Nov 2008) Log Message: ----------- Adapted loading of FMF-ZIP archives to third generation parser. Modified Paths: -------------- trunk/src/workers/fmfile/fmfile/FMFLoader.py Modified: trunk/src/workers/fmfile/fmfile/FMFLoader.py =================================================================== --- trunk/src/workers/fmfile/fmfile/FMFLoader.py 2008-11-14 15:08:19 UTC (rev 577) +++ trunk/src/workers/fmfile/fmfile/FMFLoader.py 2008-11-14 15:08:55 UTC (rev 578) @@ -63,7 +63,11 @@ data = {} for i,pixelName in enumerate(names): b = z.read(pixelName) - data[pixelName] = readSingleFile(b, pixelName) + rawContainer = readSingleFile(b, pixelName) + if len(rawContainer)==1: + data[pixelName] = rawContainer[0] + else: + data[pixelName] = rawContainer subscriber %= float(i+1)/total*100.0 return data @@ -93,7 +97,7 @@ return (commonAttr, variableAttr) def column2FieldContainer(longname, column): - if type(column[0])==type((0,)) and len(column[0])==2: + if type(column[0])==type((0,)) and len(column[0])==3: shortname = column[0][0] if isPhysicalQuantity(column[0][1]): unit = column[0][1].unit @@ -231,7 +235,7 @@ \s*:\s* # divider (.*) # value (including list values and comments) $ # line end - ''', re.VERBOSE) + ''', re.VERBOSE) from StringIO import StringIO config = FMFConfigObj(d.encode('utf-8').splitlines(), encoding='utf-8') return config2tables(preParsedData, config) @@ -356,6 +360,8 @@ unit = PhysicalQuantity(unit.encode('utf-8')) except: unit = float(unit) + else: + unit = 1.0 fieldShortname=match.group('shortname') dimensions = match.group('deps') if dimensions != None: @@ -420,7 +426,7 @@ d = re.sub(dataExpr, preParseData, d) return preParsedData, d -class FMFLoader2(Worker.Worker): +class FMFLoader(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: <li...@us...> - 2008-11-14 15:08:25
|
Revision: 577 http://pyphant.svn.sourceforge.net/pyphant/?rev=577&view=rev Author: liehr Date: 2008-11-14 15:08:19 +0000 (Fri, 14 Nov 2008) Log Message: ----------- Renamed third generation Full-Metadata-Format parser to FMFLoader.py. Modified Paths: -------------- trunk/src/workers/fmfile/fmfile/__init__.py Added Paths: ----------- trunk/src/workers/fmfile/fmfile/FMFLoader.py Removed Paths: ------------- trunk/src/workers/fmfile/fmfile/FMFLoader2.py Copied: trunk/src/workers/fmfile/fmfile/FMFLoader.py (from rev 576, trunk/src/workers/fmfile/fmfile/FMFLoader2.py) =================================================================== --- trunk/src/workers/fmfile/fmfile/FMFLoader.py (rev 0) +++ trunk/src/workers/fmfile/fmfile/FMFLoader.py 2008-11-14 15:08:19 UTC (rev 577) @@ -0,0 +1,439 @@ +# -*- coding: utf-8 -*- + +# Copyright (c) 2008, 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""" +""" + +__id__ = "$Id$" +__author__ = "$Author$" +__version__ = "$Revision$" +# $Source$ + +import zipfile, numpy, re, collections, copy, StringIO, os.path +from pyphant.core import (Worker, Connectors, + Param, DataContainer) +from pyphant.quantities.PhysicalQuantities import PhysicalQuantity,isPhysicalUnit,isPhysicalQuantity +import logging +_logger = logging.getLogger("pyphant") + + +def normation(normationStr): + try: + unit = PhysicalQuantity(str(normationStr)) + except: + try: + unit = PhysicalQuantity(1.0,str(normationStr)) + except: + unit = float(normationStr) + return unit + +def loadDataFromZip(filename, subscriber=1): + z = zipfile.ZipFile(filename, 'r') + names = z.namelist() + total = len(names) + assert total>0, "The loaded FMF archive named %s does not contain any files." % filename + data = {} + for i,pixelName in enumerate(names): + b = z.read(pixelName) + data[pixelName] = readSingleFile(b, pixelName) + subscriber %= float(i+1)/total*100.0 + return data + +def collectAttributes(data): + #Collect attributes, define filename as new attribute + atts = {u'filename': []} + for filename,sc in data.iteritems(): + atts['filename'].append(filename) + for section,sectionDict in sc.attributes.iteritems(): + for key,treetoken in sectionDict.iteritems(): + attlist = atts.setdefault(key, []) + attlist.append(treetoken) + #Separate common attributes from variable attributes + commonAttr = {} + variableAttr = {} + for k,l in atts.iteritems(): + v = l[0] + isConst=True + for i in l[1:]: + if i!=v: + isConst=False + #break + if isConst: + commonAttr[k]=v + else: + variableAttr[k]=l + return (commonAttr, variableAttr) + +def column2FieldContainer(longname, column): + if type(column[0])==type((0,)) and len(column[0])==2: + shortname = column[0][0] + if isPhysicalQuantity(column[0][1]): + unit = column[0][1].unit + field = [row[1].inUnitsOf(unit).value for row in column] + else: + unit = 1.0 + field = [row[1] for row in column] + result = DataContainer.FieldContainer(numpy.array(field),unit=PhysicalQuantity(1.0, unit),shortname=shortname,longname=longname) + else: + result = DataContainer.FieldContainer(numpy.array(column),longname=longname) + return result + +def unpackAndCollateFields(variableAttr, data): + fieldData = {} + dependencies = {} + units = {} + shortnames = {} + for filename in variableAttr['filename']: + sample = data[filename] + for field in sample.columns: + if field.longname in fieldData: + conversionFactor = normation(field.unit) / units[field.longname] + fieldData[field.longname].append(field.data * conversionFactor) + dimensionNames = [dim.longname for dim in field.dimensions + if dim.longname!=u'Index'] + if len(dimensionNames)>1: + _logger.warning("Is specified, but has not been tested!") + if dependencies[field.longname] != dimensionNames: + raise ValueError, "The data sets of the FMF archive have inconsistent dependencies in section [*data definitions]." + else: + fieldData[field.longname]=[field.data] + dependencies[field.longname]=[dim.longname for dim in field.dimensions + if dim.longname!=u'Index'] + units[field.longname] = normation(field.unit) + shortnames[field.longname]=field.shortname + return fieldData, dependencies, units, shortnames + +def checkAndCondense(data): + reference = data[0] + for element in data[1:]: + numpy.testing.assert_array_almost_equal(reference, element) + return reference + +def readZipFile(filename, subscriber=1): + data = loadDataFromZip(filename, subscriber) + commonAttr, variableAttr = collectAttributes(data) + #Wrap variable attributes into FieldContainer + containers = [ column2FieldContainer(longname, column) for longname, column in variableAttr.iteritems()] + #Process SampleContainers of parsed FMF files and skip independent variables, which are used as dimensions. + fieldData, dependencies, units, shortnames = unpackAndCollateFields(variableAttr, data) + independentFieldsNames = [] + for fieldName,dependency in dependencies.iteritems(): + if dependencies[fieldName]==[]: + independentFieldsNames.append(fieldName) + for fieldName in independentFieldsNames: + del dependencies[fieldName] + #Build independent fields + independentFields = {} + for indepField in independentFieldsNames: + indepData = checkAndCondense(fieldData[indepField]) + independentFields[indepField] = DataContainer.FieldContainer(numpy.array(indepData), + longname=indepField,shortname=shortnames[indepField], + unit = units[indepField],rescale=True) + #Build dependent fields + #QUESTION: Can a field depend on a dependent field? + for field,dependency in dependencies.iteritems(): + newField = DataContainer.FieldContainer(numpy.array(fieldData[field]), + longname=field, + shortname=shortnames[field], + unit = units[field],rescale=True) + for i,indepField in enumerate(dependency): + dim = len(newField.dimensions)-i-1 + newField.dimensions[dim]=independentFields[indepField] + assert newField.isValid() + containers.append(newField) + return DataContainer.SampleContainer(containers,attributes=commonAttr) + +def reshapeField(field): + if field.isIndependent(): + return field + dimData = [numpy.unique(d.data) for d in field.dimensions] + fieldData = numpy.ones([len(d) for d in dimData])*numpy.nan + data = numpy.vstack([field.data]+[d.data for d in field.dimensions]).transpose() + for row in data: + fieldData[[numpy.argwhere(dimData[i]==v) for i,v in enumerate(row[1:])]] = row[0] + newDims = [ DataContainer.FieldContainer(dimData[i], + f.unit, + longname=f.longname, + shortname=f.shortname, + attributes=f.attributes) + for i, f in enumerate(field.dimensions) ] + newField = DataContainer.FieldContainer(fieldData, + field.unit, + mask=numpy.isnan(fieldData), + dimensions=newDims, + longname=field.longname, + shortname=field.shortname, + attributes=field.attributes) + return newField + +def readDataFile(filename): + filehandle = open(filename,'r') + dat = filehandle.read() + filehandle.close() + rawContainer = readSingleFile(dat,filename) + if len(rawContainer)==1: + container = rawContainer[0] + container.seal() + return container + newSample = DataContainer.SampleContainer(rawContainer, + longname='List of tables', + shortname='L', + attributes=copy.deepcopy(rawContainer[0].attributes)) + newSample.seal() + return newSample + +def loadFMFFromFile(filename, subscriber=0): + try: + return readZipFile(filename, subscriber=subscriber) + except zipfile.BadZipfile: + return readDataFile(filename) + +def readSingleFile(b, pixelName): + _logger.info(u"Parsing file %s." % pixelName) + preParsedData, d = preParseData(b) + from configobj import ConfigObj + class FMFConfigObj(ConfigObj): + _keyword = re.compile(r'''^ # line start + (\s*) # indentation + ( # keyword + (?:".*?")| # double quotes + (?:'.*?')| # single quotes + (?:[^'":].*?) # no quotes + ) + \s*:\s* # divider + (.*) # value (including list values and comments) + $ # line end + ''', re.VERBOSE) + from StringIO import StringIO + config = FMFConfigObj(d.encode('utf-8').splitlines(), encoding='utf-8') + return config2tables(preParsedData, config) + +def config2tables(preParsedData, config): + 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): + 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)] + 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 + + return oldVal + + if config.has_key('*table definitions'): + longnames = dict([(i,k) for k,i in config['*table definitions'].iteritems()]) + del config['*table definitions'] + else: + longnames = { None : 'Table' } + tables = [] + for k in config: + if k.startswith('*data definitions'): + if k == '*data definitions': + shortname = None + else: + shortname = k.split(':')[1].strip() + tables.append(data2table(longnames[shortname], + shortname, + preParsedData[shortname], + config[k])) + del config[k] + attributes = config.walk(item2value) + for t in tables: + t.attributes = copy.deepcopy(attributes) + 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 = {} + dimensions_for_fields = {} + errors_for_fields = {} + for i, (fieldLongname, spec) in enumerate(config.items()): + match = re.search(colspec_re, spec) + unit = match.group('unit') + if unit != None: + unit = unit[1:-1] + if unit.startswith('.'): + unit = '0'+unit + elif unit == '%': + unit = 0.01 + elif not unit[0].isdigit(): + unit = '1'+unit + try: + unit = unit.replace('^', '**') + unit = PhysicalQuantity(unit.encode('utf-8')) + except: + unit = float(unit) + fieldShortname=match.group('shortname') + dimensions = match.group('deps') + if dimensions != None: + dimensions_for_fields[fieldShortname] = dimensions[1:-1].split(',') + else: + dimensions_for_fields[fieldShortname] = None + errors_for_fields[fieldShortname] = match.group('error') + field = DataContainer.FieldContainer(datTable[i], + longname=fieldLongname, + shortname=fieldShortname, + unit=unit) + fields.append(field) + fields_by_name[fieldShortname] = field + for f in fields: + sn = f.shortname + dims = dimensions_for_fields[sn] + if dims != None: + f.dimensions = [ fields_by_name[d] for d in dims ] + error = errors_for_fields[sn] + if error != None: + try: + error = float(error) + f.error = numpy.ones(f.data.shape)*error + except: + f.error = fields_by_name[error].inUnitsOf(f).data + fields = [ reshapeField(field) for field in fields ] + if shortname==None: + shortname='T' + return DataContainer.SampleContainer(fields, + longname=longname, + shortname=shortname) + + +def preParseData(b): + 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()]=='whitespace': + localVar[key.strip()] = None + if localVar[key.strip()]=='semicolon': + 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) + d = re.sub(commentExpr, '', d) + preParsedData = {} + def preParseData(match): + try: + 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"" + d = re.sub(dataExpr, preParseData, d) + return preParsedData, d + +class FMFLoader2(Worker.Worker): + API = 2 + VERSION = 1 + REVISION = "$Revision$"[11:-1] + name = "Load FMF files" + + _params=[("filename", u"Filename", "", Connectors.SUBTYPE_FILE)] + + @Worker.plug(Connectors.TYPE_ARRAY) + def loadFMF(self, subscriber=0): + filename = self.paramFilename.value + if not os.path.exists(filename): + raise RuntimeError("Opening non existant file: "+filename) + result = loadFMFFromFile(filename, subscriber) + result.seal() + return result + Deleted: trunk/src/workers/fmfile/fmfile/FMFLoader2.py =================================================================== --- trunk/src/workers/fmfile/fmfile/FMFLoader2.py 2008-11-14 15:07:38 UTC (rev 576) +++ trunk/src/workers/fmfile/fmfile/FMFLoader2.py 2008-11-14 15:08:19 UTC (rev 577) @@ -1,439 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright (c) 2008, 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""" -""" - -__id__ = "$Id$" -__author__ = "$Author$" -__version__ = "$Revision$" -# $Source$ - -import zipfile, numpy, re, collections, copy, StringIO, os.path -from pyphant.core import (Worker, Connectors, - Param, DataContainer) -from pyphant.quantities.PhysicalQuantities import PhysicalQuantity,isPhysicalUnit,isPhysicalQuantity -import logging -_logger = logging.getLogger("pyphant") - - -def normation(normationStr): - try: - unit = PhysicalQuantity(str(normationStr)) - except: - try: - unit = PhysicalQuantity(1.0,str(normationStr)) - except: - unit = float(normationStr) - return unit - -def loadDataFromZip(filename, subscriber=1): - z = zipfile.ZipFile(filename, 'r') - names = z.namelist() - total = len(names) - assert total>0, "The loaded FMF archive named %s does not contain any files." % filename - data = {} - for i,pixelName in enumerate(names): - b = z.read(pixelName) - data[pixelName] = readSingleFile(b, pixelName) - subscriber %= float(i+1)/total*100.0 - return data - -def collectAttributes(data): - #Collect attributes, define filename as new attribute - atts = {u'filename': []} - for filename,sc in data.iteritems(): - atts['filename'].append(filename) - for section,sectionDict in sc.attributes.iteritems(): - for key,treetoken in sectionDict.iteritems(): - attlist = atts.setdefault(key, []) - attlist.append(treetoken) - #Separate common attributes from variable attributes - commonAttr = {} - variableAttr = {} - for k,l in atts.iteritems(): - v = l[0] - isConst=True - for i in l[1:]: - if i!=v: - isConst=False - #break - if isConst: - commonAttr[k]=v - else: - variableAttr[k]=l - return (commonAttr, variableAttr) - -def column2FieldContainer(longname, column): - if type(column[0])==type((0,)) and len(column[0])==2: - shortname = column[0][0] - if isPhysicalQuantity(column[0][1]): - unit = column[0][1].unit - field = [row[1].inUnitsOf(unit).value for row in column] - else: - unit = 1.0 - field = [row[1] for row in column] - result = DataContainer.FieldContainer(numpy.array(field),unit=PhysicalQuantity(1.0, unit),shortname=shortname,longname=longname) - else: - result = DataContainer.FieldContainer(numpy.array(column),longname=longname) - return result - -def unpackAndCollateFields(variableAttr, data): - fieldData = {} - dependencies = {} - units = {} - shortnames = {} - for filename in variableAttr['filename']: - sample = data[filename] - for field in sample.columns: - if field.longname in fieldData: - conversionFactor = normation(field.unit) / units[field.longname] - fieldData[field.longname].append(field.data * conversionFactor) - dimensionNames = [dim.longname for dim in field.dimensions - if dim.longname!=u'Index'] - if len(dimensionNames)>1: - _logger.warning("Is specified, but has not been tested!") - if dependencies[field.longname] != dimensionNames: - raise ValueError, "The data sets of the FMF archive have inconsistent dependencies in section [*data definitions]." - else: - fieldData[field.longname]=[field.data] - dependencies[field.longname]=[dim.longname for dim in field.dimensions - if dim.longname!=u'Index'] - units[field.longname] = normation(field.unit) - shortnames[field.longname]=field.shortname - return fieldData, dependencies, units, shortnames - -def checkAndCondense(data): - reference = data[0] - for element in data[1:]: - numpy.testing.assert_array_almost_equal(reference, element) - return reference - -def readZipFile(filename, subscriber=1): - data = loadDataFromZip(filename, subscriber) - commonAttr, variableAttr = collectAttributes(data) - #Wrap variable attributes into FieldContainer - containers = [ column2FieldContainer(longname, column) for longname, column in variableAttr.iteritems()] - #Process SampleContainers of parsed FMF files and skip independent variables, which are used as dimensions. - fieldData, dependencies, units, shortnames = unpackAndCollateFields(variableAttr, data) - independentFieldsNames = [] - for fieldName,dependency in dependencies.iteritems(): - if dependencies[fieldName]==[]: - independentFieldsNames.append(fieldName) - for fieldName in independentFieldsNames: - del dependencies[fieldName] - #Build independent fields - independentFields = {} - for indepField in independentFieldsNames: - indepData = checkAndCondense(fieldData[indepField]) - independentFields[indepField] = DataContainer.FieldContainer(numpy.array(indepData), - longname=indepField,shortname=shortnames[indepField], - unit = units[indepField],rescale=True) - #Build dependent fields - #QUESTION: Can a field depend on a dependent field? - for field,dependency in dependencies.iteritems(): - newField = DataContainer.FieldContainer(numpy.array(fieldData[field]), - longname=field, - shortname=shortnames[field], - unit = units[field],rescale=True) - for i,indepField in enumerate(dependency): - dim = len(newField.dimensions)-i-1 - newField.dimensions[dim]=independentFields[indepField] - assert newField.isValid() - containers.append(newField) - return DataContainer.SampleContainer(containers,attributes=commonAttr) - -def reshapeField(field): - if field.isIndependent(): - return field - dimData = [numpy.unique(d.data) for d in field.dimensions] - fieldData = numpy.ones([len(d) for d in dimData])*numpy.nan - data = numpy.vstack([field.data]+[d.data for d in field.dimensions]).transpose() - for row in data: - fieldData[[numpy.argwhere(dimData[i]==v) for i,v in enumerate(row[1:])]] = row[0] - newDims = [ DataContainer.FieldContainer(dimData[i], - f.unit, - longname=f.longname, - shortname=f.shortname, - attributes=f.attributes) - for i, f in enumerate(field.dimensions) ] - newField = DataContainer.FieldContainer(fieldData, - field.unit, - mask=numpy.isnan(fieldData), - dimensions=newDims, - longname=field.longname, - shortname=field.shortname, - attributes=field.attributes) - return newField - -def readDataFile(filename): - filehandle = open(filename,'r') - dat = filehandle.read() - filehandle.close() - rawContainer = readSingleFile(dat,filename) - if len(rawContainer)==1: - container = rawContainer[0] - container.seal() - return container - newSample = DataContainer.SampleContainer(rawContainer, - longname='List of tables', - shortname='L', - attributes=copy.deepcopy(rawContainer[0].attributes)) - newSample.seal() - return newSample - -def loadFMFFromFile(filename, subscriber=0): - try: - return readZipFile(filename, subscriber=subscriber) - except zipfile.BadZipfile: - return readDataFile(filename) - -def readSingleFile(b, pixelName): - _logger.info(u"Parsing file %s." % pixelName) - preParsedData, d = preParseData(b) - from configobj import ConfigObj - class FMFConfigObj(ConfigObj): - _keyword = re.compile(r'''^ # line start - (\s*) # indentation - ( # keyword - (?:".*?")| # double quotes - (?:'.*?')| # single quotes - (?:[^'":].*?) # no quotes - ) - \s*:\s* # divider - (.*) # value (including list values and comments) - $ # line end - ''', re.VERBOSE) - from StringIO import StringIO - config = FMFConfigObj(d.encode('utf-8').splitlines(), encoding='utf-8') - return config2tables(preParsedData, config) - -def config2tables(preParsedData, config): - 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): - 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)] - 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 - - return oldVal - - if config.has_key('*table definitions'): - longnames = dict([(i,k) for k,i in config['*table definitions'].iteritems()]) - del config['*table definitions'] - else: - longnames = { None : 'Table' } - tables = [] - for k in config: - if k.startswith('*data definitions'): - if k == '*data definitions': - shortname = None - else: - shortname = k.split(':')[1].strip() - tables.append(data2table(longnames[shortname], - shortname, - preParsedData[shortname], - config[k])) - del config[k] - attributes = config.walk(item2value) - for t in tables: - t.attributes = copy.deepcopy(attributes) - 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 = {} - dimensions_for_fields = {} - errors_for_fields = {} - for i, (fieldLongname, spec) in enumerate(config.items()): - match = re.search(colspec_re, spec) - unit = match.group('unit') - if unit != None: - unit = unit[1:-1] - if unit.startswith('.'): - unit = '0'+unit - elif unit == '%': - unit = 0.01 - elif not unit[0].isdigit(): - unit = '1'+unit - try: - unit = unit.replace('^', '**') - unit = PhysicalQuantity(unit.encode('utf-8')) - except: - unit = float(unit) - fieldShortname=match.group('shortname') - dimensions = match.group('deps') - if dimensions != None: - dimensions_for_fields[fieldShortname] = dimensions[1:-1].split(',') - else: - dimensions_for_fields[fieldShortname] = None - errors_for_fields[fieldShortname] = match.group('error') - field = DataContainer.FieldContainer(datTable[i], - longname=fieldLongname, - shortname=fieldShortname, - unit=unit) - fields.append(field) - fields_by_name[fieldShortname] = field - for f in fields: - sn = f.shortname - dims = dimensions_for_fields[sn] - if dims != None: - f.dimensions = [ fields_by_name[d] for d in dims ] - error = errors_for_fields[sn] - if error != None: - try: - error = float(error) - f.error = numpy.ones(f.data.shape)*error - except: - f.error = fields_by_name[error].inUnitsOf(f).data - fields = [ reshapeField(field) for field in fields ] - if shortname==None: - shortname='T' - return DataContainer.SampleContainer(fields, - longname=longname, - shortname=shortname) - - -def preParseData(b): - 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()]=='whitespace': - localVar[key.strip()] = None - if localVar[key.strip()]=='semicolon': - 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) - d = re.sub(commentExpr, '', d) - preParsedData = {} - def preParseData(match): - try: - 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"" - d = re.sub(dataExpr, preParseData, d) - return preParsedData, d - -class FMFLoader2(Worker.Worker): - API = 2 - VERSION = 1 - REVISION = "$Revision$"[11:-1] - name = "Load FMF files" - - _params=[("filename", u"Filename", "", Connectors.SUBTYPE_FILE)] - - @Worker.plug(Connectors.TYPE_ARRAY) - def loadFMF(self, subscriber=0): - filename = self.paramFilename.value - if not os.path.exists(filename): - raise RuntimeError("Opening non existant file: "+filename) - result = loadFMFFromFile(filename, subscriber) - result.seal() - return result - Modified: trunk/src/workers/fmfile/fmfile/__init__.py =================================================================== --- trunk/src/workers/fmfile/fmfile/__init__.py 2008-11-14 15:07:38 UTC (rev 576) +++ trunk/src/workers/fmfile/fmfile/__init__.py 2008-11-14 15:08:19 UTC (rev 577) @@ -38,6 +38,5 @@ __version__ = "$Revision$" # $Source$ -workers=["FMFLoader", - "FMFLoader2"] +workers=["FMFLoader"] This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <li...@us...> - 2008-11-14 15:07:45
|
Revision: 576 http://pyphant.svn.sourceforge.net/pyphant/?rev=576&view=rev Author: liehr Date: 2008-11-14 15:07:38 +0000 (Fri, 14 Nov 2008) Log Message: ----------- Removed ANTLR based Full-Metadata-Format parser. Removed Paths: ------------- trunk/src/workers/fmfile/fmfile/FMFLoader.py trunk/src/workers/fmfile/fmfile/FMFpython.g trunk/src/workers/fmfile/fmfile/FMFpython.tokens trunk/src/workers/fmfile/fmfile/FMFpythonLexer.py trunk/src/workers/fmfile/fmfile/FMFpythonParser.py trunk/src/workers/fmfile/fmfile/FMFpythonTree.g trunk/src/workers/fmfile/fmfile/FMFpythonTree.py trunk/src/workers/fmfile/fmfile/FMFpythonTree.tokens trunk/src/workers/fmfile/fmfile/FMFpython__.g trunk/src/workers/fmfile/fmfile/tokens.py trunk/src/workers/fmfile/fmfile/update_tokens.sh Deleted: trunk/src/workers/fmfile/fmfile/FMFLoader.py =================================================================== --- trunk/src/workers/fmfile/fmfile/FMFLoader.py 2008-11-11 11:17:53 UTC (rev 575) +++ trunk/src/workers/fmfile/fmfile/FMFLoader.py 2008-11-14 15:07:38 UTC (rev 576) @@ -1,275 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright (c) 2008, 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""" -""" - -__id__ = "$Id$" -__author__ = "$Author$" -__version__ = "$Revision$" -# $Source$ - -import zipfile, numpy, re, collections, copy, StringIO, os.path -from pyphant.core import (Worker, Connectors, - Param, DataContainer) -import antlr3 -from FMFpythonLexer import FMFpythonLexer -from FMFpythonParser import FMFpythonParser -from FMFpythonTree import FMFpythonTree -from pyphant.quantities.PhysicalQuantities import PhysicalQuantity,isPhysicalUnit,isPhysicalQuantity -import logging -_logger = logging.getLogger("pyphant") - - -def normation(normationStr): - try: - unit = PhysicalQuantity(str(normationStr)) - except: - try: - unit = PhysicalQuantity(1.0,str(normationStr)) - except: - unit = float(normationStr) - return unit - -def loadDataFromZip(filename, subscriber=1): - z = zipfile.ZipFile(filename, 'r') - names = z.namelist() - total = len(names) - assert total>0, "The loaded FMF archive named %s does not contain any files." % filename - data = {} - for i,pixelName in enumerate(names): - b = z.read(pixelName) - data[pixelName] = readSingleFile(b, pixelName) - subscriber %= float(i+1)/total*100.0 - return data - -def collectAttributes(data): - #Collect attributes, define filename as new attribute - atts = {u'filename': []} - for filename,sc in data.iteritems(): - atts['filename'].append(filename) - for section,sectionDict in sc.attributes.iteritems(): - for key,treetoken in sectionDict.iteritems(): - attlist = atts.setdefault(key, []) - attlist.append(treetoken) - #Separate common attributes from variable attributes - commonAttr = {} - variableAttr = {} - for k,l in atts.iteritems(): - v = l[0] - isConst=True - for i in l[1:]: - if i!=v: - isConst=False - #break - if isConst: - commonAttr[k]=v - else: - variableAttr[k]=l - return (commonAttr, variableAttr) - -def column2FieldContainer(longname, column): - if type(column[0])==type((0,)) and len(column[0])==2: - shortname = column[0][0] - if isPhysicalQuantity(column[0][1]): - unit = column[0][1].unit - field = [row[1].inUnitsOf(unit).value for row in column] - else: - unit = 1.0 - field = [row[1] for row in column] - result = DataContainer.FieldContainer(numpy.array(field),unit=PhysicalQuantity(1.0, unit),shortname=shortname,longname=longname) - else: - result = DataContainer.FieldContainer(numpy.array(column),longname=longname) - return result - -def unpackAndCollateFields(variableAttr, data): - fieldData = {} - dependencies = {} - units = {} - shortnames = {} - for filename in variableAttr['filename']: - sample = data[filename] - for field in sample.columns: - if field.longname in fieldData: - conversionFactor = normation(field.unit) / units[field.longname] - fieldData[field.longname].append(field.data * conversionFactor) - dimensionNames = [dim.longname for dim in field.dimensions - if dim.longname!=u'Index'] - if len(dimensionNames)>1: - _logger.warning("Is specified, but has not been tested!") - if dependencies[field.longname] != dimensionNames: - raise ValueError, "The data sets of the FMF archive have inconsistent dependencies in section [*data definitions]." - else: - fieldData[field.longname]=[field.data] - dependencies[field.longname]=[dim.longname for dim in field.dimensions - if dim.longname!=u'Index'] - units[field.longname] = normation(field.unit) - shortnames[field.longname]=field.shortname - return fieldData, dependencies, units, shortnames - -def checkAndCondense(data): - reference = data[0] - for element in data[1:]: - numpy.testing.assert_array_almost_equal(reference, element) - return reference - -def readZipFile(filename, subscriber=1): - data = loadDataFromZip(filename, subscriber) - commonAttr, variableAttr = collectAttributes(data) - #Wrap variable attributes into FieldContainer - containers = [ column2FieldContainer(longname, column) for longname, column in variableAttr.iteritems()] - #Process SampleContainers of parsed FMF files and skip independent variables, which are used as dimensions. - fieldData, dependencies, units, shortnames = unpackAndCollateFields(variableAttr, data) - independentFieldsNames = [] - for fieldName,dependency in dependencies.iteritems(): - if dependencies[fieldName]==[]: - independentFieldsNames.append(fieldName) - for fieldName in independentFieldsNames: - del dependencies[fieldName] - #Build independent fields - independentFields = {} - for indepField in independentFieldsNames: - indepData = checkAndCondense(fieldData[indepField]) - independentFields[indepField] = DataContainer.FieldContainer(numpy.array(indepData), - longname=indepField,shortname=shortnames[indepField], - unit = units[indepField],rescale=True) - #Build dependent fields - #QUESTION: Can a field depend on a dependent field? - for field,dependency in dependencies.iteritems(): - newField = DataContainer.FieldContainer(numpy.array(fieldData[field]), - longname=field, - shortname=shortnames[field], - unit = units[field],rescale=True) - for i,indepField in enumerate(dependency): - dim = len(newField.dimensions)-i-1 - newField.dimensions[dim]=independentFields[indepField] - assert newField.isValid() - containers.append(newField) - return DataContainer.SampleContainer(containers,attributes=commonAttr) - -def reshapeField(field): - dimData = [numpy.unique(d.data) for d in field.dimensions] - fieldData = numpy.ones([len(d) for d in dimData])*numpy.nan - data = numpy.vstack([field.data]+[d.data for d in field.dimensions]).transpose() - for row in data: - fieldData[[numpy.argwhere(dimData[i]==v) for i,v in enumerate(row[1:])]] = row[0] - newDims = [ DataContainer.FieldContainer(dimData[i], - f.unit, - longname=f.longname, - shortname=f.shortname, - attributes=f.attributes) - for i, f in enumerate(field.dimensions) ] - newField = DataContainer.FieldContainer(fieldData, - field.unit, - mask=numpy.isnan(fieldData), - dimensions=newDims, - longname=field.longname, - shortname=field.shortname, - attributes=field.attributes) - return newField - -def readDataFile(filename): - filehandle = open(filename,'r') - dat = filehandle.read() - filehandle.close() - rawContainer = readSingleFile(dat,filename) - newContainer = [ reshapeField(field) - for field in rawContainer.columns - if not field.isIndependent() ] - newSample = DataContainer.SampleContainer(newContainer, - longname=rawContainer.longname, - shortname=rawContainer.shortname, - attributes=rawContainer.attributes) - newSample.seal() - return newSample - -def loadFMFFromFile(filename, subscriber=0): - try: - return readZipFile(filename, subscriber=subscriber) - except zipfile.BadZipfile: - return readDataFile(filename) - -def readSingleFile(b, pixelName): - _logger.info(u"Parsing file %s." % pixelName) - localVar = {} - if b[0] == ';': - items = [var.strip().split(':') for var in b.split('-*-')[1].split(';')] - for key,value in items: - localVar[key]=value - localVar.update({'fmf-version':'1.0','coding':'cp1252'}) - d = unicode(b, localVar['coding']) - dataExpr = re.compile(ur"^(\[\*data(?::([^\]]*))?\]\r?\n)([^[]*)", re.M | re.S) - preParsedData = {} - def preParseData(match): - try: - preParsedData[match.group(2)] = numpy.loadtxt(StringIO.StringIO(match.group(3)), unpack=True) - except: - return match.group(0) - return match.group(1) - d = re.sub(dataExpr, preParseData, d) - stringstream = antlr3.ANTLRStringStream(d) - lexer = FMFpythonLexer(stringstream) - tokens = antlr3.CommonTokenStream(lexer) - parser = FMFpythonParser(tokens) - data = parser.config() - nodes = antlr3.tree.CommonTreeNodeStream(data.tree) - nodes.setTokenStream(tokens) - walker = FMFpythonTree(nodes) - data = walker.dataContainer() - if None in preParsedData.keys(): - for i in xrange(len(preParsedData[None])): - data[i].data = preParsedData[None][i] - #The FieldContainer objects containing indices have to be set directly, - #otherwise the respective dimenensional FieldContainers are numpy.arrays - #of zero with, which cannot be plotted, nor saved to hdf. - for field in data: - for i,dim in enumerate(field.dimensions): - if len(dim.data)==0: - field.dimensions[i] = DataContainer.generateIndex(i,field.data.shape[i]) - return data - -class FMFLoader(Worker.Worker): - API = 2 - VERSION = 1 - REVISION = "$Revision$"[11:-1] - name = "Load FMF files" - - _params=[("filename", u"Filename", "", Connectors.SUBTYPE_FILE)] - - @Worker.plug(Connectors.TYPE_ARRAY) - def loadFMF(self, subscriber=0): - filename = self.paramFilename.value - if not os.path.exists(filename): - raise RuntimeError("Opening non existant file: "+filename) - result = loadFMFFromFile(filename, subscriber) - result.seal() - return result - Deleted: trunk/src/workers/fmfile/fmfile/FMFpython.g =================================================================== --- trunk/src/workers/fmfile/fmfile/FMFpython.g 2008-11-11 11:17:53 UTC (rev 575) +++ trunk/src/workers/fmfile/fmfile/FMFpython.g 2008-11-14 15:07:38 UTC (rev 576) @@ -1,209 +0,0 @@ -grammar FMFpython; - -options { - language=Python; - output=AST; -} - -tokens { - CONFIG; - HEADER; - COMMON_SECTION; - DATADEF_SECTION; - DATA_SECTION; - BODY; - ITEM; - DATASET; - KEY; - DATETIME; - DATE; - TIME; - NUMBER; - VARIABLE; - IDENTIFIER; - QUANTITY; - UNIT; - STRING; - COLSPEC; - LONGNAME; - DEPS; -} - -NEWLINE : ('\r'? '\n')+; -WS : (' ' | '\t')+ {$channel=HIDDEN;}; -COMMENT : (';' | '#') .* NEWLINE {$channel=HIDDEN;}; - -LBRACK : '['; -RBRACK : ']'; -LPAREN : '('; -RPAREN : ')'; -ASTERISK: '*'; -COLON : ':'; -EQUALS : '='; -fragment -PLUS : '+'; -NPLUS : (NPLUS DIGIT)=> PLUS; -fragment -MINUS : '-'; -NMINUS : (NMINUS DIGIT)=> MINUS; - -fragment -LCURLY : '{'; -fragment -RCURLY : '}'; -fragment -UNDERSCORE - : '_'; -fragment -HAT : '^'; -fragment -DIV : '/'; -fragment -DOLLAR : '$'; -fragment -PERCENTAGE - : '%'; -fragment -LESSTHAN: '<'; -fragment -GREATERTHAN - : '>'; -fragment -DIGIT : ( '0' .. '9' ) ; -fragment -DIGITS : DIGIT+; -fragment -LETTERS : 'a'..'z' | 'A'..'Z'; -fragment -FFLOAT : '.' DIGITS EXPONENT? - | (DIGITS '.' ~DIGIT) =>DIGITS '.' EXPONENT? - | (DIGITS '.' DIGITS ~'.') => DIGITS '.' DIGITS EXPONENT? - ; -fragment -EXPONENT - : ('e' | 'E') ( PLUS | MINUS )? DIGITS - ; -fragment -IINT : '0' ('x' | 'X') ( '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' )+ //hex - | '0' DIGITS* //octal - | '1'..'9' DIGITS* //decimal - ; -fragment -ESC : '\\' .; - - -GERMANDATE - : DIGIT? DIGIT '.' DIGIT? DIGIT '.' (DIGIT DIGIT)? DIGIT DIGIT; -ISODATE : DIGIT DIGIT DIGIT DIGIT MINUS DIGIT DIGIT MINUS DIGIT DIGIT; - -FLOAT : (FFLOAT ~('j'|'J'|'i'|'I')) => FFLOAT; - -INT : (IINT ~('j'|'J'|'i'|'I')) => IINT; - -IMAG : IINT ('j'|'J'|'i'|'I') - | FFLOAT ('j'|'J'|'i'|'I') - ; - -fragment -RWORD : ('\\' | LETTERS) ('\\' | LETTERS | DIGITS | UNDERSCORE | HAT | LCURLY | RCURLY | MINUS)* - ; - -WORD : RWORD - | LESSTHAN RWORD GREATERTHAN - ; - -PUNCTUATION - : '.' | ',' | ';'; - -LITERAL : '"' (ESC|~('\\'|'\n'|'"'))* '"' - | '\'' (ESC|~('\\'|'\n'|'\''))* '\'' - ; - -config - : referenceSection commonSection* datadefSection dataSection - -> ^(CONFIG referenceSection commonSection* datadefSection dataSection) - ; - -referenceSection - : LBRACK ASTERISK 'reference' RBRACK NEWLINE commonitem+ - -> ^(COMMON_SECTION ^(HEADER ASTERISK 'reference') ^(BODY commonitem+)); - -datadefSection - : LBRACK ASTERISK 'data definitions' RBRACK NEWLINE colitem+ - -> ^(DATADEF_SECTION ^(HEADER ASTERISK 'data definitions') ^(BODY colitem+)); - -dataSection - : LBRACK ASTERISK 'data' RBRACK NEWLINE dataitem* - -> ^(DATA_SECTION ^(HEADER ASTERISK 'data') ^(BODY dataitem*)); - -commonSection - : LBRACK headername RBRACK NEWLINE commonitem+ - -> ^(COMMON_SECTION ^(HEADER headername) ^(BODY commonitem+)); - -headername - : ~ASTERISK .*; - -colitem : key COLON colspec NEWLINE -> ^(COLSPEC ^(LONGNAME key) colspec); -dataitem - : cell+ NEWLINE -> ^(DATASET cell+); -commonitem - : key COLON value NEWLINE -> ^(ITEM ^(KEY key) value); - -cell : number -> ^(NUMBER number) - | WORD -> ^(STRING WORD) - | LITERAL -> ^(STRING LITERAL) - ; - -colspec : identifier deps? (LBRACK unit RBRACK)? -> ^(IDENTIFIER identifier) ^(DEPS deps?) ^(UNIT unit?); - -deps : LPAREN identifier ( ',' identifier)* RPAREN -> identifier+; - -key : ~LBRACK .*; - -value -options { - backtrack=true; - memoize=true; -} - : number -> ^(NUMBER number) - | identifier EQUALS quantity -> ^(VARIABLE ^(IDENTIFIER identifier) quantity) - | datetime -> datetime - | catchall -> ^(STRING catchall) - ; - -identifier: WORD; -/* -identifier - : WORD ( UNDERSCORE ((LCURLY WORD RCURLY) | WORD | INT) - | HAT ((LCURLY WORD RCURLY) | WORD | INT))? - ; -*/ - -catchall - : ~NEWLINE*; - -datetime - : date time? -> ^(DATETIME ^(DATE date) ^(TIME time?)); - -date : GERMANDATE | ISODATE; - -time : INT COLON INT (COLON FLOAT)?; - -number : (NPLUS|NMINUS)? absnumber; - -fragment -absnumber -options { - backtrack=true; -} - : FLOAT (NPLUS|NMINUS) IMAG - | INT (NPLUS|NMINUS) IMAG - | FLOAT - | INT - | IMAG - ; - -quantity - : number unit? -> ^(QUANTITY ^(NUMBER number) ^(UNIT unit?)); - -unit : WORD ((ASTERISK|DIV) WORD)*; Deleted: trunk/src/workers/fmfile/fmfile/FMFpython.tokens =================================================================== --- trunk/src/workers/fmfile/fmfile/FMFpython.tokens 2008-11-11 11:17:53 UTC (rev 575) +++ trunk/src/workers/fmfile/fmfile/FMFpython.tokens 2008-11-14 15:07:38 UTC (rev 576) @@ -1,64 +0,0 @@ -LESSTHAN=47 -MINUS=38 -DATASET=11 -IINT=53 -NUMBER=16 -FLOAT=57 -GERMANDATE=55 -COLSPEC=22 -PUNCTUATION=62 -LETTERS=50 -NEWLINE=25 -GREATERTHAN=48 -RCURLY=41 -LCURLY=40 -LITERAL=63 -DATADEF_SECTION=7 -INT=58 -DATETIME=13 -DATE=14 -DATA_SECTION=8 -RPAREN=31 -COMMON_SECTION=6 -LPAREN=30 -QUANTITY=19 -PLUS=35 -DIGIT=37 -BODY=9 -RWORD=60 -DEPS=24 -DIGITS=49 -NMINUS=39 -WS=26 -NPLUS=36 -STRING=21 -CONFIG=4 -DOLLAR=45 -COMMENT=27 -ISODATE=56 -ESC=54 -ITEM=10 -UNIT=20 -LBRACK=28 -LONGNAME=23 -IMAG=59 -EQUALS=34 -TIME=15 -WORD=61 -HAT=43 -EXPONENT=51 -VARIABLE=17 -KEY=12 -FFLOAT=52 -ASTERISK=32 -RBRACK=29 -COLON=33 -DIV=44 -IDENTIFIER=18 -PERCENTAGE=46 -HEADER=5 -UNDERSCORE=42 -','=67 -'data'=66 -'data definitions'=65 -'reference'=64 Deleted: trunk/src/workers/fmfile/fmfile/FMFpythonLexer.py =================================================================== --- trunk/src/workers/fmfile/fmfile/FMFpythonLexer.py 2008-11-11 11:17:53 UTC (rev 575) +++ trunk/src/workers/fmfile/fmfile/FMFpythonLexer.py 2008-11-14 15:07:38 UTC (rev 576) @@ -1,2378 +0,0 @@ -# $ANTLR 3.0.1 FMFpython.g 2008-10-15 18:08:07 - -from antlr3 import * -from antlr3.compat import set, frozenset - - -# for convenience in actions -HIDDEN = BaseRecognizer.HIDDEN - -# token types -LESSTHAN=47 -MINUS=38 -DATASET=11 -NUMBER=16 -IINT=53 -FLOAT=57 -GERMANDATE=55 -COLSPEC=22 -PUNCTUATION=62 -LETTERS=50 -NEWLINE=25 -T64=64 -GREATERTHAN=48 -RCURLY=41 -LCURLY=40 -LITERAL=63 -DATADEF_SECTION=7 -INT=58 -DATETIME=13 -DATE=14 -DATA_SECTION=8 -RPAREN=31 -COMMON_SECTION=6 -LPAREN=30 -QUANTITY=19 -PLUS=35 -DIGIT=37 -BODY=9 -RWORD=60 -DEPS=24 -DIGITS=49 -NMINUS=39 -WS=26 -NPLUS=36 -STRING=21 -CONFIG=4 -T66=66 -DOLLAR=45 -COMMENT=27 -ISODATE=56 -ESC=54 -T65=65 -ITEM=10 -UNIT=20 -LBRACK=28 -LONGNAME=23 -EQUALS=34 -IMAG=59 -TIME=15 -WORD=61 -HAT=43 -EXPONENT=51 -KEY=12 -VARIABLE=17 -EOF=-1 -T67=67 -FFLOAT=52 -ASTERISK=32 -Tokens=68 -RBRACK=29 -COLON=33 -DIV=44 -IDENTIFIER=18 -HEADER=5 -PERCENTAGE=46 -UNDERSCORE=42 - -class FMFpythonLexer(Lexer): - - grammarFileName = "FMFpython.g" - - def __init__(self, input=None): - Lexer.__init__(self, input) - self.ruleMemo = {} - self.dfa9 = self.DFA9( - self, 9, - eot = self.DFA9_eot, - eof = self.DFA9_eof, - min = self.DFA9_min, - max = self.DFA9_max, - accept = self.DFA9_accept, - special = self.DFA9_special, - transition = self.DFA9_transition - ) - self.dfa18 = self.DFA18( - self, 18, - eot = self.DFA18_eot, - eof = self.DFA18_eof, - min = self.DFA18_min, - max = self.DFA18_max, - accept = self.DFA18_accept, - special = self.DFA18_special, - transition = self.DFA18_transition - ) - self.dfa24 = self.DFA24( - self, 24, - eot = self.DFA24_eot, - eof = self.DFA24_eof, - min = self.DFA24_min, - max = self.DFA24_max, - accept = self.DFA24_accept, - special = self.DFA24_special, - transition = self.DFA24_transition - ) - - - - - - - # $ANTLR start T64 - def mT64(self, ): - - try: - self.type = T64 - - # FMFpython.g:7:5: ( 'reference' ) - # FMFpython.g:7:7: 'reference' - self.match("reference") - if self.failed: - return - - - - - - finally: - - pass - - # $ANTLR end T64 - - - - # $ANTLR start T65 - def mT65(self, ): - - try: - self.type = T65 - - # FMFpython.g:8:5: ( 'data definitions' ) - # FMFpython.g:8:7: 'data definitions' - self.match("data definitions") - if self.failed: - return - - - - - - finally: - - pass - - # $ANTLR end T65 - - - - # $ANTLR start T66 - def mT66(self, ): - - try: - self.type = T66 - - # FMFpython.g:9:5: ( 'data' ) - # FMFpython.g:9:7: 'data' - self.match("data") - if self.failed: - return - - - - - - finally: - - pass - - # $ANTLR end T66 - - - - # $ANTLR start T67 - def mT67(self, ): - - try: - self.type = T67 - - # FMFpython.g:10:5: ( ',' ) - # FMFpython.g:10:7: ',' - self.match(u',') - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end T67 - - - - # $ANTLR start NEWLINE - def mNEWLINE(self, ): - - try: - self.type = NEWLINE - - # FMFpython.g:32:9: ( ( ( '\\r' )? '\\n' )+ ) - # FMFpython.g:32:17: ( ( '\\r' )? '\\n' )+ - # FMFpython.g:32:17: ( ( '\\r' )? '\\n' )+ - cnt2 = 0 - while True: #loop2 - alt2 = 2 - LA2_0 = self.input.LA(1) - - if (LA2_0 == u'\n' or LA2_0 == u'\r') : - alt2 = 1 - - - if alt2 == 1: - # FMFpython.g:32:18: ( '\\r' )? '\\n' - # FMFpython.g:32:18: ( '\\r' )? - alt1 = 2 - LA1_0 = self.input.LA(1) - - if (LA1_0 == u'\r') : - alt1 = 1 - if alt1 == 1: - # FMFpython.g:32:18: '\\r' - self.match(u'\r') - if self.failed: - return - - - - self.match(u'\n') - if self.failed: - return - - - else: - if cnt2 >= 1: - break #loop2 - - if self.backtracking > 0: - self.failed = True - return - - eee = EarlyExitException(2, self.input) - raise eee - - cnt2 += 1 - - - - - - - finally: - - pass - - # $ANTLR end NEWLINE - - - - # $ANTLR start WS - def mWS(self, ): - - try: - self.type = WS - - # FMFpython.g:33:9: ( ( ' ' | '\\t' )+ ) - # FMFpython.g:33:17: ( ' ' | '\\t' )+ - # FMFpython.g:33:17: ( ' ' | '\\t' )+ - cnt3 = 0 - while True: #loop3 - alt3 = 2 - LA3_0 = self.input.LA(1) - - if (LA3_0 == u'\t' or LA3_0 == u' ') : - alt3 = 1 - - - if alt3 == 1: - # FMFpython.g: - if self.input.LA(1) == u'\t' or self.input.LA(1) == u' ': - self.input.consume(); - self.failed = False - - else: - if self.backtracking > 0: - self.failed = True - return - - mse = MismatchedSetException(None, self.input) - self.recover(mse) - raise mse - - - - - else: - if cnt3 >= 1: - break #loop3 - - if self.backtracking > 0: - self.failed = True - return - - eee = EarlyExitException(3, self.input) - raise eee - - cnt3 += 1 - - - if self.backtracking == 0: - self.channel=HIDDEN; - - - - - - finally: - - pass - - # $ANTLR end WS - - - - # $ANTLR start COMMENT - def mCOMMENT(self, ): - - try: - self.type = COMMENT - - # FMFpython.g:34:9: ( ( ';' | '#' ) ( . )* NEWLINE ) - # FMFpython.g:34:17: ( ';' | '#' ) ( . )* NEWLINE - if self.input.LA(1) == u'#' or self.input.LA(1) == u';': - self.input.consume(); - self.failed = False - - else: - if self.backtracking > 0: - self.failed = True - return - - mse = MismatchedSetException(None, self.input) - self.recover(mse) - raise mse - - - # FMFpython.g:34:29: ( . )* - while True: #loop4 - alt4 = 2 - LA4_0 = self.input.LA(1) - - if (LA4_0 == u'\r') : - alt4 = 2 - elif (LA4_0 == u'\n') : - alt4 = 2 - elif ((u'\u0000' <= LA4_0 <= u'\t') or (u'\u000B' <= LA4_0 <= u'\f') or (u'\u000E' <= LA4_0 <= u'\uFFFE')) : - alt4 = 1 - - - if alt4 == 1: - # FMFpython.g:34:29: . - self.matchAny() - if self.failed: - return - - - else: - break #loop4 - - - self.mNEWLINE() - if self.failed: - return - if self.backtracking == 0: - self.channel=HIDDEN; - - - - - - finally: - - pass - - # $ANTLR end COMMENT - - - - # $ANTLR start LBRACK - def mLBRACK(self, ): - - try: - self.type = LBRACK - - # FMFpython.g:36:9: ( '[' ) - # FMFpython.g:36:17: '[' - self.match(u'[') - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end LBRACK - - - - # $ANTLR start RBRACK - def mRBRACK(self, ): - - try: - self.type = RBRACK - - # FMFpython.g:37:9: ( ']' ) - # FMFpython.g:37:17: ']' - self.match(u']') - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end RBRACK - - - - # $ANTLR start LPAREN - def mLPAREN(self, ): - - try: - self.type = LPAREN - - # FMFpython.g:38:9: ( '(' ) - # FMFpython.g:38:17: '(' - self.match(u'(') - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end LPAREN - - - - # $ANTLR start RPAREN - def mRPAREN(self, ): - - try: - self.type = RPAREN - - # FMFpython.g:39:9: ( ')' ) - # FMFpython.g:39:17: ')' - self.match(u')') - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end RPAREN - - - - # $ANTLR start ASTERISK - def mASTERISK(self, ): - - try: - self.type = ASTERISK - - # FMFpython.g:40:9: ( '*' ) - # FMFpython.g:40:17: '*' - self.match(u'*') - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end ASTERISK - - - - # $ANTLR start COLON - def mCOLON(self, ): - - try: - self.type = COLON - - # FMFpython.g:41:9: ( ':' ) - # FMFpython.g:41:17: ':' - self.match(u':') - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end COLON - - - - # $ANTLR start EQUALS - def mEQUALS(self, ): - - try: - self.type = EQUALS - - # FMFpython.g:42:9: ( '=' ) - # FMFpython.g:42:17: '=' - self.match(u'=') - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end EQUALS - - - - # $ANTLR start PLUS - def mPLUS(self, ): - - try: - # FMFpython.g:44:9: ( '+' ) - # FMFpython.g:44:17: '+' - self.match(u'+') - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end PLUS - - - - # $ANTLR start NPLUS - def mNPLUS(self, ): - - try: - self.type = NPLUS - - # FMFpython.g:45:9: ( ( NPLUS DIGIT )=> PLUS ) - # FMFpython.g:45:17: ( NPLUS DIGIT )=> PLUS - self.mPLUS() - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end NPLUS - - - - # $ANTLR start MINUS - def mMINUS(self, ): - - try: - # FMFpython.g:47:9: ( '-' ) - # FMFpython.g:47:17: '-' - self.match(u'-') - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end MINUS - - - - # $ANTLR start NMINUS - def mNMINUS(self, ): - - try: - self.type = NMINUS - - # FMFpython.g:48:9: ( ( NMINUS DIGIT )=> MINUS ) - # FMFpython.g:48:17: ( NMINUS DIGIT )=> MINUS - self.mMINUS() - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end NMINUS - - - - # $ANTLR start LCURLY - def mLCURLY(self, ): - - try: - # FMFpython.g:51:9: ( '{' ) - # FMFpython.g:51:17: '{' - self.match(u'{') - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end LCURLY - - - - # $ANTLR start RCURLY - def mRCURLY(self, ): - - try: - # FMFpython.g:53:9: ( '}' ) - # FMFpython.g:53:17: '}' - self.match(u'}') - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end RCURLY - - - - # $ANTLR start UNDERSCORE - def mUNDERSCORE(self, ): - - try: - # FMFpython.g:56:9: ( '_' ) - # FMFpython.g:56:17: '_' - self.match(u'_') - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end UNDERSCORE - - - - # $ANTLR start HAT - def mHAT(self, ): - - try: - # FMFpython.g:58:9: ( '^' ) - # FMFpython.g:58:17: '^' - self.match(u'^') - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end HAT - - - - # $ANTLR start DIV - def mDIV(self, ): - - try: - # FMFpython.g:60:9: ( '/' ) - # FMFpython.g:60:17: '/' - self.match(u'/') - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end DIV - - - - # $ANTLR start DOLLAR - def mDOLLAR(self, ): - - try: - # FMFpython.g:62:9: ( '$' ) - # FMFpython.g:62:17: '$' - self.match(u'$') - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end DOLLAR - - - - # $ANTLR start PERCENTAGE - def mPERCENTAGE(self, ): - - try: - # FMFpython.g:65:9: ( '%' ) - # FMFpython.g:65:17: '%' - self.match(u'%') - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end PERCENTAGE - - - - # $ANTLR start LESSTHAN - def mLESSTHAN(self, ): - - try: - # FMFpython.g:67:9: ( '<' ) - # FMFpython.g:67:17: '<' - self.match(u'<') - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end LESSTHAN - - - - # $ANTLR start GREATERTHAN - def mGREATERTHAN(self, ): - - try: - # FMFpython.g:70:9: ( '>' ) - # FMFpython.g:70:17: '>' - self.match(u'>') - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end GREATERTHAN - - - - # $ANTLR start DIGIT - def mDIGIT(self, ): - - try: - # FMFpython.g:72:9: ( ( '0' .. '9' ) ) - # FMFpython.g:72:11: ( '0' .. '9' ) - if (u'0' <= self.input.LA(1) <= u'9'): - self.input.consume(); - self.failed = False - - else: - if self.backtracking > 0: - self.failed = True - return - - mse = MismatchedSetException(None, self.input) - self.recover(mse) - raise mse - - - - - - - finally: - - pass - - # $ANTLR end DIGIT - - - - # $ANTLR start DIGITS - def mDIGITS(self, ): - - try: - # FMFpython.g:74:9: ( ( DIGIT )+ ) - # FMFpython.g:74:11: ( DIGIT )+ - # FMFpython.g:74:11: ( DIGIT )+ - cnt5 = 0 - while True: #loop5 - alt5 = 2 - LA5_0 = self.input.LA(1) - - if ((u'0' <= LA5_0 <= u'9')) : - alt5 = 1 - - - if alt5 == 1: - # FMFpython.g:74:11: DIGIT - self.mDIGIT() - if self.failed: - return - - - else: - if cnt5 >= 1: - break #loop5 - - if self.backtracking > 0: - self.failed = True - return - - eee = EarlyExitException(5, self.input) - raise eee - - cnt5 += 1 - - - - - - - finally: - - pass - - # $ANTLR end DIGITS - - - - # $ANTLR start LETTERS - def mLETTERS(self, ): - - try: - # FMFpython.g:76:9: ( 'a' .. 'z' | 'A' .. 'Z' ) - # FMFpython.g: - if (u'A' <= self.input.LA(1) <= u'Z') or (u'a' <= self.input.LA(1) <= u'z'): - self.input.consume(); - self.failed = False - - else: - if self.backtracking > 0: - self.failed = True - return - - mse = MismatchedSetException(None, self.input) - self.recover(mse) - raise mse - - - - - - - finally: - - pass - - # $ANTLR end LETTERS - - - - # $ANTLR start FFLOAT - def mFFLOAT(self, ): - - try: - # FMFpython.g:78:9: ( '.' DIGITS ( EXPONENT )? | ( DIGITS '.' ~ DIGIT )=> DIGITS '.' ( EXPONENT )? | ( DIGITS '.' DIGITS ~ '.' )=> DIGITS '.' DIGITS ( EXPONENT )? ) - alt9 = 3 - alt9 = self.dfa9.predict(self.input) - if alt9 == 1: - # FMFpython.g:78:13: '.' DIGITS ( EXPONENT )? - self.match(u'.') - if self.failed: - return - self.mDIGITS() - if self.failed: - return - # FMFpython.g:78:24: ( EXPONENT )? - alt6 = 2 - LA6_0 = self.input.LA(1) - - if (LA6_0 == u'E' or LA6_0 == u'e') : - alt6 = 1 - if alt6 == 1: - # FMFpython.g:78:24: EXPONENT - self.mEXPONENT() - if self.failed: - return - - - - - - elif alt9 == 2: - # FMFpython.g:79:13: ( DIGITS '.' ~ DIGIT )=> DIGITS '.' ( EXPONENT )? - self.mDIGITS() - if self.failed: - return - self.match(u'.') - if self.failed: - return - # FMFpython.g:79:46: ( EXPONENT )? - alt7 = 2 - LA7_0 = self.input.LA(1) - - if (LA7_0 == u'E' or LA7_0 == u'e') : - alt7 = 1 - if alt7 == 1: - # FMFpython.g:79:46: EXPONENT - self.mEXPONENT() - if self.failed: - return - - - - - - elif alt9 == 3: - # FMFpython.g:80:13: ( DIGITS '.' DIGITS ~ '.' )=> DIGITS '.' DIGITS ( EXPONENT )? - self.mDIGITS() - if self.failed: - return - self.match(u'.') - if self.failed: - return - self.mDIGITS() - if self.failed: - return - # FMFpython.g:80:59: ( EXPONENT )? - alt8 = 2 - LA8_0 = self.input.LA(1) - - if (LA8_0 == u'E' or LA8_0 == u'e') : - alt8 = 1 - if alt8 == 1: - # FMFpython.g:80:59: EXPONENT - self.mEXPONENT() - if self.failed: - return - - - - - - - finally: - - pass - - # $ANTLR end FFLOAT - - - - # $ANTLR start EXPONENT - def mEXPONENT(self, ): - - try: - # FMFpython.g:84:9: ( ( 'e' | 'E' ) ( PLUS | MINUS )? DIGITS ) - # FMFpython.g:84:14: ( 'e' | 'E' ) ( PLUS | MINUS )? DIGITS - if self.input.LA(1) == u'E' or self.input.LA(1) == u'e': - self.input.consume(); - self.failed = False - - else: - if self.backtracking > 0: - self.failed = True - return - - mse = MismatchedSetException(None, self.input) - self.recover(mse) - raise mse - - - # FMFpython.g:84:26: ( PLUS | MINUS )? - alt10 = 2 - LA10_0 = self.input.LA(1) - - if (LA10_0 == u'+' or LA10_0 == u'-') : - alt10 = 1 - if alt10 == 1: - # FMFpython.g: - if self.input.LA(1) == u'+' or self.input.LA(1) == u'-': - self.input.consume(); - self.failed = False - - else: - if self.backtracking > 0: - self.failed = True - return - - mse = MismatchedSetException(None, self.input) - self.recover(mse) - raise mse - - - - - - self.mDIGITS() - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end EXPONENT - - - - # $ANTLR start IINT - def mIINT(self, ): - - try: - # FMFpython.g:87:9: ( '0' ( 'x' | 'X' ) ( '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' )+ | '0' ( DIGITS )* | '1' .. '9' ( DIGITS )* ) - alt14 = 3 - LA14_0 = self.input.LA(1) - - if (LA14_0 == u'0') : - LA14_1 = self.input.LA(2) - - if (LA14_1 == u'X' or LA14_1 == u'x') : - alt14 = 1 - else: - alt14 = 2 - elif ((u'1' <= LA14_0 <= u'9')) : - alt14 = 3 - else: - if self.backtracking > 0: - self.failed = True - return - - nvae = NoViableAltException("86:1: fragment IINT : ( '0' ( 'x' | 'X' ) ( '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' )+ | '0' ( DIGITS )* | '1' .. '9' ( DIGITS )* );", 14, 0, self.input) - - raise nvae - - if alt14 == 1: - # FMFpython.g:87:11: '0' ( 'x' | 'X' ) ( '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' )+ - self.match(u'0') - if self.failed: - return - if self.input.LA(1) == u'X' or self.input.LA(1) == u'x': - self.input.consume(); - self.failed = False - - else: - if self.backtracking > 0: - self.failed = True - return - - mse = MismatchedSetException(None, self.input) - self.recover(mse) - raise mse - - - # FMFpython.g:87:27: ( '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' )+ - cnt11 = 0 - while True: #loop11 - alt11 = 2 - LA11_0 = self.input.LA(1) - - if ((u'0' <= LA11_0 <= u'9') or (u'A' <= LA11_0 <= u'F') or (u'a' <= LA11_0 <= u'f')) : - alt11 = 1 - - - if alt11 == 1: - # FMFpython.g: - if (u'0' <= self.input.LA(1) <= u'9') or (u'A' <= self.input.LA(1) <= u'F') or (u'a' <= self.input.LA(1) <= u'f'): - self.input.consume(); - self.failed = False - - else: - if self.backtracking > 0: - self.failed = True - return - - mse = MismatchedSetException(None, self.input) - self.recover(mse) - raise mse - - - - - else: - if cnt11 >= 1: - break #loop11 - - if self.backtracking > 0: - self.failed = True - return - - eee = EarlyExitException(11, self.input) - raise eee - - cnt11 += 1 - - - - - elif alt14 == 2: - # FMFpython.g:88:11: '0' ( DIGITS )* - self.match(u'0') - if self.failed: - return - # FMFpython.g:88:15: ( DIGITS )* - while True: #loop12 - alt12 = 2 - LA12_0 = self.input.LA(1) - - if ((u'0' <= LA12_0 <= u'9')) : - alt12 = 1 - - - if alt12 == 1: - # FMFpython.g:88:15: DIGITS - self.mDIGITS() - if self.failed: - return - - - else: - break #loop12 - - - - - elif alt14 == 3: - # FMFpython.g:89:11: '1' .. '9' ( DIGITS )* - self.matchRange(u'1', u'9') - if self.failed: - return - # FMFpython.g:89:20: ( DIGITS )* - while True: #loop13 - alt13 = 2 - LA13_0 = self.input.LA(1) - - if ((u'0' <= LA13_0 <= u'9')) : - alt13 = 1 - - - if alt13 == 1: - # FMFpython.g:89:20: DIGITS - self.mDIGITS() - if self.failed: - return - - - else: - break #loop13 - - - - - - finally: - - pass - - # $ANTLR end IINT - - - - # $ANTLR start ESC - def mESC(self, ): - - try: - # FMFpython.g:92:9: ( '\\\\' . ) - # FMFpython.g:92:11: '\\\\' . - self.match(u'\\') - if self.failed: - return - self.matchAny() - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end ESC - - - - # $ANTLR start GERMANDATE - def mGERMANDATE(self, ): - - try: - self.type = GERMANDATE - - # FMFpython.g:96:9: ( ( DIGIT )? DIGIT '.' ( DIGIT )? DIGIT '.' ( DIGIT DIGIT )? DIGIT DIGIT ) - # FMFpython.g:96:11: ( DIGIT )? DIGIT '.' ( DIGIT )? DIGIT '.' ( DIGIT DIGIT )? DIGIT DIGIT - # FMFpython.g:96:11: ( DIGIT )? - alt15 = 2 - LA15_0 = self.input.LA(1) - - if ((u'0' <= LA15_0 <= u'9')) : - LA15_1 = self.input.LA(2) - - if ((u'0' <= LA15_1 <= u'9')) : - alt15 = 1 - if alt15 == 1: - # FMFpython.g:96:11: DIGIT - self.mDIGIT() - if self.failed: - return - - - - self.mDIGIT() - if self.failed: - return - self.match(u'.') - if self.failed: - return - # FMFpython.g:96:28: ( DIGIT )? - alt16 = 2 - LA16_0 = self.input.LA(1) - - if ((u'0' <= LA16_0 <= u'9')) : - LA16_1 = self.input.LA(2) - - if ((u'0' <= LA16_1 <= u'9')) : - alt16 = 1 - if alt16 == 1: - # FMFpython.g:96:28: DIGIT - self.mDIGIT() - if self.failed: - return - - - - self.mDIGIT() - if self.failed: - return - self.match(u'.') - if self.failed: - return - # FMFpython.g:96:45: ( DIGIT DIGIT )? - alt17 = 2 - LA17_0 = self.input.LA(1) - - if ((u'0' <= LA17_0 <= u'9')) : - LA17_1 = self.input.LA(2) - - if ((u'0' <= LA17_1 <= u'9')) : - LA17_2 = self.input.LA(3) - - if ((u'0' <= LA17_2 <= u'9')) : - alt17 = 1 - if alt17 == 1: - # FMFpython.g:96:46: DIGIT DIGIT - self.mDIGIT() - if self.failed: - return - self.mDIGIT() - if self.failed: - return - - - - self.mDIGIT() - if self.failed: - return - self.mDIGIT() - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end GERMANDATE - - - - # $ANTLR start ISODATE - def mISODATE(self, ): - - try: - self.type = ISODATE - - # FMFpython.g:97:9: ( DIGIT DIGIT DIGIT DIGIT MINUS DIGIT DIGIT MINUS DIGIT DIGIT ) - # FMFpython.g:97:11: DIGIT DIGIT DIGIT DIGIT MINUS DIGIT DIGIT MINUS DIGIT DIGIT - self.mDIGIT() - if self.failed: - return - self.mDIGIT() - if self.failed: - return - self.mDIGIT() - if self.failed: - return - self.mDIGIT() - if self.failed: - return - self.mMINUS() - if self.failed: - return - self.mDIGIT() - if self.failed: - return - self.mDIGIT() - if self.failed: - return - self.mMINUS() - if self.failed: - return - self.mDIGIT() - if self.failed: - return - self.mDIGIT() - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end ISODATE - - - - # $ANTLR start FLOAT - def mFLOAT(self, ): - - try: - self.type = FLOAT - - # FMFpython.g:99:9: ( ( FFLOAT ~ ( 'j' | 'J' | 'i' | 'I' ) )=> FFLOAT ) - # FMFpython.g:99:11: ( FFLOAT ~ ( 'j' | 'J' | 'i' | 'I' ) )=> FFLOAT - self.mFFLOAT() - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end FLOAT - - - - # $ANTLR start INT - def mINT(self, ): - - try: - self.type = INT - - # FMFpython.g:101:9: ( ( IINT ~ ( 'j' | 'J' | 'i' | 'I' ) )=> IINT ) - # FMFpython.g:101:11: ( IINT ~ ( 'j' | 'J' | 'i' | 'I' ) )=> IINT - self.mIINT() - if self.failed: - return - - - - - finally: - - pass - - # $ANTLR end INT - - - - # $ANTLR start IMAG - def mIMAG(self, ): - - try: - self.type = IMAG - - # FMFpython.g:103:9: ( IINT ( 'j' | 'J' | 'i' | 'I' ) | FFLOAT ( 'j' | 'J' | 'i' | 'I' ) ) - alt18 = 2 - alt18 = self.dfa18.predict(self.input) - if alt18 == 1: - # FMFpython.g:103:13: IINT ( 'j' | 'J' | 'i' | 'I' ) - self.mIINT() - if self.failed: - return - if (u'I' <= self.input.LA(1) <= u'J') or (u'i' <= self.input.LA(1) <= u'j'): - self.input.consume(); - self.failed = False - - else: - if self.backtracking > 0: - self.failed = True - return - - mse = MismatchedSetException(None, self.input) - self.recover(mse) - raise mse - - - - - elif alt18 == 2: - # FMFpython.g:104:13: FFLOAT ( 'j' | 'J' | 'i' | 'I' ) - self.mFFLOAT() - if self.failed: - return - if (u'I' <= self.input.LA(1) <= u'J') or (u'i' <= self.input.LA(1) <= u'j'): - self.input.consume(); - self.failed = False - - else: - if self.backtracking > 0: - self.failed = True - return - - mse = MismatchedSetException(None, self.input) - self.recover(mse) - raise mse - - - - - - finally: - - pass - - # $ANTLR end IMAG - - - - # $ANTLR start RWORD - def mRWORD(self, ): - - try: - # FMFpython.g:108:9: ( ( '\\\\' | LETTERS ) ( '\\\\' | LETTERS | DIGITS | UNDERSCORE | HAT | LCURLY | RCURLY | MINUS )* ) - # FMFpython.g:108:11: ( '\\\\' | LETTERS ) ( '\\\\' | LETTERS | DIGITS | UNDERSCORE | HAT | LCURLY | RCURLY | MINUS )* - if (u'A' <= self.input.LA(1) <= u'Z') or self.input.LA(1) == u'\\' or (u'a' <= self.input.LA(1) <= u'z'): - self.input.consume(); - self.failed = False - - else: - if self.backtracking > 0: - self.failed = True - return - - mse = MismatchedSetException(None, self.input) - self.recover(mse) - raise mse - - - # FMFpython.g:108:28: ( '\\\\' | LETTERS | DIGITS | UNDERSCORE | HAT | LCURLY | RCURLY | MINUS )* - while True: #loop19 - alt19 = 9 - LA19 = self.input.LA(1) - if LA19 == u'\\': - alt19 = 1 - elif LA19 == u'A' or LA19 == u'B' or LA19 == u'C' or LA19 == u'D' or LA19 == u'E' or LA19 == u'F' or LA19 == u'G' or LA19 == u'H' or LA19 == u'I' or LA19 == u'J' or LA19 == u'K' or LA19 == u'L' or LA19 == u'M' or LA19 == u'N' or LA19 == u'O' or LA19 == u'P' or LA19 == u'Q' or LA19 == u'R' or LA19 == u'S' or LA19 == u'T' or LA19 == u'U' or LA19 == u'V' or LA19 == u'W' or LA19 == u'X' or LA19 == u'Y' or LA19 == u'Z' or LA19 == u'a' or LA19 == u'b' or LA19 == u'c' or LA19 == u'd' or LA19 == u'e' or LA19 == u'f' or LA19 == u'g' or LA19 == u'h' or LA19 == u'i' or LA19 == u'j' or LA19 == u'k' or LA19 == u'l' or LA19 == u'm' or LA19 == u'n' or LA19 == u'o' or LA19 == u'p' or LA19 == u'q' or LA19 == u'r' or LA19 == u's' or LA19 == u't' or LA19 == u'u' or LA19 == u'v' or LA19 == u'w' or LA19 == u'x' or LA19 == u'y' or LA19 == u'z': - alt19 = 2 - elif LA19 == u'0' or LA19 == u'1' or LA19 == u'2' or LA19 == u'3' or LA19 == u'4' or LA19 == u'5' or LA19 == u'6' or LA19 == u'7' or LA19 == u'8' or LA19 == u'9': - alt19 = 3 - elif LA19 == u'_': - alt19 = 4 - elif LA19 == u'^': - alt19 = 5 - elif LA19 == u'{': - alt19 = 6 - elif LA19 == u'}': - alt19 = 7 - elif LA19 == u'-': - alt19 = 8 - - if alt19 == 1: - # FMFpython.g:108:29: '\\\\' - self.match(u'\\') - if self.failed: - return - - - elif alt19 == 2: - # FMFpython.g:108:36: LETTERS - self.mLETTERS() - if self.failed: - return - - - elif alt19 == 3: - # FMFpython.g:108:46: DIGITS - self.mDIGITS() - if self.failed: - return - - - elif alt19 == 4: - # FMFpython.g:108:55: UNDERSCORE - self.mUNDERSCORE() - if self.failed: - return - - - elif alt19 == 5: - # FMFpython.g:108:68: HAT - self.mHAT() - if self.failed: - return - - - elif alt19 == 6: - # FMFpython.g:108:74: LCURLY - self.mLCURLY() - if self.failed: - return - - - elif alt19 == 7: - # FMFpython.g:108:83: RCURLY - self.mRCURLY() - if self.failed: - return - - - elif alt19 == 8: - # FMFpython.g:108:92: MINUS - self.mMINUS() - if self.failed: - return - - - else: - break #loop19 - - - - - - - finally: - - pass - - # $ANTLR end RWORD - - - - # $ANTLR start WORD - def mWORD(self, ): - - try: - self.type = WORD - - # FMFpython.g:111:9: ( RWORD | LESSTHAN RWORD GREATERTHAN ) - alt20 = 2 - LA20_0 = self.input.LA(1) - - if ((u'A' <= LA20_0 <= u'Z') or LA20_0 == u'\\' or (u'a' <= LA20_0 <= u'z')) : - alt20 = 1 - elif (LA20_0 == u'<') : - alt20 = 2 - else: - if self.backtracking > 0: - self.failed = True - return - - nvae = NoViableAltException("111:1: WORD : ( RWORD | LESSTHAN RWORD GREATERTHAN );", 20, 0, self.input) - - raise nvae - - if alt20 == 1: - # FMFpython.g:111:11: RWORD - self.mRWORD() - if self.failed: - return - - - elif alt20 == 2: - # FMFpython.g:112:11: LESSTHAN RWORD GREATERTHAN - self.mLESSTHAN() - if self.failed: - return - self.mRWORD() - if self.failed: - return - self.mGREATERTHAN() - if self.failed: - return - - - - finally: - - pass - - # $ANTLR end WORD - - - - # $ANTLR start PUNCTUATION - def mPUNCTUATION(self, ): - - try: - self.type = PUNCTUATION - - # FMFpython.g:116:9: ( '.' | ',' | ';' ) - # FMFpython.g: - if self.input.LA(1) == u',' or self.input.LA(1) == u'.' or self.input.LA(1) == u';': - self.input.consume(); - self.failed = False - - else: - if self.backtracking > 0: - self.failed = True - return - - mse = MismatchedSetException(None, self.input) - self.recover(mse) - raise mse - - - - - - - finally: - - pass - - # $ANTLR end PUNCTUATION - - - - # $ANTLR start LITERAL - def mLITERAL(self, ): - - try: - self.type = LITERAL - - # FMFpython.g:118:9: ( '\"' ( ESC | ~ ( '\\\\' | '\\n' | '\"' ) )* '\"' | '\\'' ( ESC | ~ ( '\\\\' | '\\n' | '\\'' ) )* '\\'' ) - alt23 = 2 - LA23_0 = self.input.LA(1) - - if (LA23_0 == u'"') : - alt23 = 1 - elif (LA23_0 == u'\'') : - alt23 = 2 - else: - if self.backtracking > 0: - self.failed = True - return - - nvae = NoViableAltException("118:1: LITERAL : ( '\"' ( ESC | ~ ( '\\\\' | '\\n' | '\"' ) )* '\"' | '\\'' ( ESC | ~ ( '\\\\' | '\\n' | '\\'' ) )* '\\'' );", 23, 0, self.input) - - raise nvae - - if alt23 == 1: - # FMFpython.g:118:11: '\"' ( ESC | ~ ( '\\\\' | '\\n' | '\"' ) )* '\"' - self.match(u'"') - if self.failed: - return - # FMFpython.g:118:15: ( ESC | ~ ( '\\\\' | '\\n' | '\"' ) )* - while True: #loop21 - alt21 = 3 - LA21_0 = self.input.LA(1) - - if (LA21_0 == u'\\') : - alt21 = 1 - elif ((u'\u0000' <= LA21_0 <= u'\t') or (u'\u000B' <= LA21_0 <= u'!') or (u'#' <= LA21_0 <= u'[') or (u']' <= LA21_0 <= u'\uFFFE')) : - alt21 = 2 - - - if alt21 == 1: - # FMFpython.g:118:16: ESC - self.mESC() - if self.failed: - return - - - elif alt21 == 2: - # FMFpython.g:118:20: ~ ( '\\\\' | '\\n' | '\"' ) - if (u'\u0000' <= self.input.LA(1) <= u'\t') or (u'\u000B' <= self.input.LA(1) <= u'!') or (u'#' <= self.input.LA(1) <= u'[') or (u']' <= self.input.LA(1) <= u'\uFFFE'): - self.input.consume(); - ... [truncated message content] |
From: <li...@us...> - 2008-11-11 11:17:58
|
Revision: 575 http://pyphant.svn.sourceforge.net/pyphant/?rev=575&view=rev Author: liehr Date: 2008-11-11 11:17:53 +0000 (Tue, 11 Nov 2008) Log Message: ----------- Added currency support to PhysicalQuantities. Modified Paths: -------------- trunk/src/pyphant/pyphant/quantities/PhysicalQuantities.py Removed Paths: ------------- trunk/src/pyphant/pyphant/quantities/LICENCE Deleted: trunk/src/pyphant/pyphant/quantities/LICENCE =================================================================== --- trunk/src/pyphant/pyphant/quantities/LICENCE 2008-11-11 11:17:30 UTC (rev 574) +++ trunk/src/pyphant/pyphant/quantities/LICENCE 2008-11-11 11:17:53 UTC (rev 575) @@ -1,519 +0,0 @@ - -CONTRAT DE LICENCE DE LOGICIEL LIBRE CeCILL-B - - - Avertissement - -Ce contrat est une licence de logiciel libre issue d'une concertation -entre ses auteurs afin que le respect de deux grands principes pr\xE9side \xE0 -sa r\xE9daction: - - * d'une part, le respect des principes de diffusion des logiciels - libres: acc\xE8s au code source, droits \xE9tendus conf\xE9r\xE9s aux - utilisateurs, - * d'autre part, la d\xE9signation d'un droit applicable, le droit - fran\xE7ais, auquel elle est conforme, tant au regard du droit de la - responsabilit\xE9 civile que du droit de la propri\xE9t\xE9 intellectuelle - et de la protection qu'il offre aux auteurs et titulaires des - droits patrimoniaux sur un logiciel. - -Les auteurs de la licence CeCILL-B (pour Ce[a] C[nrs] I[nria] L[ogiciel] -L[ibre]) sont: - -Commissariat \xE0 l'Energie Atomique - CEA, \xE9tablissement public de -recherche \xE0 caract\xE8re scientifique, technique et industriel, dont le -si\xE8ge est situ\xE9 25 rue Leblanc, immeuble Le Ponant D, 75015 Paris. - -Centre National de la Recherche Scientifique - CNRS, \xE9tablissement -public \xE0 caract\xE8re scientifique et technologique, dont le si\xE8ge est -situ\xE9 3 rue Michel-Ange, 75794 Paris cedex 16. - -Institut National de Recherche en Informatique et en Automatique - -INRIA, \xE9tablissement public \xE0 caract\xE8re scientifique et technologique, -dont le si\xE8ge est situ\xE9 Domaine de Voluceau, Rocquencourt, BP 105, 78153 -Le Chesnay cedex. - - - Pr\xE9ambule - -Ce contrat est une licence de logiciel libre dont l'objectif est de -conf\xE9rer aux utilisateurs une tr\xE8s large libert\xE9 de modification et de -redistribution du logiciel r\xE9gi par cette licence. - -L'exercice de cette libert\xE9 est assorti d'une obligation forte de -citation \xE0 la charge de ceux qui distribueraient un logiciel incorporant -un logiciel r\xE9gi par la pr\xE9sente licence afin d'assurer que les -contributions de tous soient correctement identifi\xE9es et reconnues. - -L'accessibilit\xE9 au code source et les droits de copie, de modification -et de redistribution qui d\xE9coulent de ce contrat ont pour contrepartie -de n'offrir aux utilisateurs qu'une garantie limit\xE9e et de ne faire -peser sur l'auteur du logiciel, le titulaire des droits patrimoniaux et -les conc\xE9dants successifs qu'une responsabilit\xE9 restreinte. - -A cet \xE9gard l'attention de l'utilisateur est attir\xE9e sur les risques -associ\xE9s au chargement, \xE0 l'utilisation, \xE0 la modification et/ou au -d\xE9veloppement et \xE0 la reproduction du logiciel par l'utilisateur \xE9tant -donn\xE9 sa sp\xE9cificit\xE9 de logiciel libre, qui peut le rendre complexe \xE0 -manipuler et qui le r\xE9serve donc \xE0 des d\xE9veloppeurs ou des -professionnels avertis poss\xE9dant des connaissances informatiques -approfondies. Les utilisateurs sont donc invit\xE9s \xE0 charger et tester -l'ad\xE9quation du logiciel \xE0 leurs besoins dans des conditions permettant -d'assurer la s\xE9curit\xE9 de leurs syst\xE8mes et/ou de leurs donn\xE9es et, plus -g\xE9n\xE9ralement, \xE0 l'utiliser et l'exploiter dans les m\xEAmes conditions de -s\xE9curit\xE9. Ce contrat peut \xEAtre reproduit et diffus\xE9 librement, sous -r\xE9serve de le conserver en l'\xE9tat, sans ajout ni suppression de clauses. - -Ce contrat est susceptible de s'appliquer \xE0 tout logiciel dont le -titulaire des droits patrimoniaux d\xE9cide de soumettre l'exploitation aux -dispositions qu'il contient. - - - Article 1 - DEFINITIONS - -Dans ce contrat, les termes suivants, lorsqu'ils seront \xE9crits avec une -lettre capitale, auront la signification suivante: - -Contrat: d\xE9signe le pr\xE9sent contrat de licence, ses \xE9ventuelles versions -post\xE9rieures et annexes. - -Logiciel: d\xE9signe le logiciel sous sa forme de Code Objet et/ou de Code -Source et le cas \xE9ch\xE9ant sa documentation, dans leur \xE9tat au moment de -l'acceptation du Contrat par le Licenci\xE9. - -Logiciel Initial: d\xE9signe le Logiciel sous sa forme de Code Source et -\xE9ventuellement de Code Objet et le cas \xE9ch\xE9ant sa documentation, dans -leur \xE9tat au moment de leur premi\xE8re diffusion sous les termes du Contrat. - -Logiciel Modifi\xE9: d\xE9signe le Logiciel modifi\xE9 par au moins une -Contribution. - -Code Source: d\xE9signe l'ensemble des instructions et des lignes de -programme du Logiciel et auquel l'acc\xE8s est n\xE9cessaire en vue de -modifier le Logiciel. - -Code Objet: d\xE9signe les fichiers binaires issus de la compilation du -Code Source. - -Titulaire: d\xE9signe le ou les d\xE9tenteurs des droits patrimoniaux d'auteur -sur le Logiciel Initial. - -Licenci\xE9: d\xE9signe le ou les utilisateurs du Logiciel ayant accept\xE9 le -Contrat. - -Contributeur: d\xE9signe le Licenci\xE9 auteur d'au moins une Contribution. - -Conc\xE9dant: d\xE9signe le Titulaire ou toute personne physique ou morale -distribuant le Logiciel sous le Contrat. - -Contribution: d\xE9signe l'ensemble des modifications, corrections, -traductions, adaptations et/ou nouvelles fonctionnalit\xE9s int\xE9gr\xE9es dans -le Logiciel par tout Contributeur, ainsi que tout Module Interne. - -Module: d\xE9signe un ensemble de fichiers sources y compris leur -documentation qui permet de r\xE9aliser des fonctionnalit\xE9s ou services -suppl\xE9mentaires \xE0 ceux fournis par le Logiciel. - -Module Externe: d\xE9signe tout Module, non d\xE9riv\xE9 du Logiciel, tel que ce -Module et le Logiciel s'ex\xE9cutent dans des espaces d'adressage -diff\xE9rents, l'un appelant l'autre au moment de leur ex\xE9cution. - -Module Interne: d\xE9signe tout Module li\xE9 au Logiciel de telle sorte -qu'ils s'ex\xE9cutent dans le m\xEAme espace d'adressage. - -Parties: d\xE9signe collectivement le Licenci\xE9 et le Conc\xE9dant. - -Ces termes s'entendent au singulier comme au pluriel. - - - Article 2 - OBJET - -Le Contrat a pour objet la concession par le Conc\xE9dant au Licenci\xE9 d'une -licence non exclusive, cessible et mondiale du Logiciel telle que -d\xE9finie ci-apr\xE8s \xE0 l'article 5 pour toute la dur\xE9e de protection des droits -portant sur ce Logiciel. - - - Article 3 - ACCEPTATION - -3.1 L'acceptation par le Licenci\xE9 des termes du Contrat est r\xE9put\xE9e -acquise du fait du premier des faits suivants: - - * (i) le chargement du Logiciel par tout moyen notamment par - t\xE9l\xE9chargement \xE0 partir d'un serveur distant ou par chargement \xE0 - partir d'un support physique; - * (ii) le premier exercice par le Licenci\xE9 de l'un quelconque des - droits conc\xE9d\xE9s par le Contrat. - -3.2 Un exemplaire du Contrat, contenant notamment un avertissement -relatif aux sp\xE9cificit\xE9s du Logiciel, \xE0 la restriction de garantie et \xE0 -la limitation \xE0 un usage par des utilisateurs exp\xE9riment\xE9s a \xE9t\xE9 mis \xE0 -disposition du Licenci\xE9 pr\xE9alablement \xE0 son acceptation telle que -d\xE9finie \xE0 l'article 3.1 ci dessus et le Licenci\xE9 reconna\xEEt en avoir pris -connaissance. - - - Article 4 - ENTREE EN VIGUEUR ET DUREE - - - 4.1 ENTREE EN VIGUEUR - -Le Contrat entre en vigueur \xE0 la date de son acceptation par le Licenci\xE9 -telle que d\xE9finie en 3.1. - - - 4.2 DUREE - -Le Contrat produira ses effets pendant toute la dur\xE9e l\xE9gale de -protection des droits patrimoniaux portant sur le Logiciel. - - - Article 5 - ETENDUE DES DROITS CONCEDES - -Le Conc\xE9dant conc\xE8de au Licenci\xE9, qui accepte, les droits suivants sur -le Logiciel pour toutes destinations et pour la dur\xE9e du Contrat dans -les conditions ci-apr\xE8s d\xE9taill\xE9es. - -Par ailleurs, si le Conc\xE9dant d\xE9tient ou venait \xE0 d\xE9tenir un ou -plusieurs brevets d'invention prot\xE9geant tout ou partie des -fonctionnalit\xE9s du Logiciel ou de ses composants, il s'engage \xE0 ne pas -opposer les \xE9ventuels droits conf\xE9r\xE9s par ces brevets aux Licenci\xE9s -successifs qui utiliseraient, exploiteraient ou modifieraient le -Logiciel. En cas de cession de ces brevets, le Conc\xE9dant s'engage \xE0 -faire reprendre les obligations du pr\xE9sent alin\xE9a aux cessionnaires. - - - 5.1 DROIT D'UTILISATION - -Le Licenci\xE9 est autoris\xE9 \xE0 utiliser le Logiciel, sans restriction quant -aux domaines d'application, \xE9tant ci-apr\xE8s pr\xE9cis\xE9 que cela comporte: - - 1. la reproduction permanente ou provisoire du Logiciel en tout ou - partie par tout moyen et sous toute forme. - - 2. le chargement, l'affichage, l'ex\xE9cution, ou le stockage du - Logiciel sur tout support. - - 3. la possibilit\xE9 d'en observer, d'en \xE9tudier, ou d'en tester le - fonctionnement afin de d\xE9terminer les id\xE9es et principes qui sont - \xE0 la base de n'importe quel \xE9l\xE9ment de ce Logiciel; et ceci, - lorsque le Licenci\xE9 effectue toute op\xE9ration de chargement, - d'affichage, d'ex\xE9cution, de transmission ou de stockage du - Logiciel qu'il est en droit d'effectuer en vertu du Contrat. - - - 5.2 DROIT D'APPORTER DES CONTRIBUTIONS - -Le droit d'apporter des Contributions comporte le droit de traduire, -d'adapter, d'arranger ou d'apporter toute autre modification au Logiciel -et le droit de reproduire le logiciel en r\xE9sultant. - -Le Licenci\xE9 est autoris\xE9 \xE0 apporter toute Contribution au Logiciel sous -r\xE9serve de mentionner, de fa\xE7on explicite, son nom en tant qu'auteur de -cette Contribution et la date de cr\xE9ation de celle-ci. - - - 5.3 DROIT DE DISTRIBUTION - -Le droit de distribution comporte notamment le droit de diffuser, de -transmettre et de communiquer le Logiciel au public sur tout support et -par tout moyen ainsi que le droit de mettre sur le march\xE9 \xE0 titre -on\xE9reux ou gratuit, un ou des exemplaires du Logiciel par tout proc\xE9d\xE9. - -Le Licenci\xE9 est autoris\xE9 \xE0 distribuer des copies du Logiciel, modifi\xE9 ou -non, \xE0 des tiers dans les conditions ci-apr\xE8s d\xE9taill\xE9es. - - - 5.3.1 DISTRIBUTION DU LOGICIEL SANS MODIFICATION - -Le Licenci\xE9 est autoris\xE9 \xE0 distribuer des copies conformes du Logiciel, -sous forme de Code Source ou de Code Objet, \xE0 condition que cette -distribution respecte les dispositions du Contrat dans leur totalit\xE9 et -soit accompagn\xE9e: - - 1. d'un exemplaire du Contrat, - - 2. d'un avertissement relatif \xE0 la restriction de garantie et de - responsabilit\xE9 du Conc\xE9dant telle que pr\xE9vue aux articles 8 - et 9, - -et que, dans le cas o\xF9 seul le Code Objet du Logiciel est redistribu\xE9, -le Licenci\xE9 permette un acc\xE8s effectif au Code Source complet du -Logiciel pendant au moins toute la dur\xE9e de sa distribution du Logiciel, -\xE9tant entendu que le co\xFBt additionnel d'acquisition du Code Source ne -devra pas exc\xE9der le simple co\xFBt de transfert des donn\xE9es. - - - 5.3.2 DISTRIBUTION DU LOGICIEL MODIFIE - -Lorsque le Licenci\xE9 apporte une Contribution au Logiciel, le Logiciel -Modifi\xE9 peut \xEAtre distribu\xE9 sous un contrat de licence autre que le -pr\xE9sent Contrat sous r\xE9serve du respect des dispositions de l'article -5.3.4. - - - 5.3.3 DISTRIBUTION DES MODULES EXTERNES - -Lorsque le Licenci\xE9 a d\xE9velopp\xE9 un Module Externe les conditions du -Contrat ne s'appliquent pas \xE0 ce Module Externe, qui peut \xEAtre distribu\xE9 -sous un contrat de licence diff\xE9rent. - - - 5.3.4 CITATIONS - -Le Licenci\xE9 qui distribue un Logiciel Modifi\xE9 s'engage express\xE9ment: - - 1. \xE0 indiquer dans sa documentation qu'il a \xE9t\xE9 r\xE9alis\xE9 \xE0 partir du - Logiciel r\xE9gi par le Contrat, en reproduisant les mentions de - propri\xE9t\xE9 intellectuelle du Logiciel, - - 2. \xE0 faire en sorte que l'utilisation du Logiciel, ses mentions de - propri\xE9t\xE9 intellectuelle et le fait qu'il est r\xE9gi par le Contrat - soient indiqu\xE9s dans un texte facilement accessible depuis - l'interface du Logiciel Modifi\xE9, - - 3. \xE0 mentionner, sur un site Web librement accessible d\xE9crivant le - Logiciel Modifi\xE9, et pendant au moins toute la dur\xE9e de sa - distribution, qu'il a \xE9t\xE9 r\xE9alis\xE9 \xE0 partir du Logiciel r\xE9gi par le - Contrat, en reproduisant les mentions de propri\xE9t\xE9 intellectuelle - du Logiciel, - - 4. lorsqu'il le distribue \xE0 un tiers susceptible de distribuer - lui-m\xEAme un Logiciel Modifi\xE9, sans avoir \xE0 en distribuer le code - source, \xE0 faire ses meilleurs efforts pour que les obligations du - pr\xE9sent article 5.3.4 soient reprises par le dit tiers. - -Lorsque le Logiciel modifi\xE9 ou non est distribu\xE9 avec un Module Externe -qui a \xE9t\xE9 con\xE7u pour l'utiliser, le Licenci\xE9 doit soumettre le dit -Module Externe aux obligations pr\xE9c\xE9dentes. - - - 5.3.5 COMPATIBILITE AVEC LES LICENCES CeCILL et CeCILL-C - -Lorsqu'un Logiciel Modifi\xE9 contient une Contribution soumise au contrat -de licence CeCILL, les stipulations pr\xE9vues \xE0 l'article 5.3.4 sont -facultatives. - -Un Logiciel Modifi\xE9 peut \xEAtre distribu\xE9 sous le contrat de licence -CeCILL-C. Les stipulations pr\xE9vues \xE0 l'article 5.3.4 sont alors -facultatives. - - - Article 6 - PROPRIETE INTELLECTUELLE - - - 6.1 SUR LE LOGICIEL INITIAL - -Le Titulaire est d\xE9tenteur des droits patrimoniaux sur le Logiciel -Initial. Toute utilisation du Logiciel Initial est soumise au respect -des conditions dans lesquelles le Titulaire a choisi de diffuser son -oeuvre et nul autre n'a la facult\xE9 de modifier les conditions de -diffusion de ce Logiciel Initial. - -Le Titulaire s'engage \xE0 ce que le Logiciel Initial reste au moins r\xE9gi -par le Contrat et ce, pour la dur\xE9e vis\xE9e \xE0 l'article 4.2. - - - 6.2 SUR LES CONTRIBUTIONS - -Le Licenci\xE9 qui a d\xE9velopp\xE9 une Contribution est titulaire sur celle-ci -des droits de propri\xE9t\xE9 intellectuelle dans les conditions d\xE9finies par -la l\xE9gislation applicable. - - - 6.3 SUR LES MODULES EXTERNES - -Le Licenci\xE9 qui a d\xE9velopp\xE9 un Module Externe est titulaire sur celui-ci -des droits de propri\xE9t\xE9 intellectuelle dans les conditions d\xE9finies par -la l\xE9gislation applicable et reste libre du choix du contrat r\xE9gissant -sa diffusion. - - - 6.4 DISPOSITIONS COMMUNES - -Le Licenci\xE9 s'engage express\xE9ment: - - 1. \xE0 ne pas supprimer ou modifier de quelque mani\xE8re que ce soit les - mentions de propri\xE9t\xE9 intellectuelle appos\xE9es sur le Logiciel; - - 2. \xE0 reproduire \xE0 l'identique lesdites mentions de propri\xE9t\xE9 - intellectuelle sur les copies du Logiciel modifi\xE9 ou non. - -Le Licenci\xE9 s'engage \xE0 ne pas porter atteinte, directement ou -indirectement, aux droits de propri\xE9t\xE9 intellectuelle du Titulaire et/ou -des Contributeurs sur le Logiciel et \xE0 prendre, le cas \xE9ch\xE9ant, \xE0 -l'\xE9gard de son personnel toutes les mesures n\xE9cessaires pour assurer le -respect des dits droits de propri\xE9t\xE9 intellectuelle du Titulaire et/ou -des Contributeurs. - - - Article 7 - SERVICES ASSOCIES - -7.1 Le Contrat n'oblige en aucun cas le Conc\xE9dant \xE0 la r\xE9alisation de -prestations d'assistance technique ou de maintenance du Logiciel. - -Cependant le Conc\xE9dant reste libre de proposer ce type de services. Les -termes et conditions d'une telle assistance technique et/ou d'une telle -maintenance seront alors d\xE9termin\xE9s dans un acte s\xE9par\xE9. Ces actes de -maintenance et/ou assistance technique n'engageront que la seule -responsabilit\xE9 du Conc\xE9dant qui les propose. - -7.2 De m\xEAme, tout Conc\xE9dant est libre de proposer, sous sa seule -responsabilit\xE9, \xE0 ses licenci\xE9s une garantie, qui n'engagera que lui, -lors de la redistribution du Logiciel et/ou du Logiciel Modifi\xE9 et ce, -dans les conditions qu'il souhaite. Cette garantie et les modalit\xE9s -financi\xE8res de son application feront l'objet d'un acte s\xE9par\xE9 entre le -Conc\xE9dant et le Licenci\xE9. - - - Article 8 - RESPONSABILITE - -8.1 Sous r\xE9serve des dispositions de l'article 8.2, le Licenci\xE9 a la -facult\xE9, sous r\xE9serve de prouver la faute du Conc\xE9dant concern\xE9, de -solliciter la r\xE9paration du pr\xE9judice direct qu'il subirait du fait du -Logiciel et dont il apportera la preuve. - -8.2 La responsabilit\xE9 du Conc\xE9dant est limit\xE9e aux engagements pris en -application du Contrat et ne saurait \xEAtre engag\xE9e en raison notamment: -(i) des dommages dus \xE0 l'inex\xE9cution, totale ou partielle, de ses -obligations par le Licenci\xE9, (ii) des dommages directs ou indirects -d\xE9coulant de l'utilisation ou des performances du Logiciel subis par le -Licenci\xE9 et (iii) plus g\xE9n\xE9ralement d'un quelconque dommage indirect. En -particulier, les Parties conviennent express\xE9ment que tout pr\xE9judice -financier ou commercial (par exemple perte de donn\xE9es, perte de -b\xE9n\xE9fices, perte d'exploitation, perte de client\xE8le ou de commandes, -manque \xE0 gagner, trouble commercial quelconque) ou toute action dirig\xE9e -contre le Licenci\xE9 par un tiers, constitue un dommage indirect et -n'ouvre pas droit \xE0 r\xE9paration par le Conc\xE9dant. - - - Article 9 - GARANTIE - -9.1 Le Licenci\xE9 reconna\xEEt que l'\xE9tat actuel des connaissances -scientifiques et techniques au moment de la mise en circulation du -Logiciel ne permet pas d'en tester et d'en v\xE9rifier toutes les -utilisations ni de d\xE9tecter l'existence d'\xE9ventuels d\xE9fauts. L'attention -du Licenci\xE9 a \xE9t\xE9 attir\xE9e sur ce point sur les risques associ\xE9s au -chargement, \xE0 l'utilisation, la modification et/ou au d\xE9veloppement et \xE0 -la reproduction du Logiciel qui sont r\xE9serv\xE9s \xE0 des utilisateurs avertis. - -Il rel\xE8ve de la responsabilit\xE9 du Licenci\xE9 de contr\xF4ler, par tous -moyens, l'ad\xE9quation du produit \xE0 ses besoins, son bon fonctionnement et -de s'assurer qu'il ne causera pas de dommages aux personnes et aux biens. - -9.2 Le Conc\xE9dant d\xE9clare de bonne foi \xEAtre en droit de conc\xE9der -l'ensemble des droits attach\xE9s au Logiciel (comprenant notamment les -droits vis\xE9s \xE0 l'article 5). - -9.3 Le Licenci\xE9 reconna\xEEt que le Logiciel est fourni "en l'\xE9tat" par le -Conc\xE9dant sans autre garantie, expresse ou tacite, que celle pr\xE9vue \xE0 -l'article 9.2 et notamment sans aucune garantie sur sa valeur commerciale, -son caract\xE8re s\xE9curis\xE9, innovant ou pertinent. - -En particulier, le Conc\xE9dant ne garantit pas que le Logiciel est exempt -d'erreur, qu'il fonctionnera sans interruption, qu'il sera compatible -avec l'\xE9quipement du Licenci\xE9 et sa configuration logicielle ni qu'il -remplira les besoins du Licenci\xE9. - -9.4 Le Conc\xE9dant ne garantit pas, de mani\xE8re expresse ou tacite, que le -Logiciel ne porte pas atteinte \xE0 un quelconque droit de propri\xE9t\xE9 -intellectuelle d'un tiers portant sur un brevet, un logiciel ou sur tout -autre droit de propri\xE9t\xE9. Ainsi, le Conc\xE9dant exclut toute garantie au -profit du Licenci\xE9 contre les actions en contrefa\xE7on qui pourraient \xEAtre -diligent\xE9es au titre de l'utilisation, de la modification, et de la -redistribution du Logiciel. N\xE9anmoins, si de telles actions sont -exerc\xE9es contre le Licenci\xE9, le Conc\xE9dant lui apportera son aide -technique et juridique pour sa d\xE9fense. Cette aide technique et -juridique est d\xE9termin\xE9e au cas par cas entre le Conc\xE9dant concern\xE9 et -le Licenci\xE9 dans le cadre d'un protocole d'accord. Le Conc\xE9dant d\xE9gage -toute responsabilit\xE9 quant \xE0 l'utilisation de la d\xE9nomination du -Logiciel par le Licenci\xE9. Aucune garantie n'est apport\xE9e quant \xE0 -l'existence de droits ant\xE9rieurs sur le nom du Logiciel et sur -l'existence d'une marque. - - - Article 10 - RESILIATION - -10.1 En cas de manquement par le Licenci\xE9 aux obligations mises \xE0 sa -charge par le Contrat, le Conc\xE9dant pourra r\xE9silier de plein droit le -Contrat trente (30) jours apr\xE8s notification adress\xE9e au Licenci\xE9 et -rest\xE9e sans effet. - -10.2 Le Licenci\xE9 dont le Contrat est r\xE9sili\xE9 n'est plus autoris\xE9 \xE0 -utiliser, modifier ou distribuer le Logiciel. Cependant, toutes les -licences qu'il aura conc\xE9d\xE9es ant\xE9rieurement \xE0 la r\xE9siliation du Contrat -resteront valides sous r\xE9serve qu'elles aient \xE9t\xE9 effectu\xE9es en -conformit\xE9 avec le Contrat. - - - Article 11 - DISPOSITIONS DIVERSES - - - 11.1 CAUSE EXTERIEURE - -Aucune des Parties ne sera responsable d'un retard ou d'une d\xE9faillance -d'ex\xE9cution du Contrat qui serait d\xFB \xE0 un cas de force majeure, un cas -fortuit ou une cause ext\xE9rieure, telle que, notamment, le mauvais -fonctionnement ou les interruptions du r\xE9seau \xE9lectrique ou de -t\xE9l\xE9communication, la paralysie du r\xE9seau li\xE9e \xE0 une attaque -informatique, l'intervention des autorit\xE9s gouvernementales, les -catastrophes naturelles, les d\xE9g\xE2ts des eaux, les tremblements de terre, -le feu, les explosions, les gr\xE8ves et les conflits sociaux, l'\xE9tat de -guerre... - -11.2 Le fait, par l'une ou l'autre des Parties, d'omettre en une ou -plusieurs occasions de se pr\xE9valoir d'une ou plusieurs dispositions du -Contrat, ne pourra en aucun cas impliquer renonciation par la Partie -int\xE9ress\xE9e \xE0 s'en pr\xE9valoir ult\xE9rieurement. - -11.3 Le Contrat annule et remplace toute convention ant\xE9rieure, \xE9crite -ou orale, entre les Parties sur le m\xEAme objet et constitue l'accord -entier entre les Parties sur cet objet. Aucune addition ou modification -aux termes du Contrat n'aura d'effet \xE0 l'\xE9gard des Parties \xE0 moins -d'\xEAtre faite par \xE9crit et sign\xE9e par leurs repr\xE9sentants d\xFBment habilit\xE9s. - -11.4 Dans l'hypoth\xE8se o\xF9 une ou plusieurs des dispositions du Contrat -s'av\xE8rerait contraire \xE0 une loi ou \xE0 un texte applicable, existants ou -futurs, cette loi ou ce texte pr\xE9vaudrait, et les Parties feraient les -amendements n\xE9cessaires pour se conformer \xE0 cette loi ou \xE0 ce texte. -Toutes les autres dispositions resteront en vigueur. De m\xEAme, la -nullit\xE9, pour quelque raison que ce soit, d'une des dispositions du -Contrat ne saurait entra\xEEner la nullit\xE9 de l'ensemble du Contrat. - - - 11.5 LANGUE - -Le Contrat est r\xE9dig\xE9 en langue fran\xE7aise et en langue anglaise, ces -deux versions faisant \xE9galement foi. - - - Article 12 - NOUVELLES VERSIONS DU CONTRAT - -12.1 Toute personne est autoris\xE9e \xE0 copier et distribuer des copies de -ce Contrat. - -12.2 Afin d'en pr\xE9server la coh\xE9rence, le texte du Contrat est prot\xE9g\xE9 -et ne peut \xEAtre modifi\xE9 que par les auteurs de la licence, lesquels se -r\xE9servent le droit de publier p\xE9riodiquement des mises \xE0 jour ou de -nouvelles versions du Contrat, qui poss\xE9deront chacune un num\xE9ro -distinct. Ces versions ult\xE9rieures seront susceptibles de prendre en -compte de nouvelles probl\xE9matiques rencontr\xE9es par les logiciels libres. - -12.3 Tout Logiciel diffus\xE9 sous une version donn\xE9e du Contrat ne pourra -faire l'objet d'une diffusion ult\xE9rieure que sous la m\xEAme version du -Contrat ou une version post\xE9rieure. - - - Article 13 - LOI APPLICABLE ET COMPETENCE TERRITORIALE - -13.1 Le Contrat est r\xE9gi par la loi fran\xE7aise. Les Parties conviennent -de tenter de r\xE9gler \xE0 l'amiable les diff\xE9rends ou litiges qui -viendraient \xE0 se produire par suite ou \xE0 l'occasion du Contrat. - -13.2 A d\xE9faut d'accord amiable dans un d\xE9lai de deux (2) mois \xE0 compter -de leur survenance et sauf situation relevant d'une proc\xE9dure d'urgence, -les diff\xE9rends ou litiges seront port\xE9s par la Partie la plus diligente -devant les Tribunaux comp\xE9tents de Paris. - - -Version 1.0 du 2006-09-05. Modified: trunk/src/pyphant/pyphant/quantities/PhysicalQuantities.py =================================================================== --- trunk/src/pyphant/pyphant/quantities/PhysicalQuantities.py 2008-11-11 11:17:30 UTC (rev 574) +++ trunk/src/pyphant/pyphant/quantities/PhysicalQuantities.py 2008-11-11 11:17:53 UTC (rev 575) @@ -1,14 +1,41 @@ -# Physical quantities with units +# -*- coding: utf-8 -*- + +# Copyright (c) 1998-2007, Konrad Hinsen <hi...@cn...> +# Copyright (c) 2008, Rectorate of the University of Freiburg +# All rights reserved. # -# Written by Konrad Hinsen <hi...@cn...> -# with contributions from Greg Ward -# merged into Pyphant by Andreas W. Liehr -# last revision: 2008-11-10 +# 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. """ -Physical quantities with units. +Quantities with units +based on the module Scientific.Physics.PhysicalQuantities +written by Conrad Hinsen with contributions from Greg Ward. + This module provides a data type that represents a physical quantity together with its unit. It is possible to add and subtract these quantities if the units are compatible, and @@ -639,18 +666,19 @@ # SI unit definitions -_base_names = ['m', 'kg', 's', 'A', 'K', 'mol', 'cd', 'rad', 'sr'] +_base_names = ['m', 'kg', 's', 'A', 'K', 'mol', 'cd', 'rad', 'sr','EUR'] -_base_units = [('m', PhysicalUnit('m', 1., [1,0,0,0,0,0,0,0,0])), - ('g', PhysicalUnit('g', 0.001, [0,1,0,0,0,0,0,0,0])), - ('s', PhysicalUnit('s', 1., [0,0,1,0,0,0,0,0,0])), - ('A', PhysicalUnit('A', 1., [0,0,0,1,0,0,0,0,0])), - ('K', PhysicalUnit('K', 1., [0,0,0,0,1,0,0,0,0])), - ('mol', PhysicalUnit('mol', 1., [0,0,0,0,0,1,0,0,0])), - ('cd', PhysicalUnit('cd', 1., [0,0,0,0,0,0,1,0,0])), - ('rad', PhysicalUnit('rad', 1., [0,0,0,0,0,0,0,1,0])), - ('sr', PhysicalUnit('sr', 1., [0,0,0,0,0,0,0,0,1])), - ] +_base_units = [('m', PhysicalUnit('m', 1., [1,0,0,0,0,0,0,0,0,0])), + ('g', PhysicalUnit('g', 0.001, [0,1,0,0,0,0,0,0,0,0])), + ('s', PhysicalUnit('s', 1., [0,0,1,0,0,0,0,0,0,0])), + ('A', PhysicalUnit('A', 1., [0,0,0,1,0,0,0,0,0,0])), + ('K', PhysicalUnit('K', 1., [0,0,0,0,1,0,0,0,0,0])), + ('mol', PhysicalUnit('mol', 1., [0,0,0,0,0,1,0,0,0,0])), + ('cd', PhysicalUnit('cd', 1., [0,0,0,0,0,0,1,0,0,0])), + ('rad', PhysicalUnit('rad', 1., [0,0,0,0,0,0,0,1,0,0])), + ('sr', PhysicalUnit('sr', 1., [0,0,0,0,0,0,0,0,1,0])), + ('EUR', PhysicalUnit('EUR', 1., [0,0,0,0,0,0,0,0,0,1])), + ] _prefixes = [('Y', 1.e24), ('Z', 1.e21), @@ -710,7 +738,7 @@ '\n') -_unit_table['kg'] = PhysicalUnit('kg', 1., [0,1,0,0,0,0,0,0,0]) +_unit_table['kg'] = PhysicalUnit('kg', 1., [0,1,0,0,0,0,0,0,0,0]) _addUnit('Hz', '1/s', 'Hertz') _addUnit('N', 'm*kg/s**2', 'Newton') @@ -853,7 +881,58 @@ 'degree Fahrenheit') del kelvin +_help.append('Old European currencies:') +#Taken from http://www.xe.com/euro.php on 2008-11-05 +_addUnit('ATS', 'EUR/13.7603' ,'Austria, Schilling') +_addUnit('BEF', 'EUR/40.3399' ,'Belgium, Franc') +_addUnit('CYP', 'EUR/0.585274','Cyprus, Pound') +_addUnit('DEM', 'EUR/1.95583' ,'Germany, Deutsche Mark') +_addUnit('ESP', 'EUR/166.386' ,'Spain, Peseta') +_addUnit('FIM', 'EUR/5.94573' ,'Finland, Markka') +_addUnit('FRF', 'EUR/5.94573' ,'France, Franc') +_addUnit('GRD', 'EUR/340.750' ,'Greece, Drachma') +_addUnit('IEP', 'EUR/0.787564','Ireland, Pound') +_addUnit('ITL', 'EUR/1936.27' ,'Italy, Lira') +_addUnit('LUF', 'EUR/40.3399' ,'Luxembourg, Franc') +_addUnit('MTL', 'EUR/0.429300','Malta, Lira') +_addUnit('NLG', 'EUR/2.20371' ,'The Netherlands, Guilder (also called Florin)') +_addUnit('PTE', 'EUR/200.482' ,'Portugal, Escudo') +_addUnit('SIT', 'EUR/239.640' ,'Slovenia, Tolar') +_addUnit('VAL', 'EUR/1936.27' ,'Vatican City, Lira') +#Get daily updated exchange rates +import urllib +from xml.dom import minidom +url = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml" +currencyNames={'USD':'US dollar' , 'JPY':'Japanese yen', + 'BGN':'Bulgarian lev' , 'CZK':'Czech koruna', + 'DKK':'Danish krone' , 'EEK':'Estonian kroon', + 'GBP':'Pound sterling' ,'HUF':'Hungarian forint', + 'LTL':'Lithuanian litas','LVL':'Latvian lats', + 'PLN':'Polish zloty', 'RON':'New Romanian leu', + 'SEK':'Swedish krona', 'SKK':'Slovak koruna', + 'CHF':'Swiss franc', 'ISK':'Icelandic krona', + 'NOK':'Norwegian krone', 'HRK':'Croatian kuna', + 'RUB':'Russian rouble', 'TRY':'New Turkish lira', + 'AUD':'Australian dollar','BRL':'Brasilian real', + 'CAD':'Canadian dollar', 'CNY':'Chinese yuan renminbi', + 'HKD':'Hong Kong dollar','IDR':'Indonesian rupiah', + 'KRW':'South Korean won','MXN':'Mexican peso', + 'MYR':'Malaysian ringgit','NZD':'New Zealand dollar', + 'PHP':'Philippine peso', 'SGD':'Singapore dollar', + 'THB':'Thai baht', 'ZAR':'South African rand'} +try: + doc = minidom.parseString(urllib.urlopen(url).read()) + elements = doc.documentElement.getElementsByTagName('Cube') + for element in elements[2:]: + currency = element.getAttribute('currency').encode('utf8') + _addUnit(currency, + 'EUR/%s' % element.getAttribute('rate').encode('utf8'), + currencyNames[currency]) + print "Added exchange rate of %s for %s." % (elements[1].getAttribute('time'),[i.getAttribute('currency').encode('utf8') for i in elements[2:]]) +except: + print "WARNING: No daily exchange rates available." + def description(): """Return a string describing all available units.""" s = '' # collector for description text @@ -893,3 +972,10 @@ freeze = p('0 degC') print freeze.inUnitsOf ('degF') + + euro = PhysicalQuantity('1 EUR') + print euro.inUnitsOf('DEM') + print euro.inUnitsOf('USD') + + euroSQM = PhysicalQuantity('19.99 EUR/m**2') + print "%s=%s" % (euroSQM,euroSQM.inUnitsOf('EUR/cm**2')) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <li...@us...> - 2008-11-11 11:17:36
|
Revision: 574 http://pyphant.svn.sourceforge.net/pyphant/?rev=574&view=rev Author: liehr Date: 2008-11-11 11:17:30 +0000 (Tue, 11 Nov 2008) Log Message: ----------- Included Konrad Hinsens class NumerDict into the PhysicalQuantities module. Modified Paths: -------------- trunk/src/pyphant/pyphant/quantities/PhysicalQuantities.py Removed Paths: ------------- trunk/src/pyphant/pyphant/quantities/NumberDict.py Deleted: trunk/src/pyphant/pyphant/quantities/NumberDict.py =================================================================== --- trunk/src/pyphant/pyphant/quantities/NumberDict.py 2008-11-11 11:17:02 UTC (rev 573) +++ trunk/src/pyphant/pyphant/quantities/NumberDict.py 2008-11-11 11:17:30 UTC (rev 574) @@ -1,67 +0,0 @@ -# Dictionary containing numbers -# -# These objects are meant to be used like arrays with generalized -# indices. Non-existent elements default to zero. Global operations -# are addition, subtraction, and multiplication/division by a scalar. -# -# Written by Konrad Hinsen <hi...@cn...> -# last revision: 2006-10-16 -# - -""" -Dictionary storing numerical values -""" - -class NumberDict(dict): - - """ - Dictionary storing numerical values - - Constructor: NumberDict() - - An instance of this class acts like an array of number with - generalized (non-integer) indices. A value of zero is assumed - for undefined entries. NumberDict instances support addition, - and subtraction with other NumberDict instances, and multiplication - and division by scalars. - """ - - def __getitem__(self, item): - try: - return dict.__getitem__(self, item) - except KeyError: - return 0 - - def __coerce__(self, other): - if type(other) == type({}): - other = NumberDict(other) - return self, other - - def __add__(self, other): - sum_dict = NumberDict() - for key in self.keys(): - sum_dict[key] = self[key] - for key in other.keys(): - sum_dict[key] = sum_dict[key] + other[key] - return sum_dict - - def __sub__(self, other): - sum_dict = NumberDict() - for key in self.keys(): - sum_dict[key] = self[key] - for key in other.keys(): - sum_dict[key] = sum_dict[key] - other[key] - return sum_dict - - def __mul__(self, other): - new = NumberDict() - for key in self.keys(): - new[key] = other*self[key] - return new - __rmul__ = __mul__ - - def __div__(self, other): - new = NumberDict() - for key in self.keys(): - new[key] = self[key]/other - return new Modified: trunk/src/pyphant/pyphant/quantities/PhysicalQuantities.py =================================================================== --- trunk/src/pyphant/pyphant/quantities/PhysicalQuantities.py 2008-11-11 11:17:02 UTC (rev 573) +++ trunk/src/pyphant/pyphant/quantities/PhysicalQuantities.py 2008-11-11 11:17:30 UTC (rev 574) @@ -26,8 +26,60 @@ table, so use this at your own risk. """ -from pyphant.quantities.NumberDict import NumberDict +class NumberDict(dict): + """ + Dictionary storing numerical values + + Constructor: NumberDict() + + An instance of this class acts like an array of number with + generalized (non-integer) indices. A value of zero is assumed + for undefined entries. NumberDict instances support addition, + and subtraction with other NumberDict instances, and multiplication + and division by scalars. + """ + + def __getitem__(self, item): + try: + return dict.__getitem__(self, item) + except KeyError: + return 0 + + def __coerce__(self, other): + if type(other) == type({}): + other = NumberDict(other) + return self, other + + def __add__(self, other): + sum_dict = NumberDict() + for key in self.keys(): + sum_dict[key] = self[key] + for key in other.keys(): + sum_dict[key] = sum_dict[key] + other[key] + return sum_dict + + def __sub__(self, other): + sum_dict = NumberDict() + for key in self.keys(): + sum_dict[key] = self[key] + for key in other.keys(): + sum_dict[key] = sum_dict[key] - other[key] + return sum_dict + + def __mul__(self, other): + new = NumberDict() + for key in self.keys(): + new[key] = other*self[key] + return new + __rmul__ = __mul__ + + def __div__(self, other): + new = NumberDict() + for key in self.keys(): + new[key] = self[key]/other + return new + import numpy.oldnumeric def int_sum(a, axis=0): return numpy.oldnumeric.add.reduce(a, axis) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <li...@us...> - 2008-11-11 11:17:09
|
Revision: 573 http://pyphant.svn.sourceforge.net/pyphant/?rev=573&view=rev Author: liehr Date: 2008-11-11 11:17:02 +0000 (Tue, 11 Nov 2008) Log Message: ----------- Included CeCILL-B version of Konrad Hinsens PhysicalQuantities modul. Modified Paths: -------------- trunk/src/pyphant/pyphant/core/DataContainer.py trunk/src/pyphant/pyphant/core/FieldContainer.py trunk/src/pyphant/pyphant/core/PyTablesPersister.py trunk/src/pyphant/pyphant/tests/TestDataContainer.py trunk/src/pyphant/pyphant/tests/TestPyTablesPersister.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/DistanceMapper.py trunk/src/workers/ImageProcessing/ImageProcessing/ImageLoaderWorker.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/FMFLoader2.py trunk/src/workers/fmfile/fmfile/FMFpythonTree.py Added Paths: ----------- trunk/src/pyphant/pyphant/quantities/ trunk/src/pyphant/pyphant/quantities/LICENCE trunk/src/pyphant/pyphant/quantities/NumberDict.py trunk/src/pyphant/pyphant/quantities/PhysicalQuantities.py trunk/src/pyphant/pyphant/quantities/__init__.py Modified: trunk/src/pyphant/pyphant/core/DataContainer.py =================================================================== --- trunk/src/pyphant/pyphant/core/DataContainer.py 2008-11-05 09:41:50 UTC (rev 572) +++ trunk/src/pyphant/pyphant/core/DataContainer.py 2008-11-11 11:17:02 UTC (rev 573) @@ -58,7 +58,7 @@ import scipy, copy, md5, threading, numpy, StringIO import os, platform, datetime, socket, urlparse -from Scientific.Physics.PhysicalQuantities import (isPhysicalQuantity, PhysicalQuantity,_prefixes) +from pyphant.quantities.PhysicalQuantities import (isPhysicalQuantity, PhysicalQuantity,_prefixes) import logging Modified: trunk/src/pyphant/pyphant/core/FieldContainer.py =================================================================== --- trunk/src/pyphant/pyphant/core/FieldContainer.py 2008-11-05 09:41:50 UTC (rev 572) +++ trunk/src/pyphant/pyphant/core/FieldContainer.py 2008-11-11 11:17:02 UTC (rev 573) @@ -36,7 +36,7 @@ import scipy, copy, md5, threading, numpy, StringIO import os, platform, datetime, socket, urlparse -from Scientific.Physics.PhysicalQuantities import (isPhysicalQuantity, PhysicalQuantity,_prefixes) +from pyphant.quantities.PhysicalQuantities import (isPhysicalQuantity, PhysicalQuantity,_prefixes) from DataContainer import DataContainer, enc, _logger #Default variables of indices Modified: trunk/src/pyphant/pyphant/core/PyTablesPersister.py =================================================================== --- trunk/src/pyphant/pyphant/core/PyTablesPersister.py 2008-11-05 09:41:50 UTC (rev 572) +++ trunk/src/pyphant/pyphant/core/PyTablesPersister.py 2008-11-11 11:17:02 UTC (rev 573) @@ -65,7 +65,7 @@ import sys from pyphant.core import (CompositeWorker, DataContainer) from tables import StringCol, Col -from Scientific.Physics.PhysicalQuantities import PhysicalQuantity +from pyphant.quantities.PhysicalQuantities import PhysicalQuantity import scipy import logging _logger = logging.getLogger("pyphant") Added: trunk/src/pyphant/pyphant/quantities/LICENCE =================================================================== --- trunk/src/pyphant/pyphant/quantities/LICENCE (rev 0) +++ trunk/src/pyphant/pyphant/quantities/LICENCE 2008-11-11 11:17:02 UTC (rev 573) @@ -0,0 +1,519 @@ + +CONTRAT DE LICENCE DE LOGICIEL LIBRE CeCILL-B + + + Avertissement + +Ce contrat est une licence de logiciel libre issue d'une concertation +entre ses auteurs afin que le respect de deux grands principes pr\xE9side \xE0 +sa r\xE9daction: + + * d'une part, le respect des principes de diffusion des logiciels + libres: acc\xE8s au code source, droits \xE9tendus conf\xE9r\xE9s aux + utilisateurs, + * d'autre part, la d\xE9signation d'un droit applicable, le droit + fran\xE7ais, auquel elle est conforme, tant au regard du droit de la + responsabilit\xE9 civile que du droit de la propri\xE9t\xE9 intellectuelle + et de la protection qu'il offre aux auteurs et titulaires des + droits patrimoniaux sur un logiciel. + +Les auteurs de la licence CeCILL-B (pour Ce[a] C[nrs] I[nria] L[ogiciel] +L[ibre]) sont: + +Commissariat \xE0 l'Energie Atomique - CEA, \xE9tablissement public de +recherche \xE0 caract\xE8re scientifique, technique et industriel, dont le +si\xE8ge est situ\xE9 25 rue Leblanc, immeuble Le Ponant D, 75015 Paris. + +Centre National de la Recherche Scientifique - CNRS, \xE9tablissement +public \xE0 caract\xE8re scientifique et technologique, dont le si\xE8ge est +situ\xE9 3 rue Michel-Ange, 75794 Paris cedex 16. + +Institut National de Recherche en Informatique et en Automatique - +INRIA, \xE9tablissement public \xE0 caract\xE8re scientifique et technologique, +dont le si\xE8ge est situ\xE9 Domaine de Voluceau, Rocquencourt, BP 105, 78153 +Le Chesnay cedex. + + + Pr\xE9ambule + +Ce contrat est une licence de logiciel libre dont l'objectif est de +conf\xE9rer aux utilisateurs une tr\xE8s large libert\xE9 de modification et de +redistribution du logiciel r\xE9gi par cette licence. + +L'exercice de cette libert\xE9 est assorti d'une obligation forte de +citation \xE0 la charge de ceux qui distribueraient un logiciel incorporant +un logiciel r\xE9gi par la pr\xE9sente licence afin d'assurer que les +contributions de tous soient correctement identifi\xE9es et reconnues. + +L'accessibilit\xE9 au code source et les droits de copie, de modification +et de redistribution qui d\xE9coulent de ce contrat ont pour contrepartie +de n'offrir aux utilisateurs qu'une garantie limit\xE9e et de ne faire +peser sur l'auteur du logiciel, le titulaire des droits patrimoniaux et +les conc\xE9dants successifs qu'une responsabilit\xE9 restreinte. + +A cet \xE9gard l'attention de l'utilisateur est attir\xE9e sur les risques +associ\xE9s au chargement, \xE0 l'utilisation, \xE0 la modification et/ou au +d\xE9veloppement et \xE0 la reproduction du logiciel par l'utilisateur \xE9tant +donn\xE9 sa sp\xE9cificit\xE9 de logiciel libre, qui peut le rendre complexe \xE0 +manipuler et qui le r\xE9serve donc \xE0 des d\xE9veloppeurs ou des +professionnels avertis poss\xE9dant des connaissances informatiques +approfondies. Les utilisateurs sont donc invit\xE9s \xE0 charger et tester +l'ad\xE9quation du logiciel \xE0 leurs besoins dans des conditions permettant +d'assurer la s\xE9curit\xE9 de leurs syst\xE8mes et/ou de leurs donn\xE9es et, plus +g\xE9n\xE9ralement, \xE0 l'utiliser et l'exploiter dans les m\xEAmes conditions de +s\xE9curit\xE9. Ce contrat peut \xEAtre reproduit et diffus\xE9 librement, sous +r\xE9serve de le conserver en l'\xE9tat, sans ajout ni suppression de clauses. + +Ce contrat est susceptible de s'appliquer \xE0 tout logiciel dont le +titulaire des droits patrimoniaux d\xE9cide de soumettre l'exploitation aux +dispositions qu'il contient. + + + Article 1 - DEFINITIONS + +Dans ce contrat, les termes suivants, lorsqu'ils seront \xE9crits avec une +lettre capitale, auront la signification suivante: + +Contrat: d\xE9signe le pr\xE9sent contrat de licence, ses \xE9ventuelles versions +post\xE9rieures et annexes. + +Logiciel: d\xE9signe le logiciel sous sa forme de Code Objet et/ou de Code +Source et le cas \xE9ch\xE9ant sa documentation, dans leur \xE9tat au moment de +l'acceptation du Contrat par le Licenci\xE9. + +Logiciel Initial: d\xE9signe le Logiciel sous sa forme de Code Source et +\xE9ventuellement de Code Objet et le cas \xE9ch\xE9ant sa documentation, dans +leur \xE9tat au moment de leur premi\xE8re diffusion sous les termes du Contrat. + +Logiciel Modifi\xE9: d\xE9signe le Logiciel modifi\xE9 par au moins une +Contribution. + +Code Source: d\xE9signe l'ensemble des instructions et des lignes de +programme du Logiciel et auquel l'acc\xE8s est n\xE9cessaire en vue de +modifier le Logiciel. + +Code Objet: d\xE9signe les fichiers binaires issus de la compilation du +Code Source. + +Titulaire: d\xE9signe le ou les d\xE9tenteurs des droits patrimoniaux d'auteur +sur le Logiciel Initial. + +Licenci\xE9: d\xE9signe le ou les utilisateurs du Logiciel ayant accept\xE9 le +Contrat. + +Contributeur: d\xE9signe le Licenci\xE9 auteur d'au moins une Contribution. + +Conc\xE9dant: d\xE9signe le Titulaire ou toute personne physique ou morale +distribuant le Logiciel sous le Contrat. + +Contribution: d\xE9signe l'ensemble des modifications, corrections, +traductions, adaptations et/ou nouvelles fonctionnalit\xE9s int\xE9gr\xE9es dans +le Logiciel par tout Contributeur, ainsi que tout Module Interne. + +Module: d\xE9signe un ensemble de fichiers sources y compris leur +documentation qui permet de r\xE9aliser des fonctionnalit\xE9s ou services +suppl\xE9mentaires \xE0 ceux fournis par le Logiciel. + +Module Externe: d\xE9signe tout Module, non d\xE9riv\xE9 du Logiciel, tel que ce +Module et le Logiciel s'ex\xE9cutent dans des espaces d'adressage +diff\xE9rents, l'un appelant l'autre au moment de leur ex\xE9cution. + +Module Interne: d\xE9signe tout Module li\xE9 au Logiciel de telle sorte +qu'ils s'ex\xE9cutent dans le m\xEAme espace d'adressage. + +Parties: d\xE9signe collectivement le Licenci\xE9 et le Conc\xE9dant. + +Ces termes s'entendent au singulier comme au pluriel. + + + Article 2 - OBJET + +Le Contrat a pour objet la concession par le Conc\xE9dant au Licenci\xE9 d'une +licence non exclusive, cessible et mondiale du Logiciel telle que +d\xE9finie ci-apr\xE8s \xE0 l'article 5 pour toute la dur\xE9e de protection des droits +portant sur ce Logiciel. + + + Article 3 - ACCEPTATION + +3.1 L'acceptation par le Licenci\xE9 des termes du Contrat est r\xE9put\xE9e +acquise du fait du premier des faits suivants: + + * (i) le chargement du Logiciel par tout moyen notamment par + t\xE9l\xE9chargement \xE0 partir d'un serveur distant ou par chargement \xE0 + partir d'un support physique; + * (ii) le premier exercice par le Licenci\xE9 de l'un quelconque des + droits conc\xE9d\xE9s par le Contrat. + +3.2 Un exemplaire du Contrat, contenant notamment un avertissement +relatif aux sp\xE9cificit\xE9s du Logiciel, \xE0 la restriction de garantie et \xE0 +la limitation \xE0 un usage par des utilisateurs exp\xE9riment\xE9s a \xE9t\xE9 mis \xE0 +disposition du Licenci\xE9 pr\xE9alablement \xE0 son acceptation telle que +d\xE9finie \xE0 l'article 3.1 ci dessus et le Licenci\xE9 reconna\xEEt en avoir pris +connaissance. + + + Article 4 - ENTREE EN VIGUEUR ET DUREE + + + 4.1 ENTREE EN VIGUEUR + +Le Contrat entre en vigueur \xE0 la date de son acceptation par le Licenci\xE9 +telle que d\xE9finie en 3.1. + + + 4.2 DUREE + +Le Contrat produira ses effets pendant toute la dur\xE9e l\xE9gale de +protection des droits patrimoniaux portant sur le Logiciel. + + + Article 5 - ETENDUE DES DROITS CONCEDES + +Le Conc\xE9dant conc\xE8de au Licenci\xE9, qui accepte, les droits suivants sur +le Logiciel pour toutes destinations et pour la dur\xE9e du Contrat dans +les conditions ci-apr\xE8s d\xE9taill\xE9es. + +Par ailleurs, si le Conc\xE9dant d\xE9tient ou venait \xE0 d\xE9tenir un ou +plusieurs brevets d'invention prot\xE9geant tout ou partie des +fonctionnalit\xE9s du Logiciel ou de ses composants, il s'engage \xE0 ne pas +opposer les \xE9ventuels droits conf\xE9r\xE9s par ces brevets aux Licenci\xE9s +successifs qui utiliseraient, exploiteraient ou modifieraient le +Logiciel. En cas de cession de ces brevets, le Conc\xE9dant s'engage \xE0 +faire reprendre les obligations du pr\xE9sent alin\xE9a aux cessionnaires. + + + 5.1 DROIT D'UTILISATION + +Le Licenci\xE9 est autoris\xE9 \xE0 utiliser le Logiciel, sans restriction quant +aux domaines d'application, \xE9tant ci-apr\xE8s pr\xE9cis\xE9 que cela comporte: + + 1. la reproduction permanente ou provisoire du Logiciel en tout ou + partie par tout moyen et sous toute forme. + + 2. le chargement, l'affichage, l'ex\xE9cution, ou le stockage du + Logiciel sur tout support. + + 3. la possibilit\xE9 d'en observer, d'en \xE9tudier, ou d'en tester le + fonctionnement afin de d\xE9terminer les id\xE9es et principes qui sont + \xE0 la base de n'importe quel \xE9l\xE9ment de ce Logiciel; et ceci, + lorsque le Licenci\xE9 effectue toute op\xE9ration de chargement, + d'affichage, d'ex\xE9cution, de transmission ou de stockage du + Logiciel qu'il est en droit d'effectuer en vertu du Contrat. + + + 5.2 DROIT D'APPORTER DES CONTRIBUTIONS + +Le droit d'apporter des Contributions comporte le droit de traduire, +d'adapter, d'arranger ou d'apporter toute autre modification au Logiciel +et le droit de reproduire le logiciel en r\xE9sultant. + +Le Licenci\xE9 est autoris\xE9 \xE0 apporter toute Contribution au Logiciel sous +r\xE9serve de mentionner, de fa\xE7on explicite, son nom en tant qu'auteur de +cette Contribution et la date de cr\xE9ation de celle-ci. + + + 5.3 DROIT DE DISTRIBUTION + +Le droit de distribution comporte notamment le droit de diffuser, de +transmettre et de communiquer le Logiciel au public sur tout support et +par tout moyen ainsi que le droit de mettre sur le march\xE9 \xE0 titre +on\xE9reux ou gratuit, un ou des exemplaires du Logiciel par tout proc\xE9d\xE9. + +Le Licenci\xE9 est autoris\xE9 \xE0 distribuer des copies du Logiciel, modifi\xE9 ou +non, \xE0 des tiers dans les conditions ci-apr\xE8s d\xE9taill\xE9es. + + + 5.3.1 DISTRIBUTION DU LOGICIEL SANS MODIFICATION + +Le Licenci\xE9 est autoris\xE9 \xE0 distribuer des copies conformes du Logiciel, +sous forme de Code Source ou de Code Objet, \xE0 condition que cette +distribution respecte les dispositions du Contrat dans leur totalit\xE9 et +soit accompagn\xE9e: + + 1. d'un exemplaire du Contrat, + + 2. d'un avertissement relatif \xE0 la restriction de garantie et de + responsabilit\xE9 du Conc\xE9dant telle que pr\xE9vue aux articles 8 + et 9, + +et que, dans le cas o\xF9 seul le Code Objet du Logiciel est redistribu\xE9, +le Licenci\xE9 permette un acc\xE8s effectif au Code Source complet du +Logiciel pendant au moins toute la dur\xE9e de sa distribution du Logiciel, +\xE9tant entendu que le co\xFBt additionnel d'acquisition du Code Source ne +devra pas exc\xE9der le simple co\xFBt de transfert des donn\xE9es. + + + 5.3.2 DISTRIBUTION DU LOGICIEL MODIFIE + +Lorsque le Licenci\xE9 apporte une Contribution au Logiciel, le Logiciel +Modifi\xE9 peut \xEAtre distribu\xE9 sous un contrat de licence autre que le +pr\xE9sent Contrat sous r\xE9serve du respect des dispositions de l'article +5.3.4. + + + 5.3.3 DISTRIBUTION DES MODULES EXTERNES + +Lorsque le Licenci\xE9 a d\xE9velopp\xE9 un Module Externe les conditions du +Contrat ne s'appliquent pas \xE0 ce Module Externe, qui peut \xEAtre distribu\xE9 +sous un contrat de licence diff\xE9rent. + + + 5.3.4 CITATIONS + +Le Licenci\xE9 qui distribue un Logiciel Modifi\xE9 s'engage express\xE9ment: + + 1. \xE0 indiquer dans sa documentation qu'il a \xE9t\xE9 r\xE9alis\xE9 \xE0 partir du + Logiciel r\xE9gi par le Contrat, en reproduisant les mentions de + propri\xE9t\xE9 intellectuelle du Logiciel, + + 2. \xE0 faire en sorte que l'utilisation du Logiciel, ses mentions de + propri\xE9t\xE9 intellectuelle et le fait qu'il est r\xE9gi par le Contrat + soient indiqu\xE9s dans un texte facilement accessible depuis + l'interface du Logiciel Modifi\xE9, + + 3. \xE0 mentionner, sur un site Web librement accessible d\xE9crivant le + Logiciel Modifi\xE9, et pendant au moins toute la dur\xE9e de sa + distribution, qu'il a \xE9t\xE9 r\xE9alis\xE9 \xE0 partir du Logiciel r\xE9gi par le + Contrat, en reproduisant les mentions de propri\xE9t\xE9 intellectuelle + du Logiciel, + + 4. lorsqu'il le distribue \xE0 un tiers susceptible de distribuer + lui-m\xEAme un Logiciel Modifi\xE9, sans avoir \xE0 en distribuer le code + source, \xE0 faire ses meilleurs efforts pour que les obligations du + pr\xE9sent article 5.3.4 soient reprises par le dit tiers. + +Lorsque le Logiciel modifi\xE9 ou non est distribu\xE9 avec un Module Externe +qui a \xE9t\xE9 con\xE7u pour l'utiliser, le Licenci\xE9 doit soumettre le dit +Module Externe aux obligations pr\xE9c\xE9dentes. + + + 5.3.5 COMPATIBILITE AVEC LES LICENCES CeCILL et CeCILL-C + +Lorsqu'un Logiciel Modifi\xE9 contient une Contribution soumise au contrat +de licence CeCILL, les stipulations pr\xE9vues \xE0 l'article 5.3.4 sont +facultatives. + +Un Logiciel Modifi\xE9 peut \xEAtre distribu\xE9 sous le contrat de licence +CeCILL-C. Les stipulations pr\xE9vues \xE0 l'article 5.3.4 sont alors +facultatives. + + + Article 6 - PROPRIETE INTELLECTUELLE + + + 6.1 SUR LE LOGICIEL INITIAL + +Le Titulaire est d\xE9tenteur des droits patrimoniaux sur le Logiciel +Initial. Toute utilisation du Logiciel Initial est soumise au respect +des conditions dans lesquelles le Titulaire a choisi de diffuser son +oeuvre et nul autre n'a la facult\xE9 de modifier les conditions de +diffusion de ce Logiciel Initial. + +Le Titulaire s'engage \xE0 ce que le Logiciel Initial reste au moins r\xE9gi +par le Contrat et ce, pour la dur\xE9e vis\xE9e \xE0 l'article 4.2. + + + 6.2 SUR LES CONTRIBUTIONS + +Le Licenci\xE9 qui a d\xE9velopp\xE9 une Contribution est titulaire sur celle-ci +des droits de propri\xE9t\xE9 intellectuelle dans les conditions d\xE9finies par +la l\xE9gislation applicable. + + + 6.3 SUR LES MODULES EXTERNES + +Le Licenci\xE9 qui a d\xE9velopp\xE9 un Module Externe est titulaire sur celui-ci +des droits de propri\xE9t\xE9 intellectuelle dans les conditions d\xE9finies par +la l\xE9gislation applicable et reste libre du choix du contrat r\xE9gissant +sa diffusion. + + + 6.4 DISPOSITIONS COMMUNES + +Le Licenci\xE9 s'engage express\xE9ment: + + 1. \xE0 ne pas supprimer ou modifier de quelque mani\xE8re que ce soit les + mentions de propri\xE9t\xE9 intellectuelle appos\xE9es sur le Logiciel; + + 2. \xE0 reproduire \xE0 l'identique lesdites mentions de propri\xE9t\xE9 + intellectuelle sur les copies du Logiciel modifi\xE9 ou non. + +Le Licenci\xE9 s'engage \xE0 ne pas porter atteinte, directement ou +indirectement, aux droits de propri\xE9t\xE9 intellectuelle du Titulaire et/ou +des Contributeurs sur le Logiciel et \xE0 prendre, le cas \xE9ch\xE9ant, \xE0 +l'\xE9gard de son personnel toutes les mesures n\xE9cessaires pour assurer le +respect des dits droits de propri\xE9t\xE9 intellectuelle du Titulaire et/ou +des Contributeurs. + + + Article 7 - SERVICES ASSOCIES + +7.1 Le Contrat n'oblige en aucun cas le Conc\xE9dant \xE0 la r\xE9alisation de +prestations d'assistance technique ou de maintenance du Logiciel. + +Cependant le Conc\xE9dant reste libre de proposer ce type de services. Les +termes et conditions d'une telle assistance technique et/ou d'une telle +maintenance seront alors d\xE9termin\xE9s dans un acte s\xE9par\xE9. Ces actes de +maintenance et/ou assistance technique n'engageront que la seule +responsabilit\xE9 du Conc\xE9dant qui les propose. + +7.2 De m\xEAme, tout Conc\xE9dant est libre de proposer, sous sa seule +responsabilit\xE9, \xE0 ses licenci\xE9s une garantie, qui n'engagera que lui, +lors de la redistribution du Logiciel et/ou du Logiciel Modifi\xE9 et ce, +dans les conditions qu'il souhaite. Cette garantie et les modalit\xE9s +financi\xE8res de son application feront l'objet d'un acte s\xE9par\xE9 entre le +Conc\xE9dant et le Licenci\xE9. + + + Article 8 - RESPONSABILITE + +8.1 Sous r\xE9serve des dispositions de l'article 8.2, le Licenci\xE9 a la +facult\xE9, sous r\xE9serve de prouver la faute du Conc\xE9dant concern\xE9, de +solliciter la r\xE9paration du pr\xE9judice direct qu'il subirait du fait du +Logiciel et dont il apportera la preuve. + +8.2 La responsabilit\xE9 du Conc\xE9dant est limit\xE9e aux engagements pris en +application du Contrat et ne saurait \xEAtre engag\xE9e en raison notamment: +(i) des dommages dus \xE0 l'inex\xE9cution, totale ou partielle, de ses +obligations par le Licenci\xE9, (ii) des dommages directs ou indirects +d\xE9coulant de l'utilisation ou des performances du Logiciel subis par le +Licenci\xE9 et (iii) plus g\xE9n\xE9ralement d'un quelconque dommage indirect. En +particulier, les Parties conviennent express\xE9ment que tout pr\xE9judice +financier ou commercial (par exemple perte de donn\xE9es, perte de +b\xE9n\xE9fices, perte d'exploitation, perte de client\xE8le ou de commandes, +manque \xE0 gagner, trouble commercial quelconque) ou toute action dirig\xE9e +contre le Licenci\xE9 par un tiers, constitue un dommage indirect et +n'ouvre pas droit \xE0 r\xE9paration par le Conc\xE9dant. + + + Article 9 - GARANTIE + +9.1 Le Licenci\xE9 reconna\xEEt que l'\xE9tat actuel des connaissances +scientifiques et techniques au moment de la mise en circulation du +Logiciel ne permet pas d'en tester et d'en v\xE9rifier toutes les +utilisations ni de d\xE9tecter l'existence d'\xE9ventuels d\xE9fauts. L'attention +du Licenci\xE9 a \xE9t\xE9 attir\xE9e sur ce point sur les risques associ\xE9s au +chargement, \xE0 l'utilisation, la modification et/ou au d\xE9veloppement et \xE0 +la reproduction du Logiciel qui sont r\xE9serv\xE9s \xE0 des utilisateurs avertis. + +Il rel\xE8ve de la responsabilit\xE9 du Licenci\xE9 de contr\xF4ler, par tous +moyens, l'ad\xE9quation du produit \xE0 ses besoins, son bon fonctionnement et +de s'assurer qu'il ne causera pas de dommages aux personnes et aux biens. + +9.2 Le Conc\xE9dant d\xE9clare de bonne foi \xEAtre en droit de conc\xE9der +l'ensemble des droits attach\xE9s au Logiciel (comprenant notamment les +droits vis\xE9s \xE0 l'article 5). + +9.3 Le Licenci\xE9 reconna\xEEt que le Logiciel est fourni "en l'\xE9tat" par le +Conc\xE9dant sans autre garantie, expresse ou tacite, que celle pr\xE9vue \xE0 +l'article 9.2 et notamment sans aucune garantie sur sa valeur commerciale, +son caract\xE8re s\xE9curis\xE9, innovant ou pertinent. + +En particulier, le Conc\xE9dant ne garantit pas que le Logiciel est exempt +d'erreur, qu'il fonctionnera sans interruption, qu'il sera compatible +avec l'\xE9quipement du Licenci\xE9 et sa configuration logicielle ni qu'il +remplira les besoins du Licenci\xE9. + +9.4 Le Conc\xE9dant ne garantit pas, de mani\xE8re expresse ou tacite, que le +Logiciel ne porte pas atteinte \xE0 un quelconque droit de propri\xE9t\xE9 +intellectuelle d'un tiers portant sur un brevet, un logiciel ou sur tout +autre droit de propri\xE9t\xE9. Ainsi, le Conc\xE9dant exclut toute garantie au +profit du Licenci\xE9 contre les actions en contrefa\xE7on qui pourraient \xEAtre +diligent\xE9es au titre de l'utilisation, de la modification, et de la +redistribution du Logiciel. N\xE9anmoins, si de telles actions sont +exerc\xE9es contre le Licenci\xE9, le Conc\xE9dant lui apportera son aide +technique et juridique pour sa d\xE9fense. Cette aide technique et +juridique est d\xE9termin\xE9e au cas par cas entre le Conc\xE9dant concern\xE9 et +le Licenci\xE9 dans le cadre d'un protocole d'accord. Le Conc\xE9dant d\xE9gage +toute responsabilit\xE9 quant \xE0 l'utilisation de la d\xE9nomination du +Logiciel par le Licenci\xE9. Aucune garantie n'est apport\xE9e quant \xE0 +l'existence de droits ant\xE9rieurs sur le nom du Logiciel et sur +l'existence d'une marque. + + + Article 10 - RESILIATION + +10.1 En cas de manquement par le Licenci\xE9 aux obligations mises \xE0 sa +charge par le Contrat, le Conc\xE9dant pourra r\xE9silier de plein droit le +Contrat trente (30) jours apr\xE8s notification adress\xE9e au Licenci\xE9 et +rest\xE9e sans effet. + +10.2 Le Licenci\xE9 dont le Contrat est r\xE9sili\xE9 n'est plus autoris\xE9 \xE0 +utiliser, modifier ou distribuer le Logiciel. Cependant, toutes les +licences qu'il aura conc\xE9d\xE9es ant\xE9rieurement \xE0 la r\xE9siliation du Contrat +resteront valides sous r\xE9serve qu'elles aient \xE9t\xE9 effectu\xE9es en +conformit\xE9 avec le Contrat. + + + Article 11 - DISPOSITIONS DIVERSES + + + 11.1 CAUSE EXTERIEURE + +Aucune des Parties ne sera responsable d'un retard ou d'une d\xE9faillance +d'ex\xE9cution du Contrat qui serait d\xFB \xE0 un cas de force majeure, un cas +fortuit ou une cause ext\xE9rieure, telle que, notamment, le mauvais +fonctionnement ou les interruptions du r\xE9seau \xE9lectrique ou de +t\xE9l\xE9communication, la paralysie du r\xE9seau li\xE9e \xE0 une attaque +informatique, l'intervention des autorit\xE9s gouvernementales, les +catastrophes naturelles, les d\xE9g\xE2ts des eaux, les tremblements de terre, +le feu, les explosions, les gr\xE8ves et les conflits sociaux, l'\xE9tat de +guerre... + +11.2 Le fait, par l'une ou l'autre des Parties, d'omettre en une ou +plusieurs occasions de se pr\xE9valoir d'une ou plusieurs dispositions du +Contrat, ne pourra en aucun cas impliquer renonciation par la Partie +int\xE9ress\xE9e \xE0 s'en pr\xE9valoir ult\xE9rieurement. + +11.3 Le Contrat annule et remplace toute convention ant\xE9rieure, \xE9crite +ou orale, entre les Parties sur le m\xEAme objet et constitue l'accord +entier entre les Parties sur cet objet. Aucune addition ou modification +aux termes du Contrat n'aura d'effet \xE0 l'\xE9gard des Parties \xE0 moins +d'\xEAtre faite par \xE9crit et sign\xE9e par leurs repr\xE9sentants d\xFBment habilit\xE9s. + +11.4 Dans l'hypoth\xE8se o\xF9 une ou plusieurs des dispositions du Contrat +s'av\xE8rerait contraire \xE0 une loi ou \xE0 un texte applicable, existants ou +futurs, cette loi ou ce texte pr\xE9vaudrait, et les Parties feraient les +amendements n\xE9cessaires pour se conformer \xE0 cette loi ou \xE0 ce texte. +Toutes les autres dispositions resteront en vigueur. De m\xEAme, la +nullit\xE9, pour quelque raison que ce soit, d'une des dispositions du +Contrat ne saurait entra\xEEner la nullit\xE9 de l'ensemble du Contrat. + + + 11.5 LANGUE + +Le Contrat est r\xE9dig\xE9 en langue fran\xE7aise et en langue anglaise, ces +deux versions faisant \xE9galement foi. + + + Article 12 - NOUVELLES VERSIONS DU CONTRAT + +12.1 Toute personne est autoris\xE9e \xE0 copier et distribuer des copies de +ce Contrat. + +12.2 Afin d'en pr\xE9server la coh\xE9rence, le texte du Contrat est prot\xE9g\xE9 +et ne peut \xEAtre modifi\xE9 que par les auteurs de la licence, lesquels se +r\xE9servent le droit de publier p\xE9riodiquement des mises \xE0 jour ou de +nouvelles versions du Contrat, qui poss\xE9deront chacune un num\xE9ro +distinct. Ces versions ult\xE9rieures seront susceptibles de prendre en +compte de nouvelles probl\xE9matiques rencontr\xE9es par les logiciels libres. + +12.3 Tout Logiciel diffus\xE9 sous une version donn\xE9e du Contrat ne pourra +faire l'objet d'une diffusion ult\xE9rieure que sous la m\xEAme version du +Contrat ou une version post\xE9rieure. + + + Article 13 - LOI APPLICABLE ET COMPETENCE TERRITORIALE + +13.1 Le Contrat est r\xE9gi par la loi fran\xE7aise. Les Parties conviennent +de tenter de r\xE9gler \xE0 l'amiable les diff\xE9rends ou litiges qui +viendraient \xE0 se produire par suite ou \xE0 l'occasion du Contrat. + +13.2 A d\xE9faut d'accord amiable dans un d\xE9lai de deux (2) mois \xE0 compter +de leur survenance et sauf situation relevant d'une proc\xE9dure d'urgence, +les diff\xE9rends ou litiges seront port\xE9s par la Partie la plus diligente +devant les Tribunaux comp\xE9tents de Paris. + + +Version 1.0 du 2006-09-05. Added: trunk/src/pyphant/pyphant/quantities/NumberDict.py =================================================================== --- trunk/src/pyphant/pyphant/quantities/NumberDict.py (rev 0) +++ trunk/src/pyphant/pyphant/quantities/NumberDict.py 2008-11-11 11:17:02 UTC (rev 573) @@ -0,0 +1,67 @@ +# Dictionary containing numbers +# +# These objects are meant to be used like arrays with generalized +# indices. Non-existent elements default to zero. Global operations +# are addition, subtraction, and multiplication/division by a scalar. +# +# Written by Konrad Hinsen <hi...@cn...> +# last revision: 2006-10-16 +# + +""" +Dictionary storing numerical values +""" + +class NumberDict(dict): + + """ + Dictionary storing numerical values + + Constructor: NumberDict() + + An instance of this class acts like an array of number with + generalized (non-integer) indices. A value of zero is assumed + for undefined entries. NumberDict instances support addition, + and subtraction with other NumberDict instances, and multiplication + and division by scalars. + """ + + def __getitem__(self, item): + try: + return dict.__getitem__(self, item) + except KeyError: + return 0 + + def __coerce__(self, other): + if type(other) == type({}): + other = NumberDict(other) + return self, other + + def __add__(self, other): + sum_dict = NumberDict() + for key in self.keys(): + sum_dict[key] = self[key] + for key in other.keys(): + sum_dict[key] = sum_dict[key] + other[key] + return sum_dict + + def __sub__(self, other): + sum_dict = NumberDict() + for key in self.keys(): + sum_dict[key] = self[key] + for key in other.keys(): + sum_dict[key] = sum_dict[key] - other[key] + return sum_dict + + def __mul__(self, other): + new = NumberDict() + for key in self.keys(): + new[key] = other*self[key] + return new + __rmul__ = __mul__ + + def __div__(self, other): + new = NumberDict() + for key in self.keys(): + new[key] = self[key]/other + return new Added: trunk/src/pyphant/pyphant/quantities/PhysicalQuantities.py =================================================================== --- trunk/src/pyphant/pyphant/quantities/PhysicalQuantities.py (rev 0) +++ trunk/src/pyphant/pyphant/quantities/PhysicalQuantities.py 2008-11-11 11:17:02 UTC (rev 573) @@ -0,0 +1,843 @@ +# Physical quantities with units +# +# Written by Konrad Hinsen <hi...@cn...> +# with contributions from Greg Ward +# merged into Pyphant by Andreas W. Liehr +# last revision: 2008-11-10 +# + +""" +Physical quantities with units. + +This module provides a data type that represents a physical +quantity together with its unit. It is possible to add and +subtract these quantities if the units are compatible, and +a quantity can be converted to another compatible unit. +Multiplication, subtraction, and raising to integer powers +is allowed without restriction, and the result will have +the correct unit. A quantity can be raised to a non-integer +power only if the result can be represented by integer powers +of the base units. + +The values of physical constants are taken from the 1986 +recommended values from CODATA. Other conversion factors +(e.g. for British units) come from various sources. I can't +guarantee for the correctness of all entries in the unit +table, so use this at your own risk. +""" + +from pyphant.quantities.NumberDict import NumberDict + +import numpy.oldnumeric +def int_sum(a, axis=0): + return numpy.oldnumeric.add.reduce(a, axis) +def zeros_st(shape, other): + return numpy.oldnumeric.zeros(shape, dtype=other.dtype) +from numpy import ndarray as array_type + + +import re, string + + +# Class definitions + +class PhysicalQuantity: + + """ + Physical quantity with units + + PhysicalQuantity instances allow addition, subtraction, + multiplication, and division with each other as well as + multiplication, division, and exponentiation with numbers. + Addition and subtraction check that the units of the two operands + are compatible and return the result in the units of the first + operand. A limited set of mathematical functions (from module + Numeric) is applicable as well: + + - sqrt: equivalent to exponentiation with 0.5. + + - sin, cos, tan: applicable only to objects whose unit is + compatible with 'rad'. + + See the documentation of the PhysicalQuantities module for a list + of the available units. + + Here is an example on usage: + + >>> from PhysicalQuantities import PhysicalQuantity as p # short hand + >>> distance1 = p('10 m') + >>> distance2 = p('10 km') + >>> total = distance1 + distance2 + >>> total + PhysicalQuantity(10010.0,'m') + >>> total.convertToUnit('km') + >>> total.getValue() + 10.01 + >>> total.getUnitName() + 'km' + >>> total = total.inBaseUnits() + >>> total + PhysicalQuantity(10010.0,'m') + >>> + >>> t = p(314159., 's') + >>> # convert to days, hours, minutes, and second: + >>> t2 = t.inUnitsOf('d','h','min','s') + >>> t2_print = ' '.join([str(i) for i in t2]) + >>> t2_print + '3.0 d 15.0 h 15.0 min 59.0 s' + >>> + >>> e = p('2.7 Hartree*Nav') + >>> e.convertToUnit('kcal/mol') + >>> e + PhysicalQuantity(1694.2757596034764,'kcal/mol') + >>> e = e.inBaseUnits() + >>> str(e) + '7088849.77818 kg*m**2/s**2/mol' + >>> + >>> freeze = p('0 degC') + >>> freeze = freeze.inUnitsOf ('degF') + >>> str(freeze) + '32.0 degF' + >>> + """ + + def __init__(self, *args): + """ + There are two constructor calling patterns: + + 1. PhysicalQuantity(value, unit), where value is any number + and unit is a string defining the unit + + 2. PhysicalQuantity(value_with_unit), where value_with_unit + is a string that contains both the value and the unit, + i.e. '1.5 m/s'. This form is provided for more convenient + interactive use. + + @param args: either (value, unit) or (value_with_unit,) + @type args: (number, C{str}) or (C{str},) + """ + if len(args) == 2: + self.value = args[0] + self.unit = _findUnit(args[1]) + else: + s = string.strip(args[0]) + match = PhysicalQuantity._number.match(s) + if match is None: + raise TypeError('No number found') + self.value = string.atof(match.group(0)) + self.unit = _findUnit(s[len(match.group(0)):]) + + _number = re.compile('[+-]?[0-9]+(\\.[0-9]*)?([eE][+-]?[0-9]+)?') + + def __str__(self): + return str(self.value) + ' ' + self.unit.name() + + def __repr__(self): + return (self.__class__.__name__ + '(' + `self.value` + ',' + + `self.unit.name()` + ')') + + def _sum(self, other, sign1, sign2): + if not isPhysicalQuantity(other): + raise TypeError('Incompatible types') + new_value = sign1*self.value + \ + sign2*other.value*other.unit.conversionFactorTo(self.unit) + return self.__class__(new_value, self.unit) + + def __add__(self, other): + return self._sum(other, 1, 1) + + __radd__ = __add__ + + def __sub__(self, other): + return self._sum(other, 1, -1) + + def __rsub__(self, other): + return self._sum(other, -1, 1) + + def __cmp__(self, other): + diff = self._sum(other, 1, -1) + return cmp(diff.value, 0) + + def __mul__(self, other): + if not isPhysicalQuantity(other): + return self.__class__(self.value*other, self.unit) + value = self.value*other.value + unit = self.unit*other.unit + if unit.isDimensionless(): + return value*unit.factor + else: + return self.__class__(value, unit) + + __rmul__ = __mul__ + + def __div__(self, other): + if not isPhysicalQuantity(other): + return self.__class__(self.value/other, self.unit) + value = self.value/other.value + unit = self.unit/other.unit + if unit.isDimensionless(): + return value*unit.factor + else: + return self.__class__(value, unit) + + def __rdiv__(self, other): + if not isPhysicalQuantity(other): + return self.__class__(other/self.value, pow(self.unit, -1)) + value = other.value/self.value + unit = other.unit/self.unit + if unit.isDimensionless(): + return value*unit.factor + else: + return self.__class__(value, unit) + + def __pow__(self, other): + if isPhysicalQuantity(other): + raise TypeError('Exponents must be dimensionless') + return self.__class__(pow(self.value, other), pow(self.unit, other)) + + def __rpow__(self, other): + raise TypeError('Exponents must be dimensionless') + + def __abs__(self): + return self.__class__(abs(self.value), self.unit) + + def __pos__(self): + return self + + def __neg__(self): + return self.__class__(-self.value, self.unit) + + def __nonzero__(self): + return self.value != 0 + + def convertToUnit(self, unit): + """ + Change the unit and adjust the value such that + the combination is equivalent to the original one. The new unit + must be compatible with the previous unit of the object. + + @param unit: a unit + @type unit: C{str} + @raise TypeError: if the unit string is not a know unit or a + unit incompatible with the current one + """ + unit = _findUnit(unit) + self.value = _convertValue (self.value, self.unit, unit) + self.unit = unit + + def inUnitsOf(self, *units): + """ + Express the quantity in different units. If one unit is + specified, a new PhysicalQuantity object is returned that + expresses the quantity in that unit. If several units + are specified, the return value is a tuple of + PhysicalObject instances with with one element per unit such + that the sum of all quantities in the tuple equals the the + original quantity and all the values except for the last one + are integers. This is used to convert to irregular unit + systems like hour/minute/second. + + @param units: one or several units + @type units: C{str} or sequence of C{str} + @returns: one or more physical quantities + @rtype: L{PhysicalQuantity} or C{tuple} of L{PhysicalQuantity} + @raises TypeError: if any of the specified units are not compatible + with the original unit + """ + units = map(_findUnit, units) + if len(units) == 1: + unit = units[0] + value = _convertValue (self.value, self.unit, unit) + return self.__class__(value, unit) + else: + units.sort() + result = [] + value = self.value + unit = self.unit + for i in range(len(units)-1,-1,-1): + value = value*unit.conversionFactorTo(units[i]) + if i == 0: + rounded = value + else: + rounded = _round(value) + result.append(self.__class__(rounded, units[i])) + value = value - rounded + unit = units[i] + return tuple(result) + + # Contributed by Berthold Hoellmann + def inBaseUnits(self): + """ + @returns: the same quantity converted to base units, + i.e. SI units in most cases + @rtype: L{PhysicalQuantity} + """ + new_value = self.value * self.unit.factor + num = '' + denom = '' + for i in xrange(9): + unit = _base_names[i] + power = self.unit.powers[i] + if power < 0: + denom = denom + '/' + unit + if power < -1: + denom = denom + '**' + str(-power) + elif power > 0: + num = num + '*' + unit + if power > 1: + num = num + '**' + str(power) + if len(num) == 0: + num = '1' + else: + num = num[1:] + return self.__class__(new_value, num + denom) + + def isCompatible (self, unit): + """ + @param unit: a unit + @type unit: C{str} + @returns: C{True} if the specified unit is compatible with the + one of the quantity + @rtype: C{bool} + """ + unit = _findUnit (unit) + return self.unit.isCompatible (unit) + + def getValue(self): + """Return value (float) of physical quantity (no unit).""" + return self.value + + def getUnitName(self): + """Return unit (string) of physical quantity.""" + return self.unit.name() + + def sqrt(self): + return pow(self, 0.5) + + def sin(self): + if self.unit.isAngle(): + return numpy.oldnumeric.sin(self.value * \ + self.unit.conversionFactorTo(_unit_table['rad'])) + else: + raise TypeError('Argument of sin must be an angle') + + def cos(self): + if self.unit.isAngle(): + return numpy.oldnumeric.cos(self.value * \ + self.unit.conversionFactorTo(_unit_table['rad'])) + else: + raise TypeError('Argument of cos must be an angle') + + def tan(self): + if self.unit.isAngle(): + return numpy.oldnumeric.tan(self.value * \ + self.unit.conversionFactorTo(_unit_table['rad'])) + else: + raise TypeError('Argument of tan must be an angle') + + +class PhysicalUnit: + + """ + Physical unit + + A physical unit is defined by a name (possibly composite), a scaling + factor, and the exponentials of each of the SI base units that enter into + it. Units can be multiplied, divided, and raised to integer powers. + """ + + def __init__(self, names, factor, powers, offset=0): + """ + @param names: a dictionary mapping each name component to its + associated integer power (e.g. C{{'m': 1, 's': -1}}) + for M{m/s}). As a shorthand, a string may be passed + which is assigned an implicit power 1. + @type names: C{dict} or C{str} + @param factor: a scaling factor + @type factor: C{float} + @param powers: the integer powers for each of the nine base units + @type powers: C{list} of C{int} + @param offset: an additive offset to the base unit (used only for + temperatures) + @type offset: C{float} + """ + if type(names) == type(''): + self.names = NumberDict() + self.names[names] = 1 + else: + self.names = names + self.factor = factor + self.offset = offset + self.powers = powers + + def __repr__(self): + return '<PhysicalUnit ' + self.name() + '>' + + __str__ = __repr__ + + def __cmp__(self, other): + if self.powers != other.powers: + raise TypeError('Incompatible units') + return cmp(self.factor, other.factor) + + def __mul__(self, other): + if self.offset != 0 or (isPhysicalUnit (other) and other.offset != 0): + raise TypeError("cannot multiply units with non-zero offset") + if isPhysicalUnit(other): + return PhysicalUnit(self.names+other.names, + self.factor*other.factor, + map(lambda a,b: a+b, + self.powers, other.powers)) + else: + return PhysicalUnit(self.names+{str(other): 1}, + self.factor*other, + self.powers, + self.offset * other) + + __rmul__ = __mul__ + + def __div__(self, other): + if self.offset != 0 or (isPhysicalUnit (other) and other.offset != 0): + raise TypeError("cannot divide units with non-zero offset") + if isPhysicalUnit(other): + return PhysicalUnit(self.names-other.names, + self.factor/other.factor, + map(lambda a,b: a-b, + self.powers, other.powers)) + else: + return PhysicalUnit(self.names+{str(other): -1}, + self.factor/other, self.powers) + + def __rdiv__(self, other): + if self.offset != 0 or (isPhysicalUnit (other) and other.offset != 0): + raise TypeError("cannot divide units with non-zero offset") + if isPhysicalUnit(other): + return PhysicalUnit(other.names-self.names, + other.factor/self.factor, + map(lambda a,b: a-b, + other.powers, self.powers)) + else: + return PhysicalUnit({str(other): 1}-self.names, + other/self.factor, + map(lambda x: -x, self.powers)) + + def __pow__(self, other): + if self.offset != 0: + raise TypeError("cannot exponentiate units with non-zero offset") + if isinstance(other, int): + return PhysicalUnit(other*self.names, pow(self.factor, other), + map(lambda x,p=other: x*p, self.powers)) + if isinstance(other, float): + inv_exp = 1./other + rounded = int(numpy.oldnumeric.floor(inv_exp+0.5)) + if abs(inv_exp-rounded) < 1.e-10: + if reduce(lambda a, b: a and b, + map(lambda x, e=rounded: x%e == 0, self.powers)): + f = pow(self.factor, other) + p = map(lambda x,p=rounded: x/p, self.powers) + if reduce(lambda a, b: a and b, + map(lambda x, e=rounded: x%e == 0, + self.names.values())): + names = self.names/rounded + else: + names = NumberDict() + if f != 1.: + names[str(f)] = 1 + for i in range(len(p)): + names[_base_names[i]] = p[i] + return PhysicalUnit(names, f, p) + else: + raise TypeError('Illegal exponent') + raise TypeError('Only integer and inverse integer exponents allowed') + + def conversionFactorTo(self, other): + """ + @param other: another unit + @type other: L{PhysicalUnit} + @returns: the conversion factor from this unit to another unit + @rtype: C{float} + @raises TypeError: if the units are not compatible + """ + if self.powers != other.powers: + raise TypeError('Incompatible units') + if self.offset != other.offset and self.factor != other.factor: + raise TypeError(('Unit conversion (%s to %s) cannot be expressed ' + + 'as a simple multiplicative factor') % \ + (self.name(), other.name())) + return self.factor/other.factor + + def conversionTupleTo(self, other): # added 1998/09/29 GPW + """ + @param other: another unit + @type other: L{PhysicalUnit} + @returns: the conversion factor and offset from this unit to + another unit + @rtype: (C{float}, C{float}) + @raises TypeError: if the units are not compatible + """ + if self.powers != other.powers: + raise TypeError('Incompatible units') + + # let (s1,d1) be the conversion tuple from 'self' to base units + # (ie. (x+d1)*s1 converts a value x from 'self' to base units, + # and (x/s1)-d1 converts x from base to 'self' units) + # and (s2,d2) be the conversion tuple from 'other' to base units + # then we want to compute the conversion tuple (S,D) from + # 'self' to 'other' such that (x+D)*S converts x from 'self' + # units to 'other' units + # the formula to convert x from 'self' to 'other' units via the + # base units is (by definition of the conversion tuples): + # ( ((x+d1)*s1) / s2 ) - d2 + # = ( (x+d1) * s1/s2) - d2 + # = ( (x+d1) * s1/s2 ) - (d2*s2/s1) * s1/s2 + # = ( (x+d1) - (d1*s2/s1) ) * s1/s2 + # = (x + d1 - d2*s2/s1) * s1/s2 + # thus, D = d1 - d2*s2/s1 and S = s1/s2 + factor = self.factor / other.factor + offset = self.offset - (other.offset * other.factor / self.factor) + return (factor, offset) + + def isCompatible (self, other): # added 1998/10/01 GPW + """ + @param other: another unit + @type other: L{PhysicalUnit} + @returns: C{True} if the units are compatible, i.e. if the powers of + the base units are the same + @rtype: C{bool} + """ + return self.powers == other.powers + + def isDimensionless(self): + return not reduce(lambda a,b: a or b, self.powers) + + def isAngle(self): + return self.powers[7] == 1 and \ + reduce(lambda a,b: a + b, self.powers) == 1 + + def setName(self, name): + self.names = NumberDict() + self.names[name] = 1 + + def name(self): + num = '' + denom = '' + for unit in self.names.keys(): + power = self.names[unit] + if power < 0: + denom = denom + '/' + unit + if power < -1: + denom = denom + '**' + str(-power) + elif power > 0: + num = num + '*' + unit + if power > 1: + num = num + '**' + str(power) + if len(num) == 0: + num = '1' + else: + num = num[1:] + return num + denom + + +# Type checks + +def isPhysicalUnit(x): + """ + @param x: an object + @type x: any + @returns: C{True} if x is a L{PhysicalUnit} + @rtype: C{bool} + """ + return hasattr(x, 'factor') and hasattr(x, 'powers') + +def isPhysicalQuantity(x): + """ + @param x: an object + @type x: any + @returns: C{True} if x is a L{PhysicalQuantity} + @rtype: C{bool} + """ + return hasattr(x, 'value') and hasattr(x, 'unit') + + +# Helper functions + +def _findUnit(unit): + if type(unit) == type(''): + name = string.strip(unit) + unit = eval(name, _unit_table) + for cruft in ['__builtins__', '__args__']: + try: del _unit_table[cruft] + except: pass + + if not isPhysicalUnit(unit): + raise TypeError(str(unit) + ' is not a unit') + return unit + +def _round(x): + if numpy.oldnumeric.greater(x, 0.): + return numpy.oldnumeric.floor(x) + else: + return numpy.oldnumeric.ceil(x) + + +def _convertValue (value, src_unit, target_unit): + (factor, offset) = src_unit.conversionTupleTo(target_unit) + return (value + offset) * factor + + +# SI unit definitions + +_base_names = ['m', 'kg', 's', 'A', 'K', 'mol', 'cd', 'rad', 'sr'] + +_base_units = [('m', PhysicalUnit('m', 1., [1,0,0,0,0,0,0,0,0])), + ('g', PhysicalUnit('g', 0.001, [0,1,0,0,0,0,0,0,0])), + ('s', PhysicalUnit('s', 1., [0,0,1,0,0,0,0,0,0])), + ('A', PhysicalUnit('A', 1., [0,0,0,1,0,0,0,0,0])), + ('K', PhysicalUnit('K', 1., [0,0,0,0,1,0,0,0,0])), + ('mol', PhysicalUnit('mol', 1., [0,0,0,0,0,1,0,0,0])), + ('cd', PhysicalUnit('cd', 1., [0,0,0,0,0,0,1,0,0])), + ('rad', PhysicalUnit('rad', 1., [0,0,0,0,0,0,0,1,0])), + ('sr', PhysicalUnit('sr', 1., [0,0,0,0,0,0,0,0,1])), + ] + +_prefixes = [('Y', 1.e24), + ('Z', 1.e21), + ('E', 1.e18), + ('P', 1.e15), + ('T', 1.e12), + ('G', 1.e9), + ('M', 1.e6), + ('k', 1.e3), + ('h', 1.e2), + ('da', 1.e1), + ('d', 1.e-1), + ('c', 1.e-2), + ('m', 1.e-3), + ('mu', 1.e-6), + ('n', 1.e-9), + ('p', 1.e-12), + ('f', 1.e-15), + ('a', 1.e-18), + ('z', 1.e-21), + ('y', 1.e-24), + ] + +_unit_table = {} + +for unit in _base_units: + _unit_table[unit[0]] = unit[1] + +_help = [] + +def _addUnit(name, unit, comment=''): + if _unit_table.has_key(name): + raise KeyError, 'Unit ' + name + ' already defined' + if comment: + _help.append((name, comment, unit)) + if type(unit) == type(''): + unit = eval(unit, _unit_table) + for cruft in ['__builtins__', '__args__']: + try: del _unit_table[cruft] + except: pass + unit.setName(name) + _unit_table[name] = unit + +def _addPrefixed(unit): + _help.append('Prefixed units for %s:' % unit) + _prefixed_names = [] + for prefix in _prefixes: + name = prefix[0] + unit + _addUnit(name, prefix[1]*_unit_table[unit]) + _prefixed_names.append(name) + _help.append(', '.join(_prefixed_names)) + + +# SI derived units; these automatically get prefixes +_help.append('SI derived units; these automatically get prefixes:\n' + \ + ', '.join([prefix + ' (%.0E)' % value for prefix, value in _prefixes]) + \ + '\n') + + +_unit_table['kg'] = PhysicalUnit('kg', 1., [0,1,0,0,0,0,0,0,0]) + +_addUnit('Hz', '1/s', 'Hertz') +_addUnit('N', 'm*kg/s**2', 'Newton') +_addUnit('Pa', 'N/m**2', 'Pascal') +_addUnit('J', 'N*m', 'Joule') +_addUnit('W', 'J/s', 'Watt') +_addUnit('C', 's*A', 'Coulomb') +_addUnit('V', 'W/A', 'Volt') +_addUnit('F', 'C/V', 'Farad') +_addUnit('ohm', 'V/A', 'Ohm') +_addUnit('S', 'A/V', 'Siemens') +_addUnit('Wb', 'V*s', 'Weber') +_addUnit('T', 'Wb/m**2', 'Tesla') +_addUnit('H', 'Wb/A', 'Henry') +_addUnit('lm', 'cd*sr', 'Lumen') +_addUnit('lx', 'lm/m**2', 'Lux') +_addUnit('Bq', '1/s', 'Becquerel') +_addUnit('Gy', 'J/kg', 'Gray') +_addUnit('Sv', 'J/kg', 'Sievert') + +del _unit_table['kg'] + +for unit in _unit_table.keys(): + _addPrefixed(unit) + +# Fundamental constants +_help.append('Fundamental constants:') + +_unit_table['pi'] = numpy.oldnumeric.pi +_addUnit('c', '299792458.*m/s', 'speed of light') +_addUnit('mu0', '4.e-7*pi*N/A**2', 'permeability of vacuum') +_addUnit('eps0', '1/mu0/c**2', 'permittivity of vacuum') +_addUnit('Grav', '6.67259e-11*m**3/kg/s**2', 'gravitational constant') +_addUnit('hplanck', '6.6260755e-34*J*s', 'Planck constant') +_addUnit('hbar', 'hplanck/(2*pi)', 'Planck constant / 2pi') +_addUnit('e', '1.60217733e-19*C', 'elementary charge') +_addUnit('me', '9.1093897e-31*kg', 'electron mass') +_addUnit('mp', '1.6726231e-27*kg', 'proton mass') +_addUnit('Nav', '6.0221367e23/mol', 'Avogadro number') +_addUnit('k', '1.380658e-23*J/K', 'Boltzmann constant') + +# Time units +_help.append('Time units:') + +_addUnit('min', '60*s', 'minute') +_addUnit('h', '60*min', 'hour') +_addUnit('d', '24*h', 'day') +_addUnit('wk', '7*d', 'week') +_addUnit('yr', '365.25*d', 'year') + +# Length units +_help.append('Length units:') + +_addUnit('inch', '2.54*cm', 'inch') +_addUnit('ft', '12*inch', 'foot') +_addUnit('yd', '3*ft', 'yard') +_addUnit('mi', '5280.*ft', '(British) mile') +_addUnit('nmi', '1852.*m', 'Nautical mile') +_addUnit('Ang', '1.e-10*m', 'Angstrom') +_addUnit('lyr', 'c*yr', 'light year') +_addUnit('Bohr', '4*pi*eps0*hbar**2/me/e**2', 'Bohr radius') + +# Area units +_help.append('Area units:') + +_addUnit('ha', '10000*m**2', 'hectare') +_addUnit('acres', 'mi**2/640', 'acre') +_addUnit('b', '1.e-28*m', 'barn') + +# Volume units +_help.append('Volume units:') + +_addUnit('l', 'dm**3', 'liter') +_addUnit('dl', '0.1*l', 'deci liter') +_addUnit('cl', '0.01*l', 'centi liter') +_addUnit('ml', '0.001*l', 'milli liter') +_addUnit('tsp', '4.92892159375*ml', 'teaspoon') +_addUnit('tbsp', '3*tsp', 'tablespoon') +_addUnit('floz', '2*tbsp', 'fluid ounce') +_addUnit('cup', '8*floz', 'cup') +_addUnit('pt', '16*floz', 'pint') +_addUnit('qt', '2*pt', 'quart') +_addUnit('galUS', '4*qt', 'US gallon') +_addUnit('galUK', '4.54609*l', 'British gallon') + +# Mass units +_help.append('Mass units:') + +_addUnit('amu', '1.6605402e-27*kg', 'atomic mass units') +_addUnit('oz', '28.349523125*g', 'ounce') +_addUnit('lb', '16*oz', 'pound') +_addUnit('ton', '2000*lb', 'ton') + +# Force units +_help.append('Force units:') + +_addUnit('dyn', '1.e-5*N', 'dyne (cgs unit)') + +# Energy units +_help.append('Energy units:') + +_addUnit('erg', '1.e-7*J', 'erg (cgs unit)') +_addUnit('eV', 'e*V', 'electron volt') +_addUnit('Hartree', 'me*e**4/16/pi**2/eps0**2/hbar**2', 'Wavenumbers/inverse cm') +_addUnit('Ken', 'k*K', 'Kelvin as energy unit') +_addUnit('cal', '4.184*J', 'thermochemical calorie') +_addUnit('kcal', '1000*cal', 'thermochemical kilocalorie') +_addUnit('cali', '4.1868*J', 'international calorie') +_addUnit('kcali', '1000*cali', 'international kilocalorie') +_addUnit('Btu', '1055.05585262*J', 'British thermal unit') + +_addPrefixed('eV') + +# Power units +_help.append('Power units:') + +_addUnit('hp', '745.7*W', 'horsepower') + +# Pressure units +_help.append('Pressure units:') + +_addUnit('bar', '1.e5*Pa', 'bar (cgs unit)') +_addUnit('atm', '101325.*Pa', 'standard atmosphere') +_addUnit('torr', 'atm/760', 'torr = mm of mercury') +_addUnit('psi', '6894.75729317*Pa', 'pounds per square inch') + +# Angle units +_help.append('Angle units:') + +_addUnit('deg', 'pi*rad/180', 'degrees') + +_help.append('Temperature units:') +# Temperature units -- can't use the 'eval' trick that _addUnit provides +# for degC and degF because you can't add units +kelvin = _findUnit ('K') +_addUnit ('degR', '(5./9.)*K', 'degrees Rankine') +_addUnit ('degC', PhysicalUnit (None, 1.0, kelvin.powers, 273.15), + 'degrees Celcius') +_addUnit ('degF', PhysicalUnit (None, 5./9., kelvin.powers, 459.67), + 'degree Fahrenheit') +del kelvin + + +def description(): + """Return a string describing all available units.""" + s = '' # collector for description text + for entry in _help: + if isinstance(entry, basestring): + # headline for new section + s += '\n' + entry + '\n' + elif isinstance(entry, tuple): + name, comment, unit = entry + s += '%-8s %-26s %s\n' % (name, comment, unit) + else: + # impossible + raise TypeError, 'wrong construction of _help list' + return s + +# add the description of the units to the module's doc string: +__doc__ += '\n' + description() + +# Some demonstration code. Run with "python -i PhysicalQuantities.py" +# to have this available. + +if __name__ == '__main__': + +# from Scientific.N import * + l = PhysicalQuantity(10., 'm... [truncated message content] |