Exemple #1
0
 def loadImageAsGreyScale(self, subscriber=0):
     im = Image.open(self.paramFilename.value)
     if im.mode == "I;16":
         im = im.convert("I")
         data = scipy.misc.fromimage(im).astype("int16")
     else:
         data = scipy.misc.fromimage(im, flatten=True)
     Ny, Nx = data.shape
     xUnit = Quantity(self.paramXScale.value.encode('utf-8'))
     xAxis =  DataContainer.FieldContainer(scipy.linspace(0.0, xUnit.value,
                                                          Nx, True),
                                           xUnit / xUnit.value,
                                           longname = 'x-coordinate',
                                           shortname = 'x')
     if self.paramYScale.value == 'link2X':
         yUnit = xUnit * float(Ny) / Nx
     else:
         yUnit = Quantity(self.paramYScale.value.encode('utf-8'))
     yAxis =  DataContainer.FieldContainer(scipy.linspace(0.0, yUnit.value,
                                                          Ny, True),
                                           yUnit / yUnit.value,
                                           longname = 'y-coordinate',
                                           shortname = 'y')
     try:
         FieldUnit = Quantity(self.paramFieldUnit.value.encode('utf-8'))
     except AttributeError:
         FieldUnit = self.paramFieldUnit.value
     result = DataContainer.FieldContainer(data,
                                           FieldUnit,
                                           longname="Image",
                                           shortname="I",
                                           dimensions=[yAxis, xAxis])
     result.seal()
     return result
