コード例 #1
0
ファイル: testliterals.py プロジェクト: mmckerns/diffpy.srfit
    def testValue(self):
        """Make sure the convolution operator is working properly."""

        import numpy
        pi = numpy.pi
        exp = numpy.exp

        x = numpy.linspace(0, 10, 1000)

        mu1 = 4.5
        sig1 = 0.1
        mu2 = 2.5
        sig2 = 0.4

        g1 = exp(-0.5 * ((x - mu1) / sig1)**2)
        a1 = literals.Argument(name="g1", value=g1)
        g2 = exp(-0.5 * ((x - mu2) / sig2)**2)
        a2 = literals.Argument(name="g2", value=g2)

        op = literals.ConvolutionOperator()
        op.addLiteral(a1)
        op.addLiteral(a2)

        g3c = op.value

        mu3 = mu1
        sig3 = (sig1**2 + sig2**2)**0.5
        g3 = exp(-0.5 * ((x - mu3) / sig3)**2)
        g3 *= sum(g1) / sum(g3)

        self.assertAlmostEquals(sum(g3c), sum(g3))
        self.assertAlmostEquals(0, sum((g3 - g3c)**2))
        return
コード例 #2
0
ファイル: testliterals.py プロジェクト: mmckerns/diffpy.srfit
    def testAddLiteral(self):
        """Test adding a literal to an operator node."""
        op = literals.Operator(name="add",
                               symbol="+",
                               operation=numpy.add,
                               nin=2,
                               nout=1)

        self.assertRaises(ValueError, op.getValue)
        op._value = 1
        self.assertEqual(op.getValue(), 1)

        # Test addition and operations
        a = literals.Argument(name="a", value=0)
        b = literals.Argument(name="b", value=0)

        op.addLiteral(a)
        self.assertRaises(ValueError, op.getValue)

        op.addLiteral(b)
        self.assertAlmostEqual(0, op.value)

        a.setValue(1)
        b.setValue(2)
        self.assertAlmostEqual(3, op.value)

        a.setValue(None)
        # Test for self-references

        # Try to add self
        op = literals.Operator(name="add",
                               symbol="+",
                               operation=numpy.add,
                               nin=2,
                               nout=1)
        op.addLiteral(a)
        self.assertRaises(ValueError, op.addLiteral, op)

        # Try to add argument that contains self
        op2 = literals.Operator(name="sub",
                                symbol="-",
                                operation=numpy.subtract,
                                nin=2,
                                nout=1)
        op2.addLiteral(op)
        self.assertRaises(ValueError, op.addLiteral, op2)

        return
コード例 #3
0
ファイル: testliterals.py プロジェクト: mmckerns/diffpy.srfit
 def testInit(self):
     """Test that everthing initializes as expected."""
     a = literals.Argument()
     self.assertEqual(None, a._value)
     self.assertTrue(False is a.const)
     self.assertTrue(None is a.name)
     return
コード例 #4
0
ファイル: builder.py プロジェクト: mmckerns/diffpy.srfit
    def __evalBinary(self, other, OperatorClass, onleft=True):
        """Evaluate a binary function.

        Other can be an BaseBuilder or a constant.

        onleft  --  Indicates that the operator was passed on the left side
                    (defualt True).
        """
        # Create the Operator
        op = OperatorClass()

        # onleft takes care of non-commutative operators, and assures that the
        # ordering is perserved.
        if onleft:
            # Add the literals to the operator
            op.addLiteral(self.literal)

        # Deal with constants
        if not isinstance(other, BaseBuilder):
            literal = literals.Argument(value=other, const=True)
        else:
            literal = other.literal
        op.addLiteral(literal)

        if not onleft:
            # Add the literals to the operator
            op.addLiteral(self.literal)

        # Create a new OperatorBuilder for the Operator
        opbuilder = OperatorBuilder(op.name)
        opbuilder.literal = op
        return opbuilder
コード例 #5
0
ファイル: builder.py プロジェクト: mmckerns/diffpy.srfit
    def registerConstant(self, name, value):
        """Register a named constant with the factory.

        Returns the registered builder.
        """
        arg = literals.Argument(name=name, value=value, const=True)
        return self.registerArgument(name, arg)
