|
From: <ah...@us...> - 2011-11-29 09:19:18
|
Revision: 705
http://pyphant.svn.sourceforge.net/pyphant/?rev=705&view=rev
Author: aheld84
Date: 2011-11-29 09:19:11 +0000 (Tue, 29 Nov 2011)
Log Message:
-----------
Merge branch 'master' into svn-trunk
* master:
Cosm: Cleaned up code
Bugfix: Gravitational constant 'Grav' of FMFversion 1.0 is correctly interpreted.
Refactoring ParseQuantities: Explicitely checking for changed units has the disadvantage to fail on combined units.
Refactoring str2unit: The function has been refactured in order to fix some bugs, but this is just a work around, because other bugs keep crawling out of their holes.
ParseQuantities: Bugfix, reading FMF 1.0 does not accidentially convert some values to base units due to floating point accuracy.
ParseQuantity: Refactored str2unit
Modified Paths:
--------------
trunk/src/pyphant/pyphant/quantities/ParseQuantities.py
trunk/src/pyphant/pyphant/tests/TestParseQuantities.py
trunk/src/workers/fmfile/fmfile/tests/TestFMFLoader.py
Modified: trunk/src/pyphant/pyphant/quantities/ParseQuantities.py
===================================================================
--- trunk/src/pyphant/pyphant/quantities/ParseQuantities.py 2011-11-18 15:34:32 UTC (rev 704)
+++ trunk/src/pyphant/pyphant/quantities/ParseQuantities.py 2011-11-29 09:19:11 UTC (rev 705)
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2008-2009, Rectorate of the University of Freiburg
-# Copyright (c) 2009-2010, Andreas W. Liehr (li...@us...)
+# Copyright (c) 2009-2011, Andreas W. Liehr (li...@us...)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
@@ -45,52 +45,70 @@
import logging
_logger = logging.getLogger("pyphant")
-def str2unit(unit,FMFversion='1.1'):
- """The function str2unit returns either a quantity or a float from a given string."""
+def str2unit(unitStr, FMFversion='1.1'):
+ """return float or Quantity instance
+
+ The function str2unit is a factory, which either returns a float
+ or a Quantity instance from a given string.
+ Because the definition of units and physical constants is not unique for
+ FMFversion 1.0 (http://arxiv.org/abs/0904.1299) and
+ FMFversion 1.1 (http://dx.doi.org/10.1016/j.cpc.2009.11.014),
+ the result of str2unit() depends on FMFversion.
+ """
+ if FMFversion not in ['1.0', '1.1']:
+ raise ValueError('FMFversion %s not supported.' % (FMFversion, ))
+ # Deal with exceptional units like '%' or 'a.u.'
+ if unitStr.endswith('%'):
+ if len(unitStr.strip()) == 1:
+ return 0.01
+ else:
+ return float(unitStr[:-1]) / 100.0
+ elif unitStr.endswith('a.u.'):
+ if len(unitStr.strip()) == 4:
+ return 1.0
+ else:
+ return float(unitStr[:-4])
# Prepare conversion to quantity
- if unit.startswith('.'):
- unit = '0'+unit
- elif unit.endswith('%'):
+ if unitStr.startswith('.'):
+ unitStr = '0' + unitStr
+ elif not (unitStr[0].isdigit() or unitStr[0] == '-'):
+ unitStr = '1' + unitStr
+ # Convert input to quantity or float
+ unitStr = unitStr.replace('^', '**')
+ try: #FMFversion == '1.1'
+ unit = Quantity(unitStr.encode('utf-8'))
+ except:
+ unit = None
+ if FMFversion == '1.0':
try:
- unit = float(unit[:-1])/100.0
- except:
- unit = 0.01
- elif unit.endswith('a.u.'):
+ unit1_0 = PhysicalQuantity(unitStr.encode('utf-8'))
+ unit1_1 = Quantity(str(unit1_0.inBaseUnits()))
+ except:
+ unit1_1 = None
+ if isinstance(unit1_1, Quantity): # Unit exists in 1.0
+ if isinstance(unit, Quantity): # Unit also exists in 1.1
+ if unit.isCompatible(unit1_1.unit):
+ # Interpretation of unit has not changed
+ unit = unit1_1.inUnitsOf(unit.unit)
+ else:
+ unit = unit1_1
+ _logger.warn('Usage of old unit "%s" required '
+ 'conversion to base units.' % (unitStr, ))
+ else:
+ unit = unit1_1
+ _logger.warn('Usage of old unit "%s" required '
+ 'conversion to base units.' % (unitStr, ))
+ if unit is None:
try:
- unit = float(unit[:-4])
+ if 'j' in unitStr:
+ unit = complex(unitStr)
+ else:
+ unit = float(unitStr)
except:
- unit = 1.0
- elif not (unit[0].isdigit() or unit[0]=='-'):
- unit = '1'+unit
- # Convert input to quantity or float
- if FMFversion not in ['1.0','1.1']:
- raise ValueError, 'FMFversion %s not supported.' % FMFversion
- else:
- try:
- unit = unit.replace('^', '**')
- if FMFversion=='1.1':
- unit = Quantity(unit.encode('utf-8'))
- elif FMFversion=='1.0':
- unit1_0 = PhysicalQuantity(unit.encode('utf-8'))
- unit = Quantity(str(unit1_0.inBaseUnits()))
- try:
- unit_new = Quantity(str(unit1_0))
- if unit_new == unit:
- unit = unit_new
- else:
- _logger.warn('Usage of old unit "%s" required '
- 'conversion to base units.' % unit1_0)
- except:
- _logger.warn('Usage of old unit "%s" required '
- 'conversion to base units.' % unit1_0)
- except Exception, e:
- try:
- unit = float(unit)
- except:
- raise e
+ raise ValueError("Unit %s cannot be interpreted." % (unitStr, ))
return unit
-def parseQuantity(value,FMFversion='1.1'):
+def parseQuantity(value, FMFversion='1.1'):
import re
pm = re.compile(ur"(?:\\pm|\+-|\+/-)")
try:
@@ -106,36 +124,39 @@
value = str2unit(value,FMFversion)
if error != None:
if error.endswith('%'):
- error = value*float(error[:-1])/100.0
+ error = value * float(error[:-1]) / 100.0
else:
try:
- error = float(error)*unit
+ error = float(error) * unit
except:
- error = str2unit(error,FMFversion)
+ error = str2unit(error, FMFversion)
return value, error
-def parseVariable(oldVal,FMFversion='1.1'):
+def parseVariable(oldVal, FMFversion='1.1'):
shortname, value = tuple([s.strip() for s in oldVal.split('=')])
- value, error = parseQuantity(value,FMFversion)
+ value, error = parseQuantity(value, FMFversion)
return (shortname, value, error)
-def parseDateTime(value,FMFversion='1.1'):
+def parseDateTime(value, FMFversion='1.1'):
"""
>>>parseDateTime('2004-08-21 12:00:00+-12hr')
- (Quantity(731814.5,'d'), Quantity(0.5,'d'))
+ (Quantity(731814.5, 'd'), Quantity(0.5, 'd'))
>>>parseDateTime('2004-08-21 12:00:00')
- (Quantity(731814.5,'d'), None)
+ (Quantity(731814.5, 'd'), None)
"""
datetimeWithError = value.split('+-')
- if len(datetimeWithError)==2:
+ if len(datetimeWithError) == 2:
datetime = mx.DateTime.ISO.ParseAny(datetimeWithError[0])
- uncertainty = parseQuantity(datetimeWithError[1],FMFversion)[0]
+ uncertainty = parseQuantity(datetimeWithError[1], FMFversion)[0]
if uncertainty.isCompatible('h'):
- _logger.warning("The uncertainty of timestamp %s has the unit 'h', which is deprecated. The correct abbreviation for hour is 'hr'." % value)
- uncertainty = uncertainty*Quantity('1hr/h')
+ _logger.warning(
+ "The uncertainty of timestamp %s has the unit 'h', "
+ "which is deprecated. "
+ "The correct abbreviation for hour is 'hr'." % (value, ))
+ uncertainty = uncertainty * Quantity('1hr/h')
error = uncertainty.inUnitsOf('d')
else:
datetime = mx.DateTime.ISO.ParseAny(value)
error = None
- days,seconds = datetime.absvalues()
- return (Quantity(days,'d')+Quantity(seconds,'s'),error)
+ days, seconds = datetime.absvalues()
+ return (Quantity(days, 'd') + Quantity(seconds, 's'), error)
Modified: trunk/src/pyphant/pyphant/tests/TestParseQuantities.py
===================================================================
--- trunk/src/pyphant/pyphant/tests/TestParseQuantities.py 2011-11-18 15:34:32 UTC (rev 704)
+++ trunk/src/pyphant/pyphant/tests/TestParseQuantities.py 2011-11-29 09:19:11 UTC (rev 705)
@@ -2,7 +2,7 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2009, Rectorate of the University of Freiburg
-# Copyright (c) 2009-2010, Andreas W. Liehr (li...@us...)
+# Copyright (c) 2009-2011, Andreas W. Liehr (li...@us...)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
@@ -35,54 +35,86 @@
import pkg_resources
pkg_resources.require('pyphant')
-
-import unittest, numpy
+import unittest
from pyphant.quantities.ParseQuantities import parseDateTime,str2unit
from pyphant.quantities import Quantity
-"""
+
+
+class TestParseDateTime(unittest.TestCase):
+ """
>>>parseDateTime('2004-08-21 12:00:00+-12hr')
- (Quantity(731814.5,'d'), Quantity(0.5,'d'))
+ (Quantity(731814.5, 'd'), Quantity(0.5, 'd'))
>>>parseDateTime('2004-08-21 12:00:00')
- (Quantity(731814.5,'d'), None)
-"""
-class TestParseDateTime(unittest.TestCase):
+ (Quantity(731814.5, 'd'), None)
+ """
+
def testWithError(self):
self.assertEqual(parseDateTime('2004-08-21 12:00:00+-12hr'),
- (Quantity(731814.5,'d'), Quantity(0.5,'d'))
+ (Quantity(731814.5, 'd'), Quantity(0.5, 'd'))
)
def testWithErrorOldDeprecatedAbbreviation(self):
self.assertEqual(parseDateTime('2004-08-21 12:00:00+-12h'),
- (Quantity(731814.5,'d'), Quantity(0.5,'d'))
+ (Quantity(731814.5, 'd'), Quantity(0.5, 'd'))
)
+
class TestStr2unit(unittest.TestCase):
"""Test the correct conversion of strings to quantities or floats."""
+
+ def setUp(self):
+ self.inputDict = {'complexJ':'1.0j', 'Joule':'1.0J'}
+
def testSimpleQuantity(self):
- """The the conversion of a simple textual quantity specification to a quantity object."""
+ """
+ The the conversion of a simple textual quantity specification
+ to a quantity object.
+ """
expected = Quantity('1V')
result = str2unit('1V')
- self.assertEqual(expected,result)
+ self.assertEqual(expected, result)
- def setUp(self):
- self.inputDict = {'complexJ':'1.0j','Joule':'1.0J'}
+ def testComplexNumber(self):
+ """
+ Complex numbers have to be denoted by small 'j',
+ in oder to discriminate them from Joule.
+ """
+ result = str2unit(self.inputDict['complexJ'])
+ self.assertEqual(result, complex(self.inputDict['complexJ']))
def testJouleValue(self):
"""Physical quantities with unit Joule are indicated by 'J'."""
result = str2unit(self.inputDict['Joule'])
- self.assertEqual(result,Quantity(self.inputDict['Joule']))
+ self.assertEqual(result, Quantity(self.inputDict['Joule']))
def testHourPlanck(self):
- """In FMF 1.0 unit 'h' denotes hours, while in FMF 1.1 'h' denotes the Planck constant."""
+ """
+ In FMF 1.0 unit 'h' denotes hours,
+ while in FMF 1.1 'h' denotes the Planck constant.
+ """
result = str2unit('1h')
- self.assertEqual(result,Quantity('6.62606896e-34 J*s'))
- result = str2unit('1h',FMFversion='1.0')
- self.assertEqual(result,Quantity('3600s'))
+ self.assertEqual(result, Quantity('6.62606896e-34 J*s'))
+ result = str2unit('1h', FMFversion='1.0')
+ self.assertEqual(result, Quantity('3600s'))
+ def testFloatAccuracy(self):
+ result = str2unit('16.8 mm', FMFversion='1.0')
+ diff = result - Quantity('16.8 mm')
+ self.assertEqual(abs(diff.value) < 2e-14,True)
+ result = str2unit('16.8 mm', FMFversion='1.0')
+ diff = Quantity('16.8 mm')
+ self.assertEqual(result, diff)
+
+ def testGravitationalConstant(self):
+ result = str2unit("1 Grav", FMFversion="1.0")
+ self.assertEqual(result, str2unit('6.67259e-11 m**3/kg/s**2'))
+
+
if __name__ == "__main__":
import sys
if len(sys.argv) == 1:
unittest.main()
else:
- suite = unittest.TestLoader().loadTestsFromTestCase(eval(sys.argv[1:][0]))
+ suite = unittest.TestLoader().loadTestsFromTestCase(
+ eval(sys.argv[1:][0]))
unittest.TextTestRunner().run(suite)
Modified: trunk/src/workers/fmfile/fmfile/tests/TestFMFLoader.py
===================================================================
--- trunk/src/workers/fmfile/fmfile/tests/TestFMFLoader.py 2011-11-18 15:34:32 UTC (rev 704)
+++ trunk/src/workers/fmfile/fmfile/tests/TestFMFLoader.py 2011-11-29 09:19:11 UTC (rev 705)
@@ -1,8 +1,8 @@
-#!/usr/bin/env python2.5
+#!/usr/bin/env python2.6
# -*- coding: utf-8 -*-
# Copyright (c) 2008-2009, Rectorate of the University of Freiburg
-# Copyright (c) 2009-2010, Andreas W. Liehr (li...@us...)
+# Copyright (c) 2009-2011, Andreas W. Liehr (li...@us...)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
@@ -45,15 +45,22 @@
from pyphant.quantities.ParseQuantities import str2unit
from copy import deepcopy
+#Estimate floating point accuracy
+ACCURACY = 1.0 -0.1 -0.1 -0.1 -0.1 -0.1 -0.1 -0.1 -0.1 -0.1 -0.
+
class FieldContainerCondenseDim(unittest.TestCase):
def setUp(self):
self.x = numpy.linspace(0,0.9,10)
m = numpy.meshgrid(self.x, self.x*5)
self.valid = numpy.tile(self.x, (10,1))
- self.invalid = [ a.squeeze() for a in numpy.vsplit(m[0]+m[1], len(m[0])) ]
+ self.invalid = [
+ a.squeeze() for a in numpy.vsplit(m[0] + m[1], len(m[0]))
+ ]
def testInvalid(self):
- self.assertRaises(AssertionError, FMFLoader.checkAndCondense, self.invalid)
+ self.assertRaises(
+ AssertionError, FMFLoader.checkAndCondense, self.invalid
+ )
def testValid(self):
result = FMFLoader.checkAndCondense(self.valid)
@@ -61,75 +68,100 @@
class TestColumn2FieldContainer(unittest.TestCase):
def testStrings(self):
- column = ['Hello','World']
- result = FMFLoader.column2FieldContainer('simple string',column)
- expectedResult = FieldContainer(numpy.array(column),longname='simple string')
- assertEqual(result,expectedResult)
+ column = ['Hello', 'World']
+ result = FMFLoader.column2FieldContainer('simple string', column)
+ expectedResult = FieldContainer(
+ numpy.array(column), longname='simple string'
+ )
+ assertEqual(result, expectedResult)
def testListofStrings(self):
- column = ['World',['Hello', 'World'],'World']
- result = FMFLoader.column2FieldContainer('simple string',column)
- expectedResult = FieldContainer(numpy.array(['World','Hello, World','World']),longname='simple string')
- assertEqual(result,expectedResult)
+ column = ['World', ['Hello', 'World'], 'World']
+ result = FMFLoader.column2FieldContainer('simple string', column)
+ expectedResult = FieldContainer(
+ numpy.array(['World', 'Hello, World', 'World']),
+ longname='simple string'
+ )
+ assertEqual(result, expectedResult)
def testListofStrings2(self):
- column = [['Hello', 'World'],'World']
- result = FMFLoader.column2FieldContainer('simple string',column)
- expectedResult = FieldContainer(numpy.array(['Hello, World','World']),longname='simple string')
- assertEqual(result,expectedResult)
+ column = [['Hello', 'World'], 'World']
+ result = FMFLoader.column2FieldContainer('simple string', column)
+ expectedResult = FieldContainer(
+ numpy.array(['Hello, World', 'World']), longname='simple string'
+ )
+ assertEqual(result, expectedResult)
def testVariable(self):
- column = [('T',Quantity('22.4 degC'),Quantity('0.5 degC')),
- ('T',Quantity('11.2 degC'),Quantity('0.5 degC'))
- ]
- result = FMFLoader.column2FieldContainer('temperature',column)
- expectedResult = FieldContainer(numpy.array([22.4,11.2]),error=numpy.array([0.5,0.5]),
- mask = numpy.array([False,False]),
- unit='1 degC',longname='temperature',shortname='T')
- assertEqual(result,expectedResult)
+ column = [
+ ('T', Quantity('22.4 degC'), Quantity('0.5 degC')),
+ ('T', Quantity('11.2 degC'), Quantity('0.5 degC'))
+ ]
+ result = FMFLoader.column2FieldContainer('temperature', column)
+ expectedResult = FieldContainer(
+ numpy.array([22.4, 11.2]) ,error=numpy.array([0.5, 0.5]),
+ mask=numpy.array([False, False]),
+ unit='1 degC', longname='temperature', shortname='T'
+ )
+ assertEqual(result, expectedResult)
def testVariableWithNaN(self):
- column = [('T',Quantity('22.4 degC'),Quantity('0.5 degC')),
- ('T',Quantity('11.2 degC'),None)
- ]
- result = FMFLoader.column2FieldContainer('temperature',column)
- expectedResult = FieldContainer(numpy.array([22.4,11.2]),error=numpy.array([0.5,0.0]),
- mask = numpy.array([False,False]),
- unit='1 degC',longname='temperature',shortname='T')
- assertEqual(result,expectedResult)
+ column = [
+ ('T', Quantity('22.4 degC'), Quantity('0.5 degC')),
+ ('T', Quantity('11.2 degC'), None)
+ ]
+ result = FMFLoader.column2FieldContainer('temperature', column)
+ expectedResult = FieldContainer(
+ numpy.array([22.4, 11.2]), error=numpy.array([0.5, 0.0]),
+ mask = numpy.array([False, False]),
+ unit='1 degC', longname='temperature', shortname='T'
+ )
+ assertEqual(result, expectedResult)
def testVariableFirstNaN(self):
- column = [('T','NaN',Quantity('0.5 degC')),
- ('T',Quantity('11.2 degC'),None)
- ]
- result = FMFLoader.column2FieldContainer('temperature',column)
- expectedResult = FieldContainer(numpy.array([numpy.NaN,11.2]),error=numpy.array([0.5,0.0]),
- mask = numpy.array([True,False]),
- unit='1 degC',longname='temperature',shortname='T')
- assertEqual(result,expectedResult)
+ column = [
+ ('T', 'NaN', Quantity('0.5 degC')),
+ ('T', Quantity('11.2 degC'), None)
+ ]
+ result = FMFLoader.column2FieldContainer('temperature', column)
+ expectedResult = FieldContainer(
+ numpy.array([numpy.NaN, 11.2]), error=numpy.array([0.5, 0.0]),
+ mask = numpy.array([True, False]),
+ unit='1 degC', longname='temperature', shortname='T')
+ assertEqual(result, expectedResult)
class TestDiscriminatingJouleAndImaginary(unittest.TestCase):
- """In order to discriminate between an imaginary number and unit Joule, imaginary numbers have to be indicated only by a minor capital 'j', while a major capital 'J' indicates the unit Joule.
"""
+ In order to discriminate between an imaginary number and unit Joule,
+ imaginary numbers have to be indicated only by a minor capital 'j',
+ while a major capital 'J' indicates the unit Joule.
+ """
def setUp(self):
- self.inputDict = {'complexJ':'1.0j','Joule':'1.0J'}
+ self.inputDict = {'complexJ':'1.0j', 'Joule':'1.0J'}
- def testComplexVale(self):
+ def testComplexValue(self):
"""Imaginary numbers are indicated by 'j'."""
result = FMFLoader.item2value(self.inputDict['complexJ'])
- self.assertEqual(result,complex(self.inputDict['complexJ']))
+ self.assertEqual(result, (complex(self.inputDict['complexJ']), None))
def testJouleValue1_1(self):
"""Physical quantities with unit Joule are indicated by 'J'."""
result = FMFLoader.item2value(self.inputDict['Joule'])
- self.assertEqual(result,(Quantity(self.inputDict['Joule']),None))
+ self.assertEqual(result, (Quantity(self.inputDict['Joule']), None))
def testJouleValue1_0(self):
"""Physical quantities with unit Joule are indicated by 'J'."""
- result = FMFLoader.item2value(self.inputDict['Joule'],FMFversion='1.0')
- self.assertEqual(result,(Quantity(self.inputDict['Joule']),None))
+ result = FMFLoader.item2value(
+ self.inputDict['Joule'], FMFversion='1.0'
+ )
+ self.assertEqual(result, (Quantity(self.inputDict['Joule']), None))
class TestFMFversion1_0(unittest.TestCase):
+ def almostEqual(self, a, b):
+ diff = a - b
+ mean = 0.5 * (a + b)
+ self.assertTrue(abs(diff / mean) < ACCURACY)
+
def setUp(self):
self.FMFinput = """# -*- fmf-version: 1.0; coding: utf-8 -*-
[*reference]
@@ -178,31 +210,84 @@
2 1+1j 2.
"""
def testReadSingleFile(self):
- """Test the correct interpretation of physical constants as definied in FMF version 1.0."""
- consts = FMFLoader.readSingleFile(self.FMFinput,"testReadSingleFile")[0].attributes['Mathematical and Physical Constants']
- self.assertEqual(consts[u'Speed of light'][1],str2unit("1 c",FMFversion="1.0"))
- self.assertEqual(consts[u'Speed of light'][1],str2unit("1 c"))
- self.assertEqual(consts[u'Permeability of vacuum'][1],str2unit("1 mu0",FMFversion="1.0"))
- self.assertEqual(consts[u'Permittivity of vacuum'][1],str2unit("1 eps0",FMFversion="1.0"))
- self.assertEqual(consts[u'Gravitational constant'][1],str2unit("1 Grav",FMFversion="1.0"))
- self.assertEqual(consts[u'Planck constant'][1],str2unit("1 hplanck",FMFversion="1.0"))
- self.assertEqual(consts[u'Planck constant / 2pi'][1],str2unit("1 hbar",FMFversion="1.0"))
- self.assertEqual(consts[u'Elementary charge'][1],str2unit("1 e",FMFversion="1.0"))
- self.assertNotEqual(consts[u'Elementary charge'][1],str2unit("1 e"),
- "Elementary charge has been adapted to new CODATA recommendations.")
- self.assertEqual(consts[u'Electron mass'][1],str2unit("1 me",FMFversion="1.0"))
- self.assertNotEqual(consts[u'Electron mass'][1],str2unit("1 me"),
- "Electron mass has been adapted to new CODATA recommendations.")
- self.assertEqual(consts[u'Proton mass'][1],str2unit("1 mp",FMFversion="1.0"))
- self.assertNotEqual(consts[u'Proton mass'][1],str2unit("1 mp"),
- "Proton mass has been adapted to new CODATA recommendations.")
- self.assertEqual(consts[u'Avogadro number'][1],str2unit("1 Nav",FMFversion="1.0"))
- self.assertEqual(consts[u'Boltzmann constant'][1],str2unit("1 k",FMFversion="1.0"))
- consts = FMFLoader.readSingleFile(self.FMFinput,"testReadSingleFile")[0].attributes['Additional constants changed from FMF version 1.0 to 1.1']
- self.assertEqual(consts[u'Parsec'][1],str2unit("1 pc",FMFversion="1.0"))
- self.assertEqual(consts[u'US gallon'][1],str2unit("1 galUS",FMFversion="1.0"))
- self.assertEqual(consts[u'Atomic mass units'][1],str2unit("1 amu",FMFversion="1.0"))
+ """
+ Test the correct interpretation of physical constants
+ as definied in FMF version 1.0.
+ """
+ consts = FMFLoader.readSingleFile(
+ self.FMFinput,
+ "testReadSingleFile")[0].attributes[
+ 'Mathematical and Physical Constants'
+ ]
+ self.assertEqual(
+ consts[u'Speed of light'][1], str2unit("1 c", FMFversion="1.0")
+ )
+ self.assertEqual(consts[u'Speed of light'][1], str2unit("1 c"))
+ self.assertEqual(
+ consts[u'Permeability of vacuum'][1],
+ str2unit("1 mu0", FMFversion="1.0")
+ )
+ self.assertEqual(
+ consts[u'Permittivity of vacuum'][1],
+ str2unit("1 eps0", FMFversion="1.0")
+ )
+ self.assertEqual(
+ consts[u'Gravitational constant'][1],
+ str2unit("1 Grav", FMFversion="1.0")
+ )
+ self.assertTrue(
+ consts[u'Planck constant'][1],
+ str2unit("1 hplanck", FMFversion="1.0")
+ )
+ self.almostEqual(
+ consts[u'Planck constant / 2pi'][1],
+ str2unit("1 hbar", FMFversion="1.0")
+ )
+ self.almostEqual(
+ consts[u'Elementary charge'][1],
+ str2unit("1 e", FMFversion="1.0")
+ )
+ self.assertNotEqual(
+ consts[u'Elementary charge'][1], str2unit("1 e"),
+ "Elementary charge has been adapted to new CODATA recommendations."
+ )
+ self.assertEqual(
+ consts[u'Electron mass'][1], str2unit("1 me", FMFversion="1.0")
+ )
+ self.assertNotEqual(
+ consts[u'Electron mass'][1], str2unit("1 me"),
+ "Electron mass has been adapted to new CODATA recommendations."
+ )
+ self.assertEqual(
+ consts[u'Proton mass'][1], str2unit("1 mp", FMFversion="1.0")
+ )
+ self.assertNotEqual(
+ consts[u'Proton mass'][1], str2unit("1 mp"),
+ "Proton mass has been adapted to new CODATA recommendations."
+ )
+ self.assertEqual(
+ consts[u'Avogadro number'][1], str2unit("1 Nav", FMFversion="1.0")
+ )
+ self.assertEqual(
+ consts[u'Boltzmann constant'][1], str2unit("1 k", FMFversion="1.0")
+ )
+ consts = FMFLoader.readSingleFile(
+ self.FMFinput,
+ "testReadSingleFile")[0].attributes[
+ 'Additional constants changed from FMF version 1.0 to 1.1'
+ ]
+ self.almostEqual(
+ consts[u'Parsec'][1], str2unit("1 pc", FMFversion="1.0")
+ )
+ self.almostEqual(
+ consts[u'US gallon'][1], str2unit("1 galUS", FMFversion="1.0")
+ )
+ self.assertEqual(
+ consts[u'Atomic mass units'][1],
+ str2unit("1 amu", FMFversion="1.0")
+ )
+
class TestFMFversion1_1(unittest.TestCase):
def setUp(self):
self.FMFinput = """# -*- fmf-version: 1.1; coding: utf-8 -*-
@@ -255,26 +340,76 @@
2 1+1j 2.
"""
def testReadSingleFile(self):
- """Test the correct interpretation of physical constants as definied in FMF version 1.1."""
- consts = FMFLoader.readSingleFile(self.FMFinput,"testReadSingleFile")[0].attributes['Mathematical and Physical Constants']
- self.assertEqual(consts[u'Speed of light'][1],str2unit("1 c",FMFversion="1.1"))
- self.assertEqual(consts[u'Permeability of vacuum'][1],str2unit("1 mu0",FMFversion="1.1"),
- 'The values differ by %s.' % (consts[u'Permeability of vacuum'][1]-str2unit("1 mu0",FMFversion="1.1"),))
- self.assertEqual(consts[u'Permittivity of vacuum'][1],str2unit("1 eps0",FMFversion="1.1"))
- self.assertEqual(consts[u'Gravitational constant'][1],str2unit("1 G",FMFversion="1.1"))
- self.assertEqual(consts[u'Planck constant'][1],str2unit("1 h",FMFversion="1.1"))
- self.assertEqual(consts[u'Planck constant / 2pi'][1],str2unit("1 hbar",FMFversion="1.1"))
- self.assertEqual(consts[u'Elementary charge'][1],str2unit("1 e",FMFversion="1.1"),
- 'The elements %s and %s do not match.' % (consts[u'Elementary charge'][1],str2unit("1 e",FMFversion="1.1")))
- self.assertEqual(consts[u'Electron mass'][1],str2unit("1 me",FMFversion="1.1"))
- self.assertEqual(consts[u'Proton mass'][1],str2unit("1 mp",FMFversion="1.1"))
- self.assertEqual(consts[u'Avogadro number'][1],str2unit("1 NA",FMFversion="1.1"))
- self.assertEqual(consts[u'Boltzmann constant'][1],str2unit("1 k",FMFversion="1.1"))
- self.assertEqual(consts[u'Rydberg constant'][1],str2unit("1 Ryd",FMFversion="1.1"))
- consts = FMFLoader.readSingleFile(self.FMFinput,"testReadSingleFile")[0].attributes['Additional constants changed from FMF version 1.0 to 1.1']
- self.assertEqual(consts[u'Parsec'][1],str2unit("1 pc",FMFversion="1.1"))
- self.assertEqual(consts[u'US gallon'][1],str2unit("1 galUS",FMFversion="1.1"))
- self.assertEqual(consts[u'Atomic mass units'][1],str2unit("1 u",FMFversion="1.1"))
+ """
+ Test the correct interpretation of physical constants
+ as definied in FMF version 1.1.
+ """
+ consts = FMFLoader.readSingleFile(
+ self.FMFinput, "testReadSingleFile")[0].attributes[
+ 'Mathematical and Physical Constants'
+ ]
+ self.assertEqual(
+ consts[u'Speed of light'][1], str2unit("1 c", FMFversion="1.1")
+ )
+ self.assertEqual(
+ consts[u'Permeability of vacuum'][1],
+ str2unit("1 mu0", FMFversion="1.1"),
+ 'The values differ by %s.' % (
+ consts[u'Permeability of vacuum'][1] -\
+ str2unit("1 mu0", FMFversion="1.1"),
+ )
+ )
+ self.assertEqual(
+ consts[u'Permittivity of vacuum'][1],
+ str2unit("1 eps0", FMFversion="1.1")
+ )
+ self.assertEqual(
+ consts[u'Gravitational constant'][1],
+ str2unit("1 G", FMFversion="1.1")
+ )
+ self.assertEqual(
+ consts[u'Planck constant'][1],
+ str2unit("1 h", FMFversion="1.1")
+ )
+ self.assertEqual(
+ consts[u'Planck constant / 2pi'][1],
+ str2unit("1 hbar", FMFversion="1.1")
+ )
+ self.assertEqual(
+ consts[u'Elementary charge'][1], str2unit("1 e",FMFversion="1.1"),
+ 'The elements %s and %s do not match.' % (
+ consts[u'Elementary charge'][1],
+ str2unit("1 e", FMFversion="1.1")
+ )
+ )
+ self.assertEqual(
+ consts[u'Electron mass'][1], str2unit("1 me", FMFversion="1.1")
+ )
+ self.assertEqual(
+ consts[u'Proton mass'][1], str2unit("1 mp", FMFversion="1.1")
+ )
+ self.assertEqual(
+ consts[u'Avogadro number'][1], str2unit("1 NA", FMFversion="1.1")
+ )
+ self.assertEqual(
+ consts[u'Boltzmann constant'][1], str2unit("1 k",FMFversion="1.1")
+ )
+ self.assertEqual(
+ consts[u'Rydberg constant'][1], str2unit("1 Ryd", FMFversion="1.1")
+ )
+ consts = FMFLoader.readSingleFile(
+ self.FMFinput, "testReadSingleFile")[0].attributes[
+ 'Additional constants changed from FMF version 1.0 to 1.1'
+ ]
+ self.assertEqual(
+ consts[u'Parsec'][1], str2unit("1 pc", FMFversion="1.1")
+ )
+ self.assertEqual(
+ consts[u'US gallon'][1], str2unit("1 galUS", FMFversion="1.1")
+ )
+ self.assertEqual(
+ consts[u'Atomic mass units'][1], str2unit("1 u", FMFversion="1.1")
+ )
class Emd5ConsistencyTestCase(unittest.TestCase):
@@ -379,7 +514,6 @@
self.assertEqual(result.attributes['*reference']['title'], title)
-
if __name__ == "__main__":
import sys
import logging
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|