Exemple #2
0
 def setUp(self):
     self.arrays = []
     self.arrays.append([1, 2, 3])
     self.arrays.append([1.9, -2.2, 3.4])
     self.matrix = [[3.8, 4.5], [-3.4, 546.6]]
     self.shapes = []
     self.shapes.append((5, np.array([6])))
     self.shapes.append((5, np.array([6.])))
     self.shapes.append(((3, 2), np.array([6])))
     self.shapes.append(((3, 2), np.array([6.])))
     self.angles = []
     self.angles.append(Quantity('1.4 rad'))
     self.angles.append(Quantity('2 rad'))
     self.angles.append(Quantity('30 deg'))
     self.angles.append(Quantity('-40 deg'))
     self.length = Quantity('5.3 m')
     self.phyunit = PhysicalUnit('m', 1., [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
     self.phyunit **= 5
     self.exps = [
         0, 1, 2, 1. / 5, 1. / (5. + 1e-12), 1. / (5. - 1e-12),
         -1. / (5. + 1e-12), -1. / (5. - 1e-12)
     ]
     self.badexps = [
         2., 1. / 6, 1. / (5. + 1e-8), 1. / (5. - 1e-8), -1. / (5. + 1e-8),
         -1. / (5. - 1e-8)
     ]
     self.values = [0, 1, 0., 1e-10, 4.049, 10.05, 3 - 1e-10]
     self.values += [-1, -1e-10, -4.049, -10.05, -(3 - 1e-10)]
Exemple #3
0
 def __init__(self, data, unit=1, error=None, mask=None,
              dimensions=None, longname=u"Sampled Field",
              shortname=u"\\Psi", attributes=None, rescale=False):
     DataContainer.__init__(self, longname, shortname, attributes)
     self.data = data
     self.mask = mask
     try:
         if isinstance(unit, (str, unicode)):
             unit = unit.replace('^', '**')
         if isinstance(unit, unicode):
             unit = unit.encode('utf-8')
         self.unit = Quantity(unit)
     except:
         try:
             self.unit = Quantity("1"+unit)
         except:
             self.unit = unit
     self.error = error
     if dimensions != None:
         self.dimensions = dimensions
     else:
         N = len(data.shape)-1
         self.dimensions = [generateIndex(N-i,n) for i,n in enumerate(data.shape)]
     if rescale:
         self.rescale()
         for dim in self._dimensions:
             dim.rescale()
     assert self.isValid()
Exemple #4
0
 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)
Exemple #5
0
    def setUp(self):
        super(SampleContainerInSampleContainerTestCase, self).setUp()
        sample1 = SampleContainer([self.dependent, self.field],
                                  longname='First Sample',
                                  shortname='X',
                                  attributes=copy.copy(self.attributes).update(
                                      {'isSample': 'It seems so.'}))
        self.independent2 = FieldContainer(
            0.3 * numpy.linspace(0, 1, self.testData.shape[0] * 10),
            longname='independent variable',
            shortname='x',
            unit=Quantity('1 mg'),
            attributes=copy.copy(self.attributes).update({'independent':
                                                          True}))
        self.dependent2 = FieldContainer(9.81 * self.independent2.data,
                                         dimensions=[self.independent2],
                                         longname='dependent variable',
                                         shortname='f',
                                         unit=Quantity('9.81 nN'),
                                         attributes=copy.copy(
                                             self.attributes).update(
                                                 {'independent': False}))

        sample2 = SampleContainer([self.dependent2, self.independent2],
                                  longname='Second Sample',
                                  shortname='Y',
                                  attributes=copy.copy(self.attributes).update(
                                      {'sample Nr.': 2}))
        self.sample = SampleContainer([sample1, sample2],
                                      longname='SampleContainer with Samples',
                                      shortname='(X,Y)',
                                      attributes=copy.copy(
                                          self.attributes).update(
                                              {'isSample': 'It seems so.'}))
        self.sample.seal()
Exemple #6
0
 def testRatiosUpToTenPercentError(self):
     delta = .1
     from ImageProcessing.CoverageWorker import CoverageWorker
     from ImageProcessing import FEATURE_COLOR, BACKGROUND_COLOR
     from pyphant.quantities import Quantity
     cworker = CoverageWorker()
     for rho1Fac in [0.1, 0.25, 0.5, 1.0, 1.5, 2.0, 5.0, 10.0]:
         rho1 = '%s mC / m ** 3' % (3000. * rho1Fac, )
         rho2 = '3 C / m ** 3'
         cworker.paramRho1.value = rho1
         cworker.paramRho2.value = rho2
         rho1 = Quantity(rho1)
         rho2 = Quantity(rho2)
         for ratio in numpy.arange(0.0, 1.01, 0.01):
             cworker.paramW1.value = '%s%%' % (ratio * 100., )
             result = cworker.threshold(self.image)
             self.assertEqual(result.dimensions, self.image.dimensions)
             stuff1 = numpy.where(result.data == FEATURE_COLOR, True,
                                  False).sum()
             stuff2 = numpy.where(result.data == BACKGROUND_COLOR, True,
                                  False).sum()
             self.assertEqual(stuff1 + stuff2, result.data.size)
             stuff1 = (stuff1 * rho1).inUnitsOf('C / m ** 3').value
             stuff2 = (stuff2 * rho2).inUnitsOf('C / m ** 3').value
             actualRatio = stuff1 / (stuff1 + stuff2)
             self.assertTrue(abs(ratio - actualRatio) <= delta)
 def threshold(self, image, subscriber=0):
     th = float(self.paramThreshold.value)
     if self.paramUnit.value.lower() != 'ignore':
         from pyphant.quantities import Quantity, isQuantity
         try:
             unit = float(self.paramUnit.value)
             assert not isQuantity(image.unit)
         except ValueError:
             try:
                 unit = Quantity(self.paramUnit.value)
             except TypeError:
                 unit = Quantity(1.0, self.paramUnit.value)
             assert isQuantity(image.unit)
             assert unit.isCompatible(image.unit.unit)
         th *= unit / image.unit
     resultArray = scipy.where(image.data < th,
                               ImageProcessing.FEATURE_COLOR,
                               ImageProcessing.BACKGROUND_COLOR)
     result = DataContainer.FieldContainer(resultArray,
                                           dimensions=copy.deepcopy(
                                               image.dimensions),
                                           longname=u"Binary Image",
                                           shortname=u"B")
     result.seal()
     return result
Exemple #8
0
 def testLoadOneRow(self):
     result = self.load('onerow.fmf')
     t = FieldContainer(numpy.array([1.0]), unit=Quantity('1 s'),
                        shortname='t', longname='time')
     s = FieldContainer(numpy.array([2.0]), unit=Quantity('1 m'),
                        shortname='s', longname='distance')
     self.checkExpected([t, s], result)
Exemple #9
0
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 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:
            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:
            if "j" in unitStr:
                unit = complex(unitStr)
            else:
                unit = float(unitStr)
        except:
            raise ValueError("Unit %s cannot be interpreted." % (unitStr,))
    return unit
Exemple #10
0
 def testNonUniformAxes(self):
     im = np.array(
         [
             [0., 1., 2.],
             [30., 10., 50.],
             [8., 9., 6.],
             [-10., 0., 22.]
             ]
         )
     x = FieldContainer(np.array([1., 10., 200.]), unit=Quantity('1 m'))
     y = FieldContainer(np.array([0., 2., 4., 8.]), unit=Quantity('1 cm'))
     fc = FieldContainer(im, unit=Quantity('5 V'), dimensions=[y, x])
     fc.seal()
     grad_y, grad_x = np.gradient(fc.data)
     grad_y /= np.gradient(y.data).reshape((4, 1))
     grad_x /= np.gradient(x.data).reshape((1, 3))
     grad_y = FieldContainer(
         grad_y, unit=fc.unit / y.unit,
         dimensions=copy.deepcopy(fc.dimensions)
         )
     grad_x = FieldContainer(
         grad_x, unit=fc.unit / x.unit,
         dimensions=copy.deepcopy(fc.dimensions)
         )
     grad_x = grad_x.inUnitsOf(grad_y)
     expected_result = FieldContainer(
         (grad_x.data ** 2 + grad_y.data ** 2) ** 0.5,
         unit=copy.deepcopy(grad_y.unit),
         dimensions=copy.deepcopy(fc.dimensions)
         )
     result = Gradient().gradientWorker(fc)
     self.assertEqual(expected_result, result)
Exemple #11
0
 def setUp(self):
     self.quants = []
     self.quants.append(Quantity("1000 m"))
     self.quants.append(Quantity("1 km"))
     self.quants.append(Quantity("1000.1 m"))
     self.quants.append(0)
     self.quants.append(None)
     self.quants.append(Quantity("1000 s"))
Exemple #12
0
 def testLoadOneRowDep(self):
     result = self.load('onerow_dep.fmf')
     t = FieldContainer(numpy.array([1.0]), unit=Quantity('1 s'),
                        shortname='t', longname='time')
     s = FieldContainer(numpy.array([5.0]), unit=Quantity('1 m'),
                        shortname='s', longname='distance')
     s.dimensions[0] = deepcopy(t)
     self.checkExpected([t, s], result)
Exemple #13
0
 def testHourPlanck(self):
     """
     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'))
Exemple #14
0
def normation(normationStr):
    try:
        unit = Quantity(str(normationStr))
    except:
        try:
            unit = Quantity(1.0, str(normationStr))
        except:
            unit = float(normationStr)
    return unit
Exemple #15
0
 def testUnits(self):
     data = (np.arange(0, 256, .01)).reshape((80, 320))
     image = FieldContainer(data, unit=Quantity('1 mJ'))
     for dim in image.dimensions:
         dim.unit = Quantity('1 cm')
     image.seal()
     gradient = Gradient()
     result = gradient.gradientWorker(image)
     self.assertEqual(result.dimensions, image.dimensions)
     self.assertEqual(result.unit, Quantity('1 mJ / cm'))
Exemple #16
0
 def testVariableFirstNaN(self):
     column = [('T', 'NaN', Quantity('0.5 degC')),
               ('T', Quantity('11.2 degC'), None)]
     result = LoadFMF.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)
Exemple #17
0
 def testVariable(self):
     column = [('T', Quantity('22.4 degC'), Quantity('0.5 degC')),
               ('T', Quantity('11.2 degC'), Quantity('0.5 degC'))]
     result = LoadFMF.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)
Exemple #18
0
    def visit_Str(self, node):
        quantity = Quantity(node.s)

        class QuantityDummy(object):
            pass

        dummy = QuantityDummy()
        dummy.unit = Quantity(1.0, quantity.unit)
        dummy.data = quantity.value
        dummy.dimensions = None
        newName = self.getName(dummy)
        return Name(newName, Load())
Exemple #19
0
 def testUnits(self):
     from ImageProcessing.Gradient import Gradient
     from pyphant.core.DataContainer import FieldContainer
     from pyphant.quantities import Quantity
     data = (numpy.arange(0, 256, .01)).reshape((80, 320))
     image = FieldContainer(data, unit=Quantity('1 mJ'))
     for dim in image.dimensions:
         dim.unit = Quantity('1 cm')
     image.seal()
     gradient = Gradient()
     result = gradient.gradientWorker(image)
     self.assertEqual(result.dimensions, image.dimensions)
     self.assertEqual(result.unit, Quantity('1 mJ / cm'))
Exemple #20
0
    def getDimension(self, axis, length):
        from pyphant.quantities import Quantity
        from pyphant.core.DataContainer import FieldContainer
        import numpy
        delta = Quantity(self.getParam('d' + axis).value)
        start = Quantity(self.getParam('start' + axis).value)

        start = start.inUnitsOf(delta.unit)
        data = start.value + numpy.arange(0, length, dtype=float) * delta.value
        dim = FieldContainer(data,
                             unit=Quantity(1.0, delta.unit),
                             shortname=axis,
                             longname='%s-Axis' % (axis.upper(), ))
        return dim
Exemple #21
0
 def loadImageAsGreyScale(self, subscriber=0):
     import os
     import re
     from scipy.misc import imread
     import numpy
     from pyphant.core.DataContainer import FieldContainer
     from pyphant.quantities import Quantity
     path = os.path.realpath(self.paramPath.value)
     if os.path.isfile(path):
         path = os.path.dirname(path)
     pattern = re.compile(self.paramRegex.value)
     filenames = filter(lambda x: pattern.match(x) is not None,
                        os.listdir(path))
     filenames.sort()
     filenames = [os.path.join(path, fname) for fname in filenames]
     print path
     zClip = self.getClip(self.paramZClip.value)
     filenames = filenames[zClip[0]:zClip[1]]
     assert len(filenames) >= 1
     yClip = self.getClip(self.paramYClip.value)
     xClip = self.getClip(self.paramXClip.value)
     dtype = self.paramDtype.value
     data = []
     for i, fn in enumerate(filenames):
         subscriber %= 1 + 99 * i / len(filenames)
         data.append(imread(fn, True)[yClip[0]:yClip[1], xClip[0]:xClip[1]])
     data = numpy.array(data, dtype=dtype)
     axes = ['z', 'y', 'x']
     dimensions = [
         self.getDimension(a, data.shape[i]) for i, a in enumerate(axes)
     ]
     try:
         unit = Quantity(self.paramFieldUnit.value)
     except AttributeError:
         unit = self.paramFieldUnit.value
     longname = self.paramLongname.value
     shortname = self.paramShortname.value
     image = FieldContainer(data=data,
                            dimensions=dimensions,
                            unit=unit,
                            longname=longname,
                            shortname=shortname,
                            attributes={
                                'yFactor': Quantity(self.paramDy.value),
                                'xFactor': Quantity(self.paramDx.value)
                            })
     image.seal()
     subscriber %= 100
     return image
Exemple #22
0
def slice2ind(arg, dim):
    if isinstance(arg, type("")):
        sl = ["0" + a for a in arg.split(':')
              ]  #Hack for quantities. which does not recognize .6 as a number.
        unit = dim.unit
        try:
            hi = Quantity(sl[1])
            try:
                li = Quantity(sl[0])
            except:
                li = Quantity(float(sl[0]), hi.unit)
            try:
                li, hi = [
                    i.inUnitsOf(unit.unit).value / unit.value
                    for i in [li, hi]
                ]
            except TypeError:
                raise TypeError(
                    "IncompatibleUnits: Dimension %s: %s [%s] can not be sliced with \"%s\"."
                    % (dim.longname, dim.shortname, dim.unit, arg))
        except SyntaxError:
            li, hi = [float(i) / unit for i in sl]
        f = dim.data
        intervallElements = numpy.logical_and(f >= li, f < hi)
        if numpy.alltrue(intervallElements):
            start = 0
            end = len(intervallElements) + 1
        else:
            dma = numpy.diff(intervallElements).nonzero()
            if len(dma[0]) == 0:
                raise NotImplementedError(
                    "This slice needs interpolation, which is not implemented yet."
                )
            if li <= f.min():
                start = 0
                end = dma[0][0] + 1
            elif hi > f.max():
                start = dma[0][0] + 1
                end = len(intervallElements) + 1
            elif hi == f.max():
                start = dma[0][0] + 1
                end = len(intervallElements)
            else:
                start, end = dma[0] + 1
        return slice(start, end)
    elif isinstance(arg, type(2)):
        return slice(arg, arg + 1)
    else:
        return arg
Exemple #23
0
    def getDimension(self, axis, length):
        from pyphant.quantities import Quantity
        from pyphant.core.DataContainer import FieldContainer
        import numpy
        delta = Quantity(self.getParam('d' + axis).value)
        start = Quantity(self.getParam('start' + axis).value)

        start = start.inUnitsOf(delta.unit)
        data = start.value + numpy.arange(0, length, dtype=float) * delta.value
        dim = FieldContainer(
            data, unit=Quantity(1.0, delta.unit),
            shortname=axis,
            longname='%s-Axis' % (axis.upper(), )
            )
        return dim
Exemple #24
0
def createFieldContainer(key, array):
    def longname2unit(name):
        reg = re.compile(r"\[([^]]*)\]")
        m = reg.search(name)
        if not m or m.group(1) == "counts" or m.group(1) == "":
            return 1.0
        else:
            return Quantity('1 ' + str(m.group(1)))

    fieldUnit = longname2unit(key)
    if isQuantity(fieldUnit):
        fieldContainer = DataContainer.FieldContainer(numpy.array(array),
                                                      unit=fieldUnit,
                                                      longname=key)
    else:
        try:
            quantities = [
                Quantity(string.encode('latin-1')) for string in array
            ]
            firstUnit = quantities[0].unit
            scaledArray = [
                quant.inUnitsOf(firstUnit).value for quant in quantities
            ]
            fieldContainer = DataContainer.FieldContainer(
                numpy.array(scaledArray),
                unit='1. %s' % firstUnit.name(),
                longname=key)
        except:
            fieldContainer = DataContainer.FieldContainer(numpy.array(array),
                                                          unit=fieldUnit,
                                                          longname=key)
    return fieldContainer
Exemple #25
0
 def longname2unit(name):
     reg = re.compile(r"\[([^]]*)\]")
     m = reg.search(name)
     if not m or m.group(1) == "counts" or m.group(1) == "":
         return 1.0
     else:
         return Quantity('1 ' + str(m.group(1)))
 def setUp(self):
     super(SampleContainerTestCase,self).setUp()
     self.independent = FieldContainer(0.3*numpy.linspace(0,1,self.testData.shape[0]),
                                       longname='independent variable',
                                       shortname='x',
                                       unit = Quantity('1 mg'),
                                       attributes = copy.copy(self.attributes).update({'independent':True}))
     self.dependent = FieldContainer(9.81*self.independent.data,
                                     dimensions=[self.independent],
                                     longname='dependent variable',
                                     shortname='f',
                                     unit = Quantity('9.81 nN'),
                                     attributes = copy.copy(self.attributes).update({'independent':False}))
     self.sample = SampleContainer([self.dependent,self.field],longname='Sample',shortname='X',
                                   attributes = copy.copy(self.attributes).update({'isSample':'It seems so.'}))
     self.sample.seal()
Exemple #27
0
 def testLoadOneValue(self):
     result = self.load('onevalue.fmf')
     t = FieldContainer(numpy.array([1.0]),
                        unit=Quantity('1 s'),
                        shortname='t',
                        longname='time')
     self.checkExpected([t], result)
Exemple #28
0
 def setUp(self):
     import tempfile
     import os
     self.dir = tempfile.mkdtemp()
     self.dbase = self.dir + os.path.sep + "testcase.sqlite3"
     self.wrapper = pyphant.core.SQLiteWrapper.SQLiteWrapper(self.dbase)
     with self.wrapper:
         self.wrapper.setup_dbase()
     self.summary = {
         'id': 'emd5://PC/aheld/'
         '2009-01-01_12:00:00.123456/12345678910.field',
         'longname': 'name',
         'shortname': 'sn',
         'creator': 'aheld',
         'date': '2009-01-01_12:00:00.123456',
         'machine': 'PC',
         'type': 'field',
         'unit': Quantity('10.03e-8 mm**-1'),
         'attributes': {
             'attribute1': 'bla1',
             'attribute2': 'bla2'
         },
         'hash': '12345678910',
         'dimensions': [im_id]
     }
     self.sc_summary = self.summary.copy()
     self.sc_summary['id'] = self.summary['id'][:-5] + 'sample'
     self.sc_summary.pop('unit')
     self.sc_summary.pop('dimensions')
     self.sc_summary['columns'] = [self.summary['id'], self.summary['id']]
     self.sc_summary['type'] = 'sample'
     self.sc_summary['longname'] = u'name2'
     self.sc_summary['shortname'] = u'sn2'
Exemple #29
0
 def testPowersOfUnits(self):
     expected = (1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
     result = pyphant.core.SQLiteWrapper.quantity2powers(Quantity('1m'))
     self.assertEqual(
         expected, result,
         "The number of basic units determining a quantity does not fit. The SQTLiteWrapper is expecting"
     )
Exemple #30
0
 def testLoadOneColumn(self):
     result = self.load('onecolumn.fmf')
     t = FieldContainer(numpy.array([1, 2, 3, 4]),
                        unit=Quantity('1 s'),
                        shortname='t',
                        longname='time')
     self.checkExpected([t], result)
Exemple #31
0
 def calcAbsorption(self, osc, subscriber=0):
     I = osc[u'I']
     I_d = osc[u'I_d']
     I_0 = osc[u'I_0']
     A = - ((I.data - I_d.data) / (I_0.data - I_d.data) - 1)
     if self.paramClipping.value == 1:
         A[A > 1] = 1
         A[A < 0] = 0
     Abso = DataContainer.FieldContainer(A,
                                         longname=u'absorption',
                                         shortname=ur'\tilde{A}')
     Abso.dimensions[-1] = I.dimensions[-1]
     if self.paramMask_lamp.value == 1:
         removePeak(Abso, Quantity('654nm'), Quantity('660nm'))
         removePeak(Abso, Quantity('920nm'), Quantity('980nm'))
     Abso.seal()
     return Abso
Exemple #32
0
 def testSimpleQuantity(self):
     """
     The the conversion of a simple textual quantity specification
     to a quantity object.
     """
     expected = Quantity('1V')
     result = str2unit('1V')
     self.assertEqual(expected, result)
Exemple #33
0
class OscPlotPanel(PlotPanel):
    x_key = 0
    y_key = 1
    c_key = 2
    radius = Quantity('0.4mm')
    vmin = None
    vmax = None

    def __init__(self, parent, dataContainer):
        self.dataContainer = dataContainer
        PlotPanel.__init__(self, parent)

    def draw(self):
        self.x = self.dataContainer[self.x_key]
        self.y = self.dataContainer[self.y_key]
        self.c = self.dataContainer[self.c_key]
        if self.vmin is not None:
            self.vmin /= self.c.unit
        if self.vmax is not None:
            self.vmax /= self.c.unit
        self.figure.clear()
        self.ax = self.figure.add_subplot(111)
        self.figure.subplots_adjust(hspace=0.8)
        aspect = self.y.unit / self.x.unit
        if not isinstance(aspect, Quantity):
            self.ax.set_aspect(aspect)
        try:
            if self.c.mask != None:
                mask = numpy.logical_not(self.c.mask)
                x = self.x.data[mask]
                y = self.y.data[mask]
                c = self.c.data[mask]
            else:
                x = self.x.data
                y = self.y.data
                c = self.c.data
            self.scat = self.ax.scatter(x,
                                        y,
                                        s=numpy.pi *
                                        (self.radius / self.x.unit)**2,
                                        c=c,
                                        vmin=self.vmin,
                                        vmax=self.vmax)
            self.colorbar = self.figure.colorbar(self.scat,
                                                 format=F(self.c),
                                                 ax=self.ax)
            self.rescale(self.ax)
        except Exception, e:
            print e
        self.ax.set_xlabel(self.x.label)
        self.ax.set_ylabel(self.y.label)
        try:
            self.ax.set_title(self.dataContainer.attributes['title'])
        except (KeyError, TypeError):
            pass
        self.ax.callbacks.connect('xlim_changed', self.rescale)
        self.ax.callbacks.connect('ylim_changed', self.rescale)
        self.canvas.draw()
 def threshold(self, image, subscriber=0):
     th = float(self.paramThreshold.value)
     if self.paramUnit.value.lower() != 'ignore':
         from pyphant.quantities import Quantity, isQuantity
         try:
             unit = float(self.paramUnit.value)
             assert not isQuantity(image.unit)
         except ValueError:
             try:
                 unit = Quantity(self.paramUnit.value)
             except TypeError:
                 unit = Quantity(1.0, self.paramUnit.value)
             assert isQuantity(image.unit)
             assert unit.isCompatible(image.unit.unit)
         th *= unit / image.unit
     resultArray = scipy.where(image.data < th,
                               ImageProcessing.FEATURE_COLOR,
                               ImageProcessing.BACKGROUND_COLOR)
     result = DataContainer.FieldContainer(resultArray,
                                 dimensions=copy.deepcopy(image.dimensions),
                                 longname=u"Binary Image", shortname=u"B")
     result.seal()
     return result
Exemple #35
0
 def test_degC(self):
     temperature = Quantity('0 degC')
     self.assertEqual(temperature.inBaseUnits(),
                      Quantity('273.15 K'))
Exemple #36
0
class FieldContainer(DataContainer):
    u"""FieldContainer(data, unit=1, error=None,dimensions=None, longname=u"Sampled Field",
\t\t\t  shortname=u"\\Psi",rescale=False)
\t  Class describing sampled fields:
\t  .data\t\t- Numpy.array representing the sampled field.
\t  .unit\t\t- Quantity object denoting the unit of the sampled field.
\t  .dimensions\t- List of FieldContainer instances
\t\t\t  describing the dimensions of the sampled field.
\t  .data \t- Sampled field stored as numpy.array, which is rescaled to reasonable basic units if option rescale is chosen.
\t  .error\t- Absolut error of the sampled field stored as numpy.array
\t  .longname \t- Notation of the data, e.g. 'electric field',
\t\t\t  which is used for the automatic annotation of charts.
\t  .shortname \t- Symbol of the physical variable in LaTeX notation, e.g. 'E_\\alpha',
\t\t\t  which is also used for the automatic annotation of charts.
\t  .id \t\t- Identifier of Enhanced MD5 (emd5) format
\t\t\t\temd5://NODE/USER/DATETIME/MD5-HASH.TYPESTRING
\t\t\t  which is set by calling method .seal() and
\t\t\t  indicates that the stored information are unchangable.
\t  .label\t- Typical axis description composed from the meta information of the DataContainer.
Concerning the ordering of data matrices and the dimension list consult http://wiki.pyphant.org/xwiki/bin/view/Main/Dimension+Handling+in+Pyphant.
"""
    typeString = u"field"
    def __init__(self, data, unit=1, error=None, mask=None,
                 dimensions=None, longname=u"Sampled Field",
                 shortname=u"\\Psi", attributes=None, rescale=False):
        DataContainer.__init__(self, longname, shortname, attributes)
        self.data = data
        self.mask = mask
        try:
            if isinstance(unit, (str, unicode)):
                unit = unit.replace('^', '**')
            if isinstance(unit, unicode):
                unit = unit.encode('utf-8')
            self.unit = Quantity(unit)
        except:
            try:
                self.unit = Quantity("1"+unit)
            except:
                self.unit = unit
        self.error = error
        if dimensions != None:
            self.dimensions = dimensions
        else:
            N = len(data.shape)-1
            self.dimensions = [generateIndex(N-i,n) for i,n in enumerate(data.shape)]
        if rescale:
            self.rescale()
            for dim in self._dimensions:
                dim.rescale()
        assert self.isValid()

    def _set_dimensions(self,dimensions):
        self._dimensions = DimensionList(dimensions)

    def _get_dimensions(self):
        return self._dimensions
    dimensions = property(_get_dimensions,_set_dimensions)

    def _getLabel(self):
        if len(self._dimensions)>0:
            shortnames = [dim.shortname for dim in self._dimensions]
            shortnames.reverse()
            dependency = '(%s)' % ','.join(shortnames)
        else:
            dependency = ''
        label = u"%s $%s%s$ / %s" % (self.longname.title(), self.shortname, dependency, self.unit)
        try:
            if not isQuantity(self.unit) and self.unit == 1:
                label = u"%s $%s%s$ / a.u." % (self.longname.title(),self.shortname,dependency)
        except:
            pass #just a ScientificPython bug
        return label.replace('1.0 ',r'')#.replace('mu',u'\\textmu{}')
    label=property(_getLabel)

    def _getShortLabel(self):
        if not isQuantity(self.unit) and self.unit == 1:
            if self.longname == 'index':
                label = u"%s $%s$" % (self.longname.title(),self.shortname)
            else:
                label = u"%s $%s$ / a.u." % (self.longname.title(),self.shortname)
        else:
            label =  u"%s $%s$ / %s" % (self.longname.title(), self.shortname, self.unit)
        return label.replace('1.0 ',r'')#.replace('mu',u'\\textmu{}')
    shortlabel=property(_getShortLabel)

    def _getRawDataBytes(self):
        return self.data.nbytes \
               + sum([dim.rawDataBytes for dim in self.dimensions])
    rawDataBytes = property(_getRawDataBytes)

    def __deepcopy__(self, memo):
        self.lock.acquire()
        data=copy.deepcopy(self.data, memo)
        data.setflags(write=True)
        mask=copy.deepcopy(self.mask, memo)
        if mask!=None:
            mask.setflags(write=True)
        error=copy.deepcopy(self.error, memo)
        if error!=None:
            error.setflags(write=True)
        dimensions=copy.deepcopy(self._dimensions, memo)
        res = FieldContainer(data, self.unit, error, mask, dimensions,
                             self.longname, self.shortname)
        self.lock.release()
        return res

    def generateHash(self, m=None):
        if m == None:
            m = hashlib.md5()
        super(FieldContainer, self).generateHash(m)
        #m.update(str(self.data.tolist()))
        m.update(self.data.dumps())
        m.update(str(self.unit))
        if self.error!=None:
            #m.update(str(self.error.tolist()))
            m.update(self.error.dumps())
        if self.mask!=None:
            #m.update(str(self.mask.tolist()))
            m.update(self.mask.dumps())
        [m.update(dim.hash) for dim in self._dimensions]
        return enc(m.hexdigest())

    def seal(self, id=None):
        with self.lock:
            assert self.isValid()
            self.data.setflags(write=False)
            if self.mask!=None:
                self.mask.setflags(write=False)
            if self.error!=None:
                self.error.setflags(write=False)
            if not id:
                self._dimensions.write = False
                for dim in self._dimensions:
                    dim.seal()
            super(FieldContainer, self).seal(id)

    def inUnitsOf(self, other):
        if not isQuantity(self.unit):
            if isQuantity(other.unit):
                raise ValueError("Incompatible Units: self.unit = <%s>, other.unit = <%s>"%(self.unit, other.unit))
            factor = float(self.unit)/float(other.unit)
        elif not isQuantity(other.unit):
            raise ValueError("Incompatible Units: self.unit = <%s>, other.unit = <%s>"%(self.unit, other.unit))
        else:
            if not self.unit.isCompatible(other.unit.unit):
                raise ValueError("Incompatible Units: self.unit = <%s>, other.unit = <%s>"%(self.unit, other.unit))
            factor = self.unit.inUnitsOf(other.unit.unit).value/other.unit.value
        newSelf = copy.deepcopy(self)
        newSelf.data *= factor
        if newSelf.error != None:
            newSelf.error *= factor
        newSelf.unit = copy.deepcopy(other.unit)
        return newSelf

    def rescale(self):
        if isQuantity(self.unit):
            oldUnit = self.unit.inBaseUnits()
        else:
            return
        #Compute decade of field and multiply it to oldUnit
        oldFieldAmplitude = max(abs(numpy.amax(self.data)),abs(numpy.amin(self.data)))
        oldUnit *= oldFieldAmplitude
        #Compute next lower decade
        decade = scipy.log10(oldUnit.value)
        newDecade = 10**(scipy.floor(decade))
        #Find appropriate prefix
        baseUnit=oldUnit.unit.name()
        if baseUnit == 'm':
            prefixes = PREFIXES_METER
        else:
            prefixes = PREFIXES
        prefixCandidates = map(lambda i: (i[0],abs(i[1]-newDecade)),prefixes)
        optPrefix = min([prefix[1] for prefix in prefixCandidates])
        newPrefix = filter(lambda prefix: prefix[1]==optPrefix,prefixCandidates)[0][0]
        newUnitName = newPrefix+baseUnit
        #Convert to new unit
        newUnit = oldUnit.inUnitsOf(newUnitName)
        unitAmplitude = newUnit.value
        if self.data.dtype.name.startswith('int'):
            self.unit = newUnit/oldFieldAmplitude
            return
        self.data *= unitAmplitude/oldFieldAmplitude
        self.unit = newUnit/unitAmplitude

    def __eq__(self, other, rtol=1e-5, atol=1e-8):
        if type(self) != type(other):
            if type(other) != IndexMarker and type(other) != NoneType:
                _logger.debug('Cannot compare objects with different type (%s and %s).' % (type(self),type(other)))
            return False
        if not (self.typeString == other.typeString):
            _logger.debug('The typeString is not identical.')
            return False
        if (self.mask==None) and (other.mask!=None):
            _logger.debug('The mask of the first field container has not been set, while the mask of the second field container is set to %s.' % other.mask)
            return False
        elif  self.mask!=None and (other.mask==None):
            _logger.debug('The mask of the second field container has not been set, while the mask of the first field container is set to %s.' % self.mask)
            return False
        if not (numpy.alltrue(self.mask==other.mask)):
            _logger.debug('The masks are not identical: %s\n%s' % (self.mask,other.mask))
            return False
        if self.mask!=None:
            data = self.data[numpy.logical_not(self.mask)]
            otherData = other.data[numpy.logical_not(other.mask)]
            if self.error!=None:
                error = self.error[numpy.logical_not(self.mask)]
            else:
                error = self.error
            if other.error!=None:
                otherError = other.error[numpy.logical_not(other.mask)]
            else:
                otherError = other.error
        else:
            data = self.data
            error = self.error
            otherData = other.data
            otherError = other.error
        if (isQuantity(self.unit) or isQuantity(other.unit)):
            try:
                if not (self.unit.inBaseUnits().unit == other.unit.inBaseUnits().unit):
                    _logger.debug('The units are different.')
                    return False
            except AttributeError:
                _logger.debug('Cannot compare unit with normed quantity: %s, %s' % (self.unit,other.unit))
                return False
            try:
                scaledData = data*self.unit.value
                scaledOtherData = otherData*other.unit.inUnitsOf(self.unit.unit).value
                if not numpy.allclose(scaledData,scaledOtherData,rtol,atol):
                    if numpy.sometrue(numpy.isnan(scaledData)):
                        _logger.debug('The fields cannot be compared, because some elements of the first field are NaN and the mask has not been set.')
                    if numpy.sometrue(numpy.isnan(scaledOtherData)):
                        _logger.debug('The fields cannot be compared, because some elements of the second field are NaN and the mask has not been set.')
                    else:
                        difference = numpy.abs(scaledData-scaledOtherData)
                        _logger.debug('The scaled fields differ, data-otherData: %s\n%s\n%s' % (difference.max(),
                                                                                       scaledData,
                                                                                       scaledOtherData))
                    return False
            except ValueError:
                _logger.debug('Shape mismatch: %s != %s' % (self.data.shape,other.data.shape))
                return False
            if error!=None:
                scaledError = error*self.unit.value
                if otherError!=None:
                    otherScaledError = otherError*other.unit.inUnitsOf(self.unit.unit).value
                else:
                    _logger.debug('The errors differ: The error of the second argument is none, while the error of the first argument is %s.' % error)
                    return False
                if not numpy.allclose(scaledError,otherScaledError,rtol,atol):
                    _logger.debug('The normed errors differ: %s\n%s' % (scaledError,otherScaledError))
                    return False
        else:
            if not data.dtype.char in ['S','U']:
                try:
                    scaledData = data*self.unit
                    scaledOtherData = otherData*other.unit
                    if not numpy.allclose(scaledData,scaledOtherData,rtol,atol):
                        _logger.debug('The scaled fields differ: %s\n%s'%(scaledData,scaledOtherData))
                        return False
                except ValueError:
                    _logger.debug('Shape mismatch: %s != %s' % (self.data.shape,other.data.shape))
                    return False
                if error==None:
                    if not (otherError==None):
                        _logger.debug('The errors differ: Error of first argument is None, but the error of the second argument is not None.')
                        return False
                else:
                    scaledError = error*self.unit
                    otherScaledError = otherError*other.unit
                    if not numpy.allclose(scaledError,otherScaledError,rtol,atol):
                        _logger.debug('The errors differ: %s\n%s' % (scaledError,otherScaledError))
                        return False
        if not self.attributes == other.attributes:
            _logger.debug('The attribute dictionary differs.')
            return False
        for dimSelf,dimOther in zip(self._dimensions,other.dimensions):
            if dimSelf != dimOther:
                _logger.debug('Different dimensions: %s, %s' % (dimSelf,dimOther))
                return False
        return True

    def __ne__(self, other):
        return not self.__eq__(other)

    def __add__(self, other):
        if isinstance(other, FieldContainer):
            if self.error!=None or other.error!=None:
                return NotImplemented
            else:
                error = None
            if len(self._dimensions) != len(other.dimensions):
                return NotImplemented
            for i in xrange(len(self._dimensions)):
                if not self._dimensions[i] == other.dimensions[i]:
                    return NotImplemented
            if isQuantity(self.unit):
                if not isQuantity(other.unit):
                    return NotImplemented
                if not self.unit.isCompatible(other.unit.unit):
                    return NotImplemented
                if self.unit >= other.unit:
                    data = self.data+(other.data*other.unit.value*other.unit.unit.conversionFactorTo(self.unit.unit))/self.unit.value
                    unit = self.unit
                else:
                    data = other.data+(self.data*self.unit.value*self.unit.unit.conversionFactorTo(other.unit.unit))/other.unit.value
                    unit = other.unit
            elif isQuantity(other.unit):
                return NotImplemented
            else:
                data = (self.data*self.unit) + (other.data*other.unit)
                unit = 1.0
            if self.mask==None:
                mask=other.mask
            elif other.mask==None:
                mask=self.mask
            else:
                mask=self.mask+other.mask
            longname = u"Sum of %s and %s." % (self.longname, other.longname)
            shortname = u"%s + %s" % (self.shortname, other.shortname)
            return FieldContainer(data, unit, error, mask,
                                  copy.deepcopy(self._dimensions),
                                  longname, shortname)
        return NotImplemented

    def __sub__(self, other):
        if isinstance(other, FieldContainer):
            if self.error!=None or other.error!=None:
                error = other.error + self.error
            else:
                error = None
            if len(self._dimensions) != len(other.dimensions):
                return NotImplemented
            for i in xrange(len(self._dimensions)):
                if not self._dimensions[i] == other.dimensions[i]:
                    return NotImplemented
            if isQuantity(self.unit):
                if not (isQuantity(other.unit) and self.unit.isCompatible(other.unit.unit)):
                    return NotImplemented
                if self.unit >= other.unit:
                    data = self.data - (other.data*other.unit.value*other.unit.unit.conversionFactorTo(self.unit.unit))/self.unit.value
                    unit = self.unit
                else:
                    data = ((self.data*self.unit.value*self.unit.unit.conversionFactorTo(other.unit.unit))/other.unit.value) - other.data
                    unit = other.unit
            else:
                if isQuantity(other.unit):
                    return NotImplemented
                data = (self.data*self.unit) - (other.data*other.unit)
                unit = 1.0
            if self.mask==None:
                mask=other.mask
            elif other.mask==None:
                mask=self.mask
            else:
                mask=self.mask+other.mask
            longname = u"Difference of %s and %s." % (self.longname, other.longname)
            shortname = u"%s - %s" % (self.shortname, other.shortname)
            return FieldContainer(data, unit, error, mask,
                                  copy.deepcopy(self._dimensions),
                                  longname, shortname)
        return NotImplemented

    def __str__(self):
        deps = [ dim for dim in self._dimensions if type(dim)!=type(IndexMarker()) ]
        report  = "\nFieldContainer %s of shape %s with field\n%s\n"% (self.label,self.data.shape,self.data)
        if self.error != None:
            report += ", error\n%s\n" % self.error
        if self.mask !=None:
            report += ", mask\n%s\n" % self.mask
        if len(deps)>0:
            report += 'depending on dimensions %s\n' % deps
        if len(self.attributes)>0:
            report += 'and attributes\n%s\n' % self.attributes
        return report

    def __repr__(self):
        return self.__str__()

    def __getitem__(self, args):
        if isinstance(args, type("")):
            args=[args]
        if isinstance(args, type(1)):
            if args>=len(self.data):
                raise IndexError, 'index out of bound'
        try:
            len(args)
        except:
            args = [args]
        args = [ slice2ind(arg, self._dimensions[dim]) for dim, arg in enumerate(args) ]
        data = self.data[args]
        attributes = copy.deepcopy(self.attributes)
        mask = None
        error = None
        dimensions = []
        for i,l in enumerate(data.shape[:len(args)]):
            dim = self._dimensions[i]
            if l==1:
                attributes[dim.longname] = (dim.shortname, dim.data[args[i]].squeeze()*dim.unit)
            else:
                if isinstance(dim, IndexMarker):
                    dimensions.append(dim)
                else:
                    dimensions.append(dim[args[i],])
        for i in xrange(len(args),len(data.shape)):
            dimensions.append(copy.deepcopy(self._dimensions[i]))
        if data.shape != (1,):
            data = data.squeeze()
            if self.mask!=None:
                mask = self.mask[args].squeeze()
            if self.error!=None:
                error = self.error[args].squeeze()
        else:
            if self.mask!=None:
                mask = self.mask[args]
            if self.error!=None:
                error = self.error[args]
        field = FieldContainer(data, dimensions=dimensions,
                               longname=self.longname,
                               shortname=self.shortname,
                               mask=mask,
                               error=error,
                               unit=self.unit,
                               attributes=attributes)
        return field

    def isValid(self):
        # Valid dimensions?
        if (not (len(self._dimensions)==1
                 and isinstance(self._dimensions[0], IndexMarker)) #IndexMarkers are valid and...
            and not (self.data.shape == (1,) and len(self._dimensions)==0)): #...so are zero dim fields.
            dimshape = []
            for d in self._dimensions:
                if len(d.data.shape)>1:
                    _logger.debug("Dimension %s is not 1-d." % d.longname)
                    return False
                dimshape.append(d.data.shape[0])
            if self.data.shape!=tuple(dimshape):
                _logger.debug("Shape of data %s and of dimensions %s do not match for field\n:%s" %
                              (self.data.shape, dimshape, self))
                return False
            for d in self._dimensions:
                if not d.isValid():
                    _logger.debug("Invalid dimension %s."%d.longname)
                    return False
        # Valid mask?
        if (self.mask!=None) and (self.data.shape!=self.mask.shape):
            _logger.debug("Shape of data %s and of mask %s do not match."%(self.data.shape, self.mask.shape))
            return False
        # Valid error?
        if (self.error!=None) and (self.data.shape!=self.error.shape):
            _logger.debug("Shape of data %s and of error %s do not match."%(self.data.shape, self.error.shape))
            return False
        return True

    def isIndex(self):
        return self.dimensions==INDEX

    def isIndependent(self):
        for d in self.dimensions:
            if not d.isIndex():
                return False
        return True

    def isLinearlyDiscretised(self):
        for dim in self.dimensions:
            d = numpy.diff(dim.data)
            if not numpy.alltrue(numpy.logical_not(d-d[0])):
                return False
        return True

    def getMaskedFC(self, numpymask):
        """
        Return an unsealed FieldContainer instance that emerges from
        this instance by clipping along the primary axis according to the
        entries in the parameter numpymask, i.e. all entries where numpymask
        is set to False are discarded.
        numpymask -- Numpy array with Boolean values
        """
        mdims = []
        for dim in self.dimensions:
            if mdims == []:
                # only primary axis has to be masked:
                mdims.append(dim.getMaskedFC(numpymask))
            else:
                mdims.append(copy.deepcopy(dim))
        to_mask = [self.data, self.error, self.mask]
        masked = []
        for item in to_mask:
            if item != None:
                masked.append(item[numpymask])
            else:
                masked.append(None)
        return FieldContainer(masked[0],
                              copy.deepcopy(self.unit),
                              masked[1],
                              masked[2],
                              mdims,
                              longname=self.longname,
                              shortname=self.shortname,
                              attributes=copy.deepcopy(self.attributes),
                              rescale=False)

    maskedData = property( lambda self: numpy.ma.array(self.data, mask=self.mask) )
    maskedError = property( lambda self: numpy.ma.array(self.error, mask=self.mask) )