コード例 #6
0
    def makeEquation(self,
                     eqstr,
                     buildargs=True,
                     argclass=literals.Argument,
                     argkw={}):
        """Make an equation from an equation string.

        Arguments
        eqstr       --  An equation in string form using standard python
                        syntax.  The equation string can use any function
                        registered literal or function, including numpy ufuncs
                        that are automatically registered.
        buildargs   --  A flag indicating whether missing arguments can be
                        created by the Factory (default True). If False, then
                        the a ValueError will be raised if there are undefined
                        arguments in the eqstr. Built arguments will be of type
                        argclass.
        argclass    --  Class to use when creating new Arguments (default
                        diffpy.srfit.equation.literals.Argument). The class
                        constructor must accept the 'name' key word.
        argkw       --  Key word dictionary to pass to the argclass constructor
                        (default {}).

        Returns a callable Literal representing the equation string.
        """
        self._prepareBuilders(eqstr, buildargs, argclass, argkw)
        beq = eval(eqstr, {}, self.builders)
        # handle scalar numbers or numpy arrays
        if isinstance(beq, (numbers.Number, numpy.ndarray)):
            lit = literals.Argument(value=beq, const=True)
            eq = Equation(name='', root=lit)
        else:
            eq = beq.getEquation()
            self.equations.add(eq)
        return eq
コード例 #7
0
 def test_value(self):
     """Check ArrayOperator.value.
     """
     x = literals.Argument('x', 1.0)
     y = literals.Argument('y', 2.0)
     z = literals.Argument('z', 3.0)
     # check empty array
     op = literals.ArrayOperator()
     self.assertEqual(0, len(op.value))
     self.assertTrue(isinstance(op.value, numpy.ndarray))
     # check behavior with 2 arguments
     op.addLiteral(x)
     self.assertTrue(numpy.array_equal([1], op.value))
     op.addLiteral(y)
     op.addLiteral(z)
     self.assertTrue(numpy.array_equal([1, 2, 3], op.value))
     z.value = 7
     self.assertTrue(numpy.array_equal([1, 2, 7], op.value))
     return
コード例 #8
0
ファイル: testliterals.py プロジェクト: mmckerns/diffpy.srfit
    def testValue(self):
        """Test value."""
        # Test addition and operations
        op = literals.Operator(symbol="+", operation=numpy.add, nin=2)
        a = literals.Argument(value=0)
        b = literals.Argument(value=0)

        op.addLiteral(a)
        op.addLiteral(b)

        self.assertAlmostEquals(0, op.value)

        # Test update from the nodes
        a.setValue(4)
        self.assertTrue(op._value is None)
        self.assertAlmostEqual(4, op.value)
        self.assertAlmostEqual(4, op.getValue())

        b.value = 2
        self.assertTrue(op._value is None)
        self.assertAlmostEqual(6, op.value)

        return
コード例 #9
0
ファイル: testliterals.py プロジェクト: mmckerns/diffpy.srfit
    def testValue(self):
        """Test value setting."""

        a = literals.Argument()

        self.assertEquals(None, a.getValue())

        # Test setting value
        a.setValue(3.14)
        self.assertAlmostEqual(3.14, a._value)

        a.setValue(3.14)
        self.assertAlmostEqual(3.14, a.value)
        self.assertAlmostEqual(3.14, a.getValue())
        return
コード例 #10
0
    def wipeout(self, eq):
        """Invalidate the specified equation and remove it from the factory.

        This will remove the equation from the purview of the factory and
        also change its formula to return NaN.  This ensures that eq does
        not observe any object in the factory and thus prevents its indirect
        pickling with the factory because of observer callback function.

        No return value.
        """
        if eq is None:
            assert eq not in self.equations
            return
        self.equations.discard(eq)
        # invalidate this equation to clean up any observer relations of
        # objects in the factory towards its literals tree.
        nan = literals.Argument('nan', value=numpy.nan, const=True)
        eq.setRoot(nan)
        return
コード例 #11
0
ファイル: builder.py プロジェクト: mmckerns/diffpy.srfit
    def __init__(self, value=None, name=None, const=False, arg=None):
        """Create an ArgumentBuilder instance, containing a new Argument.

        Arguments
        value   --  The value of the wrapped Argument (float, default None)
        name    --  The name of the wrapped Argument (string, default None)
        const   --  Flag indicating whether the Argument is constant (bool,
                    default False)
        arg     --  A pre-defined Argument to use. If this is None (default),
                    then a new Argument will be created from value, name and
                    const.
        """
        BaseBuilder.__init__(self)
        if arg is None:
            self.literal = literals.Argument(value=value,
                                             name=name,
                                             const=const)
        else:
            self.literal = arg
        return
コード例 #12
0
def _makeArgs(num):
    args = []
    for i in xrange(num):
        j=i+1
        args.append(literals.Argument(name="v%i"%j, value=j))
    return args
コード例 #13
0
ファイル: testliterals.py プロジェクト: mmckerns/diffpy.srfit
 def testIdentity(self):
     """Make sure an Argument is an Argument."""
     a = literals.Argument()
     self.assertTrue(abcs.issubclass(literals.Argument, abcs.ArgumentABC))
     self.assertTrue(abcs.isinstance(a, abcs.ArgumentABC))
     return