Example #1
0
    def test_ExtendedVersion_Asymptotic_Exponential_A_WithExponentialDecayAndOffset_2D(
            self):
        equation = pyeq2.Models_2D.Exponential.AsymptoticExponentialA(
            'SSQABS', 'Exponential Decay And Offset')
        self.assertEqual(equation.extendedVersionHandler.__class__.__name__,
                         'ExtendedVersionHandler_ExponentialDecayAndOffset')
        self.assertEqual(
            equation.GetDisplayHTML(),
            'y = 1.0 - a<sup>x</sup><br>y = y / (d * exp(x)) + Offset')
        self.assertEqual(
            equation.GetDisplayName(),
            'Asymptotic Exponential A With Exponential Decay And Offset')
        self.assertEqual(equation.GetCoefficientDesignators(),
                         ['a', 'b', 'Offset'])
        self.assertEqual(len(equation.GetDataCacheFunctions()), 2)
        self.assertFalse(equation.CanLinearSolverBeUsedForSSQABS())

        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(
            DataForUnitTests.asciiDataInColumns_2D, equation, False)

        equation.Solve()
        coefficientsShouldBe = numpy.array(
            [2.69273579217, 0.00518863941, 182.725486049])
        self.assertTrue(
            numpy.allclose(equation.solvedCoefficients,
                           coefficientsShouldBe,
                           rtol=1.0E-06,
                           atol=1.0E-300))
Example #2
0
    def test_ExtendedVersion_Reciprocal_Exponential_WithOffset_2D(self):
        equation = pyeq2.Models_2D.Exponential.Exponential(
            'SSQABS', 'Reciprocal With Offset')
        self.assertEqual(equation.extendedVersionHandler.__class__.__name__,
                         'ExtendedVersionHandler_ReciprocalWithOffset')
        self.assertEqual(equation.GetDisplayHTML(),
                         'y = a * exp(bx)<br>y = 1.0 / y + Offset')
        self.assertEqual(equation.GetDisplayName(),
                         'Reciprocal Exponential With Offset')
        self.assertEqual(equation.GetCoefficientDesignators(),
                         ['a', 'b', 'Offset'])
        self.assertEqual(len(equation.GetDataCacheFunctions()), 1)
        self.assertFalse(equation.CanLinearSolverBeUsedForSSQABS())

        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(
            DataForUnitTests.asciiDataInColumns_2D, equation, False)

        equation.Solve()
        coefficientsShouldBe = numpy.array(
            [0.15004943, -0.10305384, -11.22929034])
        self.assertTrue(
            numpy.allclose(equation.solvedCoefficients,
                           coefficientsShouldBe,
                           rtol=1.0E-06,
                           atol=1.0E-300))
Example #3
0
    def test_ExtendedVersion_Exponential_WithLinearGrowthAndOffset_2D(self):
        equation = pyeq2.Models_2D.Exponential.Exponential(
            'SSQABS', 'Linear Growth And Offset')
        self.assertEqual(equation.extendedVersionHandler.__class__.__name__,
                         'ExtendedVersionHandler_LinearGrowthAndOffset')
        self.assertEqual(equation.GetDisplayHTML(),
                         'y = a * exp(bx)<br>y = y * x + Offset')
        self.assertEqual(equation.GetDisplayName(),
                         'Exponential With Linear Growth And Offset')
        self.assertEqual(equation.GetCoefficientDesignators(),
                         ['a', 'b', 'Offset'])
        self.assertEqual(len(equation.GetDataCacheFunctions()), 1)
        self.assertFalse(equation.CanLinearSolverBeUsedForSSQABS())

        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(
            DataForUnitTests.asciiDataInColumns_2D, equation, False)

        equation.Solve()
        coefficientsShouldBe = numpy.array(
            [0.643949371878, 0.0613391161993, -4.44443175952])
        self.assertTrue(
            numpy.allclose(equation.solvedCoefficients,
                           coefficientsShouldBe,
                           rtol=1.0E-06,
                           atol=1.0E-300))
Example #4
0
    def test_GenerationOf_CPP(self):
        generatedShouldBe = '''// To the best of my knowledge this code is correct.
// If you find any errors or problems please contact
// me directly using [email protected].
//
//      James


#include <math.h>

// Fitting target: lowest sum of squared absolute error
// Fitting target value = 0.223837322455

double Polynomial_Linear_model(double x_in)
{
	double temp;
	temp = 0.0;

	// coefficients
	double a = -8.01913564075E+00;
	double b = 1.52644729419E+00;

	temp += a + b * x_in;
	return temp;
}
'''
        equation = pyeq2.Models_2D.Polynomial.Linear('SSQABS')
        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(
            DataForUnitTests.asciiDataInColumns_2D, equation, False)
        equation.Solve()
        generated = pyeq2.outputSourceCodeService().GetOutputSourceCodeCPP(
            equation, inDigitsOfPrecisionString='11')
        self.assertEqual(generated, generatedShouldBe)
    def test_GenerationOf_CPP(self):
        generatedShouldBe = """// To the best of my knowledge this code is correct.
// If you find any errors or problems please contact
// me directly using [email protected].
//
//      James


#include <math.h>

// Fitting target: lowest sum of squared absolute error
// Fitting target value = 0.223837322455

double Linear_model(double x_in)
{
	double temp;
	temp = 0.0;

	// coefficients
	double a = -8.01913564075E+00;
	double b = 1.52644729419E+00;

	temp += a + b * x_in;
	return temp;
}
"""
        equation = pyeq2.Models_2D.Polynomial.Linear("SSQABS")
        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(
            DataForUnitTests.asciiDataInColumns_2D, equation, False
        )
        equation.Solve()
        generated = pyeq2.outputSourceCodeService().GetOutputSourceCodeCPP(equation, inDigitsOfPrecisionString="11")
        self.assertEqual(generated, generatedShouldBe)
def SetParametersAndFit(equationString, inFittingTargetString, inExtendedVersionString, inTextData):
    
    # individual cluster nodes must be able to import pyeq2
    import pyeq2

    exec('equation = ' + equationString +'("' + inFittingTargetString + '", "' + inExtendedVersionString + '")')
    pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(inTextData, equation, False)
 
    try:
        # check for number of coefficients > number of data points to be fitted
        if len(equation.GetCoefficientDesignators()) > len(equation.dataCache.allDataCacheDictionary['DependentData']):
            return None

        # check for functions requiring non-zero nor non-negative data such as 1/x, etc.
        if equation.ShouldDataBeRejected(equation):
            return None

        equation.Solve()

        fittedTarget = equation.CalculateAllDataFittingTarget(equation.solvedCoefficients)
        if fittedTarget > 1.0E290: # error too large
            return None
    except:
        return None

    return [fittedTarget, equation.GetDisplayName(), equation.solvedCoefficients, equationString, inExtendedVersionString]
Example #7
0
 def test_SolveUsingDE_3D(self):
     coefficientsShouldBe = numpy.array([-2.05105972, -0.49194959,  1.77817475])
     model = pyeq2.Models_3D.UserDefinedFunction.UserDefinedFunction('SSQABS', 'Default', 'a + b*X + c*Y')
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_3D_small, model, False)
     coefficients = pyeq2.solverService().SolveUsingDE(model)
     fittingTarget = model.CalculateAllDataFittingTarget(coefficients)
     self.assertTrue(fittingTarget <= 0.1)
Example #8
0
 def test_UserDefinedFunction_2D(self):
     coefficientsShouldBe = numpy.array([3.28686108e-04, 1.30583728])
     functionString = 'Scale * exp(X) + offset'
     model = pyeq2.Models_2D.UserDefinedFunction.UserDefinedFunction(inUserFunctionString = functionString)
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_2D, model, False)
     model.Solve()
     self.assertTrue(numpy.allclose(model.solvedCoefficients, coefficientsShouldBe, rtol=1.0E-8, atol=1.0E-300))
Example #9
0
    def test_SolveUsingSpline_3D(self):
        xKnotPointsShouldBe = numpy.array([0.607, 0.607, 0.607, 3.017, 3.017, 3.017])
        yKnotPointsShouldBe = numpy.array([1.984, 1.984, 1.984, 3.153, 3.153, 3.153])
        coefficientsShouldBe = numpy.array(
            [2.33418963, 1.80079612, 5.07902936, 0.54445029, 1.04110843, 2.14180324, 0.26992805, 0.39148852, 0.8177307]
        )
        testEvaluationShouldBe = numpy.array([0.76020577997])
        model = pyeq2.Models_3D.Spline.Spline(inSmoothingFactor=1.0, inXOrder=2, inYOrder=2)
        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_3D, model, False)
        fittedParameters = pyeq2.solverService().SolveUsingSpline(model)

        # example of later using the saved spline knot points and coefficients
        unFittedSpline = scipy.interpolate.fitpack2.SmoothBivariateSpline(
            model.dataCache.allDataCacheDictionary["X"],
            model.dataCache.allDataCacheDictionary["Y"],
            model.dataCache.allDataCacheDictionary["DependentData"],
            s=model.smoothingFactor,
            kx=model.xOrder,
            ky=model.yOrder,
        )
        unFittedSpline.tck = fittedParameters
        testEvaluation = unFittedSpline.ev(2.5, 2.5)

        self.assertTrue(numpy.allclose(testEvaluation, testEvaluationShouldBe, rtol=1.0e-10, atol=1.0e-300))
        self.assertTrue(numpy.equal(fittedParameters[0], xKnotPointsShouldBe).all())
        self.assertTrue(numpy.equal(fittedParameters[1], yKnotPointsShouldBe).all())
        self.assertTrue(numpy.allclose(fittedParameters[2], coefficientsShouldBe, rtol=1.0e-06, atol=1.0e-300))
Example #10
0
def fp_fit(x, y):
	"""Given a list of x and y values, function fits a four parameter logistic 
	distribution to the data. The distribution being fit has bounds set on several of
	the parameters to keep the distribution in the proper orientation. These are:
	
	a	-0.25	0.25
	b	-inf	-0.1
	c	0		inf
	d	0.75	1.25
	
	The function returns a tuple of the parameters and the covariance of the fit:
	
	((a, b, c, d), cov)
	
	"""
	equation = pyeq2.Models_2D.Sigmoidal.FourParameterLogistic()

	data = "\n".join("{} {}".format(x1, y1) for x1, y1 in zip(x, y))
	
	equation.upperCoefficientBounds = [0.25, -0.1, None, 1.25]
	equation.lowerCoefficientBounds = [-0.25, None, 0, 0.75]
	
	pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(data, equation, False)
	equation.Solve()
	
	return equation.solvedCoefficients, equation.CalculateAllDataFittingTarget(equation.solvedCoefficients)
Example #11
0
 def test_SolveUsingLevenbergMarquardt_3D(self):
     coefficientsShouldBe = numpy.array([0.28658387, -0.90215776, 1.15483863])
     model = pyeq2.Models_3D.Polynomial.Linear('SSQABS')
     model.estimatedCoefficients = numpy.array([0.2, -1.0, 1.0]) # starting values for the simplex solver
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_3D, model, False)
     coefficients = pyeq2.solverService().SolveUsingSelectedAlgorithm(model, inAlgorithmName="Levenberg-Marquardt")
     self.assertTrue(numpy.allclose(coefficients, coefficientsShouldBe, rtol=1.0E-05, atol=1.0E-300))
Example #12
0
 def test_SolveUsingSimplex_3D(self):
     coefficientsShouldBe = numpy.array([0.28658383, -0.90215775, 1.15483864])
     model = pyeq2.Models_3D.Polynomial.Linear('SSQABS')
     model.estimatedCoefficients = numpy.array([1.0, 1.0, 1.0]) # starting values for the simplex solver
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_3D, model, False)
     coefficients = pyeq2.solverService().SolveUsingSimplex(model)
     self.assertTrue(numpy.allclose(coefficients, coefficientsShouldBe, rtol=1.0E-06, atol=1.0E-300))
Example #13
0
 def test_SolveUsingODR_3D(self):
     coefficientsShouldBe = numpy.array([-0.04925, -0.90509, 1.28076])
     model = pyeq2.Models_3D.Polynomial.Linear("ODR")
     model.estimatedCoefficients = numpy.array([0.2, -1.0, 1.0])  # starting values for the ODR solver
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_3D, model, False)
     coefficients = pyeq2.solverService().SolveUsingODR(model)
     self.assertTrue(numpy.allclose(coefficients, coefficientsShouldBe, rtol=1.0e-03, atol=1.0e-300))
    def test_SolveUsingSpline_2D(self):
        knotPointsShouldBe = numpy.array(
            [5.357, 5.357, 5.357, 5.357, 9.861, 9.861, 9.861, 9.861])
        coefficientsShouldBe = numpy.array([
            0.38297001, 1.95535226, 4.59605664, 7.16162379, 0.0, 0.0, 0.0, 0.0
        ])
        testEvaluationShouldBe = numpy.array([4.02361487093])
        model = pyeq2.Models_2D.Spline.Spline(inSmoothingFactor=1.0,
                                              inXOrder=3)
        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(
            DataForUnitTests.asciiDataInColumns_2D, model, False)
        fittedParameters = pyeq2.solverService().SolveUsingSpline(model)

        # example of later using the saved spline knot points and coefficients
        unFittedSpline = scipy.interpolate.fitpack2.UnivariateSpline(
            model.dataCache.allDataCacheDictionary['X'],
            model.dataCache.allDataCacheDictionary['DependentData'],
            s=model.smoothingFactor,
            k=model.xOrder)
        unFittedSpline._eval_args = fittedParameters
        testEvaluation = unFittedSpline(numpy.array([8.0]))

        self.assertTrue(
            numpy.allclose(testEvaluation,
                           testEvaluationShouldBe,
                           rtol=1.0E-10,
                           atol=1.0E-300))
        self.assertTrue(
            numpy.equal(fittedParameters[0], knotPointsShouldBe).all())
        self.assertTrue(
            numpy.allclose(fittedParameters[1],
                           coefficientsShouldBe,
                           rtol=1.0E-06,
                           atol=1.0E-300))
Example #15
0
 def test_SolveUsingSimplex_3D(self):
     coefficientsShouldBe = numpy.array([0.28658383, -0.90215775, 1.15483864])
     model = pyeq2.Models_3D.Polynomial.Linear("SSQABS")
     model.estimatedCoefficients = numpy.array([1.0, 1.0, 1.0])  # starting values for the simplex solver
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_3D, model, False)
     coefficients = pyeq2.solverService().SolveUsingSimplex(model)
     self.assertTrue(numpy.allclose(coefficients, coefficientsShouldBe, rtol=1.0e-06, atol=1.0e-300))
Example #16
0
 def test_SolveUsingLevenbergMarquardt_2D(self):
     coefficientsShouldBe = numpy.array([-8.01913565, 1.5264473])
     model = pyeq2.Models_2D.Polynomial.Linear("SSQABS")
     model.estimatedCoefficients = numpy.array([-4.0, 2.0])  # starting values for the simplex solver
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_2D, model, False)
     coefficients = pyeq2.solverService().SolveUsingLevenbergMarquardt(model)
     self.assertTrue(numpy.allclose(coefficients, coefficientsShouldBe, rtol=1.0e-06, atol=1.0e-300))
Example #17
0
 def test_Rational_WithOffset_2D(self):
     equation = pyeq2.Models_2D.Rational.UserSelectableRational(
         'SSQABS', 'Offset', [0, 1], [2, 3])
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(
         equation.exampleData, equation, False)
     self.assertTrue(
         0.008 >= equation.CalculateAllDataFittingTarget(equation.Solve()))
Example #18
0
 def test_SolveUsingSimplex_SSQREL_2D(self):
     coefficientsShouldBe = numpy.array([-6.74510573, 1.32459622])
     model = pyeq2.Models_2D.Polynomial.Linear("SSQREL")
     model.estimatedCoefficients = numpy.array([1.0, 1.0])  # starting values for the simplex solver
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_2D, model, False)
     coefficients = pyeq2.solverService().SolveUsingSimplex(model)
     self.assertTrue(numpy.allclose(coefficients, coefficientsShouldBe, rtol=1.0e-06, atol=1.0e-300))
Example #19
0
 def test_Polyfunctional3D(self):
     equation = pyeq2.Models_3D.Polyfunctional.UserSelectablePolyfunctional(
         'SSQREL', 'Default', [[0, 0], [1, 1], [3, 3]])
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(
         equation.exampleData, equation, False)
     self.assertTrue(
         8.2 >= equation.CalculateAllDataFittingTarget(equation.Solve()))
Example #20
0
 def test_Polyfunctional2D(self):
     equation = pyeq2.Models_2D.Polyfunctional.UserSelectablePolyfunctional(
         'SSQABS', 'Default', [0, 1, 3])
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(
         equation.exampleData, equation, False)
     self.assertTrue(
         0.013 >= equation.CalculateAllDataFittingTarget(equation.Solve()))
Example #21
0
 def test_SecondDegreeLegendrePolynomial(self):
     equation = pyeq2.Models_2D.LegendrePolynomial.SecondDegreeLegendrePolynomial(
         'SSQABS')
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(
         equation.exampleData, equation, False)
     self.assertTrue(
         0.0146 >= equation.CalculateAllDataFittingTarget(equation.Solve()))
Example #22
0
 def test_SolveUsingDE_3D(self):
     coefficientsShouldBe = numpy.array([-2.05105972, -0.49194959,  1.77817475])
     model = pyeq2.Models_3D.UserDefinedFunction.UserDefinedFunction('SSQABS', 'Default', 'a + b*X + c*Y')
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_3D_small, model, False)
     coefficients = pyeq2.solverService().SolveUsingDE(model)
     fittingTarget = model.CalculateAllDataFittingTarget(coefficients)
     self.assertTrue(fittingTarget <= 0.1)
Example #23
0
 def test_SolveUsingODR_3D(self):
     coefficientsShouldBe = numpy.array([-0.04925, -0.90509, 1.28076])
     model = pyeq2.Models_3D.Polynomial.Linear('ODR')
     model.estimatedCoefficients = numpy.array([0.2, -1.0, 1.0]) # starting values for the ODR solver
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_3D, model, False)
     coefficients = pyeq2.solverService().SolveUsingODR(model)
     self.assertTrue(numpy.allclose(coefficients, coefficientsShouldBe, rtol=1.0E-03, atol=1.0E-300))
Example #24
0
 def test_SolveUsingSimplex_SSQREL_2D(self):
     coefficientsShouldBe = numpy.array([-6.74510573, 1.32459622])
     model = pyeq2.Models_2D.Polynomial.Linear('SSQREL')
     model.estimatedCoefficients = numpy.array([1.0, 1.0]) # starting values for the simplex solver
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_2D, model, False)
     coefficients = pyeq2.solverService().SolveUsingSimplex(model)
     self.assertTrue(numpy.allclose(coefficients, coefficientsShouldBe, rtol=1.0E-06, atol=1.0E-300))
    def test_GenerationOf_PYTHON(self):
        generatedShouldBe = '''# To the best of my knowledge this code is correct.
# If you find any errors or problems please contact
# me directly using [email protected].
#
#      James


import math

# Fitting target: lowest sum of squared absolute error
# Fitting target value = 0.223837322455

def Polynomial_Linear_model(x_in):
    temp = 0.0

    # coefficients
    a = -8.01913564075E+00
    b = 1.52644729419E+00

    temp += a + b * x_in
    return temp
'''
        equation = pyeq2.Models_2D.Polynomial.Linear('SSQABS')
        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_2D, equation, False)
        equation.Solve()
        generated = pyeq2.outputSourceCodeService().GetOutputSourceCodePYTHON(equation, inDigitsOfPrecisionString = '11')
        self.assertEqual(generated, generatedShouldBe)
Example #26
0
    def test_GenerationOf_PYTHON(self):
        generatedShouldBe = '''# To the best of my knowledge this code is correct.
# If you find any errors or problems please contact
# me directly using [email protected].
#
#      James


import math

# Fitting target: lowest sum of squared absolute error
# Fitting target value = 0.223837322455

def Polynomial_Linear_model(x_in):
    temp = 0.0

    # coefficients
    a = -8.01913564075E+00
    b = 1.52644729419E+00

    temp += a + b * x_in
    return temp
'''
        equation = pyeq2.Models_2D.Polynomial.Linear('SSQABS')
        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(
            DataForUnitTests.asciiDataInColumns_2D, equation, False)
        equation.Solve()
        generated = pyeq2.outputSourceCodeService().GetOutputSourceCodePYTHON(
            equation, inDigitsOfPrecisionString='11')
        self.assertEqual(generated, generatedShouldBe)
Example #27
0
    def test_GenerationOf_MATLAB(self):
        generatedShouldBe = '''% To the best of my knowledge this code is correct.
% If you find any errors or problems please contact
% me directly using [email protected].
%
%      James


% Fitting target: lowest sum of squared absolute error
% Fitting target value = 0.223837322455

function y = Polynomial_Linear_model(x_in)
\ttemp = 0.0;

\t% coefficients
\ta = -8.01913564075E+00;
\tb = 1.52644729419E+00;

\ttemp = temp + a + b .* x_in;

\ty = temp;
'''
        equation = pyeq2.Models_2D.Polynomial.Linear('SSQABS')
        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(
            DataForUnitTests.asciiDataInColumns_2D, equation, False)
        equation.Solve()
        generated = pyeq2.outputSourceCodeService().GetOutputSourceCodeMATLAB(
            equation, inDigitsOfPrecisionString='11')
        self.assertEqual(generated, generatedShouldBe)
    def test_GenerationOf_VBA(self):
        generatedShouldBe = """' To the best of my knowledge this code is correct.
' If you find any errors or problems please contact
' me directly using [email protected].
'
'      James

' Fitting target: lowest sum of squared absolute error
' Fitting target value = 0.223837322455

Public Function Linear_model(x_in)
\ttemp = 0.0

\t' coefficients
\tConst a = -8.01913564075E+00
\tConst b = 1.52644729419E+00

\ttemp = temp + a + b * x_in
\tLinear_model = temp
End Function
"""
        equation = pyeq2.Models_2D.Polynomial.Linear("SSQABS")
        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(
            DataForUnitTests.asciiDataInColumns_2D, equation, False
        )
        equation.Solve()
        generated = pyeq2.outputSourceCodeService().GetOutputSourceCodeVBA(equation, inDigitsOfPrecisionString="11")
        self.assertEqual(generated, generatedShouldBe)
    def test_GenerationOf_MATLAB(self):
        generatedShouldBe = '''% To the best of my knowledge this code is correct.
% If you find any errors or problems please contact
% me directly using [email protected].
%
%      James


% Fitting target: lowest sum of squared absolute error
% Fitting target value = 0.223837322455

function y = Polynomial_Linear_model(x_in)
\ttemp = 0.0;

\t% coefficients
\ta = -8.01913564075E+00;
\tb = 1.52644729419E+00;

\ttemp = temp + a + b .* x_in;

\ty = temp;
'''
        equation = pyeq2.Models_2D.Polynomial.Linear('SSQABS')
        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_2D, equation, False)
        equation.Solve()
        generated = pyeq2.outputSourceCodeService().GetOutputSourceCodeMATLAB(equation, inDigitsOfPrecisionString = '11')
        self.assertEqual(generated, generatedShouldBe)
    def test_GenerationOf_CSHARP(self):
        generatedShouldBe = '''// To the best of my knowledge this code is correct.
// If you find any errors or problems please contact
// me directly using [email protected].
//
//      James


using System;

// Fitting target: lowest sum of squared absolute error
// Fitting target value = 0.223837322455

class Polynomial_Linear
{
\tdouble Polynomial_Linear_model(double x_in)
\t{
\t\tdouble temp;
\t\ttemp = 0.0;

\t\t// coefficients
\t\tdouble a = -8.01913564075E+00;
\t\tdouble b = 1.52644729419E+00;

\t\ttemp += a + b * x_in;
\t\treturn temp;
\t}
}
'''
        equation = pyeq2.Models_2D.Polynomial.Linear('SSQABS')
        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_2D, equation, False)
        equation.Solve()
        generated = pyeq2.outputSourceCodeService().GetOutputSourceCodeCSHARP(equation, inDigitsOfPrecisionString = '11')
        self.assertEqual(generated, generatedShouldBe)
Example #31
0
 def test_Polynomial3D(self):
     equation = pyeq2.Models_3D.Polynomial.UserSelectablePolynomial(
         'SSQABS', 'Default', 2, 2)
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(
         equation.exampleData, equation, False)
     self.assertTrue(2.92E-04 >= equation.CalculateAllDataFittingTarget(
         equation.Solve()))
Example #32
0
 def test_SolveUsingDE_2D(self):
     coefficientsShouldBe = numpy.array([-6.15515504031, 1.21618173729])
     model = pyeq2.Models_2D.UserDefinedFunction.UserDefinedFunction("SSQABS", "Default", "m*X + b")
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(
         DataForUnitTests.asciiDataInColumns_2D_small, model, False
     )
     coefficients = pyeq2.solverService().SolveUsingDE(model)
     self.assertTrue(numpy.allclose(coefficients, coefficientsShouldBe, rtol=1.0e-06, atol=1.0e-300))
Example #33
0
 def test_SolveUsingDE_3D(self):
     coefficientsShouldBe = numpy.array([-0.206068766376, -0.644872592849, 1.13361007134])
     model = pyeq2.Models_3D.UserDefinedFunction.UserDefinedFunction("SSQABS", "Default", "a + b*X + c*Y")
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(
         DataForUnitTests.asciiDataInColumns_3D_small, model, False
     )
     coefficients = pyeq2.solverService().SolveUsingDE(model)
     self.assertTrue(numpy.allclose(coefficients, coefficientsShouldBe, rtol=1.0e-06, atol=1.0e-300))
def CalculateAndPrintResults(equation, nistDataObject, inStartValues, inStartValuesString, inPrintFlag):

    if nistDataObject.RawDataIn_XY_Format != "": # 2D data
        rawData = nistDataObject.RawDataIn_XY_Format
    else: # 3D data
        rawData = nistDataObject.RawDataIn_XYZ_Format
    
    pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(rawData, equation, False)
    
    equation.estimatedCoefficients = inStartValues
    
    equation.Solve()
    
    ssq = equation.CalculateAllDataFittingTarget(equation.solvedCoefficients)
    
    #
    # See the NIST note at the top of this file regarding dignificant digits.
    # NIST files truncate SSQ to 10 decimal places.  First check if 8 decimal
    # places (to allow for machine precision, rounding, etc) in Python
    # gives the same result as NIST, then compare actual values if that fails
    # as it is possible though very, very unlikely that pyeq2 fits better than NIST.
    ssqString = "%-.11E" % (ssq)
    if (ssqString[:10] + ssqString[-4:]) == (nistDataObject.ResidualSumOfSquaresString[:10] + nistDataObject.ResidualSumOfSquaresString[-4:]):
        compareString = '- equal to NIST'
        betterThanOrEqualToNIST = True
    else:
        deltaSSQ = nistDataObject.ResidualSumOfSquaresValue - ssq
        if deltaSSQ > 0.0: # NIST gives values to 10 decimal places
            compareString = '- better than NIST'
            betterThanOrEqualToNIST = True
        elif deltaSSQ < 0.0:
            compareString = '- worse than NIST'
            betterThanOrEqualToNIST = False
        else:
            compareString = '- equal to NIST'
            betterThanOrEqualToNIST = True
    
    
    if inPrintFlag:
        print(equation.GetDisplayName(), str(equation.GetDimensionality()) + "D", '- using "' + inStartValuesString + '" values')
        print(equation.fittingTargetDictionary[equation.fittingTarget], '=',)
        print(ssqString + ', should be',)
        print(nistDataObject.ResidualSumOfSquaresValue, compareString)
        
        print("Parameters:")
        for i in range(len(equation.solvedCoefficients)):
            spacer = ' '
            if equation.solvedCoefficients[i] < 0.0:
                spacer = ''
            print("    %s = %s%-.10E" % (equation.GetCoefficientDesignators()[i], spacer, equation.solvedCoefficients[i]),)
            print('(NIST Cert. %s%-.10E, NIST est. %s%-.5E' % (spacer, nistDataObject.CertifiedValues[i], spacer, inStartValues[i]))
        
        print()
    
    return betterThanOrEqualToNIST
 def test_SplineSolve_2D(self):
     resultShouldBe = (numpy.array([5.357, 5.357, 5.357, 5.357, 9.861, 9.861, 9.861, 9.861]),
                       numpy.array([0.38297001, 1.95535226, 4.59605664, 7.16162379, 0.0, 0.0, 0.0, 0.0]),
                       3
                      )
     model = pyeq2.Models_2D.Spline.Spline(inSmoothingFactor = 1.0, inXOrder = 3)
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(model.exampleData, model, False)
     result = model.Solve()
     self.assertTrue(numpy.allclose(result[0], resultShouldBe[0], rtol=1.0E-06, atol=1.0E-300))
     self.assertTrue(numpy.allclose(result[1], resultShouldBe[1], rtol=1.0E-06, atol=1.0E-300))
     self.assertEqual(result[2], resultShouldBe[2])
Example #36
0
 def test_SplineSolve_3D(self):
     resultShouldBe = (numpy.array([0.607, 0.607, 0.607, 3.017, 3.017, 3.017]),
                       numpy.array([1.984, 1.984, 1.984, 3.153, 3.153, 3.153]),
                       numpy.array([2.33418963, 1.80079612, 5.07902936, 0.54445029, 1.04110843, 2.14180324, 0.26992805, 0.39148852, 0.8177307])
                      )
     model = pyeq2.Models_3D.Spline.Spline(inSmoothingFactor = 1.0, inXOrder = 2, inYOrder = 2)
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(model.exampleData, model, False)
     result = model.Solve()
     self.assertTrue(numpy.allclose(result[0], resultShouldBe[0], rtol=1.0E-06, atol=1.0E-300))
     self.assertTrue(numpy.allclose(result[1], resultShouldBe[1], rtol=1.0E-06, atol=1.0E-300))
     self.assertTrue(numpy.allclose(result[2], resultShouldBe[2], rtol=1.0E-06, atol=1.0E-300))
Example #37
0
 def test_SplineSolve_2D(self):
     resultShouldBe = (numpy.array([5.357, 5.357, 5.357, 5.357, 9.861, 9.861, 9.861, 9.861]),
                       numpy.array([0.38297001, 1.95535226, 4.59605664, 7.16162379, 0.0, 0.0, 0.0, 0.0]),
                       3
                      )
     model = pyeq2.Models_2D.Spline.Spline(inSmoothingFactor = 1.0, inXOrder = 3)
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(model.exampleData, model, False)
     result = model.Solve()
     self.assertTrue(numpy.allclose(result[0], resultShouldBe[0], rtol=1.0E-06, atol=1.0E-300))
     self.assertTrue(numpy.allclose(result[1], resultShouldBe[1], rtol=1.0E-06, atol=1.0E-300))
     self.assertEqual(result[2], resultShouldBe[2])
 def test_SplineSolve_3D(self):
     resultShouldBe = (numpy.array([0.607, 0.607, 0.607, 3.017, 3.017, 3.017]),
                       numpy.array([1.984, 1.984, 1.984, 3.153, 3.153, 3.153]),
                       numpy.array([2.33418963, 1.80079612, 5.07902936, 0.54445029, 1.04110843, 2.14180324, 0.26992805, 0.39148852, 0.8177307])
                      )
     model = pyeq2.Models_3D.Spline.Spline(inSmoothingFactor = 1.0, inXOrder = 2, inYOrder = 2)
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(model.exampleData, model, False)
     result = model.Solve()
     self.assertTrue(numpy.allclose(result[0], resultShouldBe[0], rtol=1.0E-06, atol=1.0E-300))
     self.assertTrue(numpy.allclose(result[1], resultShouldBe[1], rtol=1.0E-06, atol=1.0E-300))
     self.assertTrue(numpy.allclose(result[2], resultShouldBe[2], rtol=1.0E-06, atol=1.0E-300))
 def test_SolveUsingODR_2D(self):
     coefficientsShouldBe = numpy.array([-8.04624, 1.53032])
     model = pyeq2.Models_2D.Polynomial.Linear('ODR')
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(
         DataForUnitTests.asciiDataInColumns_2D, model, False)
     coefficients = pyeq2.solverService().SolveUsingODR(model)
     self.assertTrue(
         numpy.allclose(coefficients,
                        coefficientsShouldBe,
                        rtol=1.0E-03,
                        atol=1.0E-300))
 def test_SolveUsingDE_2D(self):
     coefficientsShouldBe = numpy.array([-6.15515504031, 1.21618173729])
     model = pyeq2.Models_2D.UserDefinedFunction.UserDefinedFunction(
         'SSQABS', 'Default', 'm*X + b')
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(
         DataForUnitTests.asciiDataInColumns_2D_small, model, False)
     coefficients = pyeq2.solverService().SolveUsingDE(model)
     self.assertTrue(
         numpy.allclose(coefficients,
                        coefficientsShouldBe,
                        rtol=1.0E-06,
                        atol=1.0E-300))
 def test_SolveUsingLinear_2D(self):
     coefficientsShouldBe = numpy.array(
         [-8.0191356407516956E+00, 1.5264472941853220E+00])
     model = pyeq2.Models_2D.Polynomial.Linear('SSQABS')
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(
         DataForUnitTests.asciiDataInColumns_2D, model, False)
     coefficients = pyeq2.solverService().SolveUsingLinear(model)
     self.assertTrue(
         numpy.allclose(coefficients,
                        coefficientsShouldBe,
                        rtol=1.0E-10,
                        atol=1.0E-300))
Example #42
0
def fitEquationUsingDispyCluster(inEquationString, inFittingTargetString, inExtendedVersionString, inTextData):
	
    # individual cluster nodes must be able to import pyeq2
    import pyeq2

    exec('equation = ' + inEquationString +'("' + inFittingTargetString + '", "' + inExtendedVersionString + '")')
    pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(inTextData, equation, False)
    equation.Solve()
    fittedTarget = equation.CalculateAllDataFittingTarget(equation.solvedCoefficients)
   
    # this result list allows easy sorting of multiple results later
    return [fittedTarget, inEquationString, equation.solvedCoefficients]
Example #43
0
    def OnFit3D(self, evt):
        textData = str(self.text_3D.GetValue())
        equationSelection = self.rbEqChoice_3D.GetStringSelection()
        fittingTargetSelection = self.rbFittingTargetChoice_3D.GetStringSelection()

        # the GUI's fitting target string contains what we need - extract it
        fittingTarget = fittingTargetSelection.split("(")[1].split(")")[0]

        if equationSelection == "Linear Polynomial":
            self.equation = pyeq2.Models_3D.Polynomial.Linear(fittingTarget)
        if equationSelection == "Full Quadratic Polynomial":
            self.equation = pyeq2.Models_3D.Polynomial.FullQuadratic(fittingTarget)
        if equationSelection == "Full Cubic Polynomial":
            self.equation = pyeq2.Models_3D.Polynomial.FullCubic(fittingTarget)
        if equationSelection == "Monkey Saddle A":
            self.equation = pyeq2.Models_3D.Miscellaneous.MonkeySaddleA(fittingTarget)
        if equationSelection == "Gaussian Curvature Of Whitneys Umbrella A":
            self.equation = pyeq2.Models_3D.Miscellaneous.GaussianCurvatureOfWhitneysUmbrellaA(fittingTarget)
        if equationSelection == "NIST Nelson Autolog":
            self.equation = pyeq2.Models_3D.NIST.NIST_NelsonAutolog(fittingTarget)
        if equationSelection == "Custom Polynomial One":
            self.equation = pyeq2.Models_3D.Polynomial.UserSelectablePolynomial(fittingTarget, "Default", 3, 1)

        # convert text to numeric data checking for log of negative numbers, etc.
        try:
            pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(textData, self.equation, False)
        except:
            wx.MessageBox(self.equation.reasonWhyDataRejected, "Error")
            return

        # check for number of coefficients > number of data points to be fitted
        coeffCount = len(self.equation.GetCoefficientDesignators())
        dataCount = len(self.equation.dataCache.allDataCacheDictionary["DependentData"])
        if coeffCount > dataCount:
            wx.MessageBox(
                "This equation requires a minimum of "
                + str(coeffCount)
                + " data points, you have supplied "
                + repr(dataCount)
                + ".",
                "Error",
            )
            return

        # Now the status dialog is used. Disable fitting buttons until thread completes
        self.btnFit2D.Disable()
        self.btnFit3D.Disable()
        self.statusBox.text.SetValue("")
        self.statusBox.Show()  # hidden by OnThreadStatus() when thread completes

        # thread will automatically start to run
        self.fittingWorkerThread = CustomThreads.FittingThread(self, self.equation)
Example #44
0
    def OnFit2D(self, evt):
        textData = str(self.text_2D.GetValue())
        equationSelection = self.rbEqChoice_2D.GetStringSelection()
        fittingTargetSelection = self.rbFittingTargetChoice_2D.GetStringSelection()

        # the GUI's fitting target string contains what we need - extract it
        fittingTarget = fittingTargetSelection.split("(")[1].split(")")[0]

        if equationSelection == "Linear Polynomial":
            self.equation = pyeq2.Models_2D.Polynomial.Linear(fittingTarget)
        if equationSelection == "Quadratic Polynomial":
            self.equation = pyeq2.Models_2D.Polynomial.Quadratic(fittingTarget)
        if equationSelection == "Cubic Polynomial":
            self.equation = pyeq2.Models_2D.Polynomial.Cubic(fittingTarget)
        if equationSelection == "Witch Of Maria Agnesi A":
            self.equation = pyeq2.Models_2D.Miscellaneous.WitchOfAgnesiA(fittingTarget)
        if equationSelection == "VanDeemter Chromatography":
            self.equation = pyeq2.Models_2D.Engineering.VanDeemterChromatography(fittingTarget)
        if equationSelection == "Gamma Ray Angular Distribution (degrees) B":
            self.equation = pyeq2.Models_2D.LegendrePolynomial.GammaRayAngularDistributionDegreesB(fittingTarget)
        if equationSelection == "Exponential With Offset":
            self.equation = pyeq2.Models_2D.Exponential.Exponential(fittingTarget, "Offset")

        # convert text to numeric data checking for log of negative numbers, etc.
        try:
            pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(textData, self.equation, False)
        except:
            wx.MessageBox(self.equation.reasonWhyDataRejected, "Error")
            return

        # check for number of coefficients > number of data points to be fitted
        coeffCount = len(self.equation.GetCoefficientDesignators())
        dataCount = len(self.equation.dataCache.allDataCacheDictionary["DependentData"])
        if coeffCount > dataCount:
            wx.MessageBox(
                "This equation requires a minimum of "
                + str(coeffCount)
                + " data points, you have supplied "
                + repr(dataCount)
                + ".",
                "Error",
            )
            return

        # Now the status dialog is used. Disable fitting buttons until thread completes
        self.btnFit2D.Disable()
        self.btnFit3D.Disable()
        self.statusBox.text.SetValue("")
        self.statusBox.Show()  # hidden by OnThreadStatus() when thread completes

        # thread will automatically start to tun
        self.fittingWorkerThread = CustomThreads.FittingThread(self, self.equation)
 def test_SolveUsingDE_3D(self):
     coefficientsShouldBe = numpy.array(
         [-0.206068766376, -0.644872592849, 1.13361007134])
     model = pyeq2.Models_3D.UserDefinedFunction.UserDefinedFunction(
         'SSQABS', 'Default', 'a + b*X + c*Y')
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(
         DataForUnitTests.asciiDataInColumns_3D_small, model, False)
     coefficients = pyeq2.solverService().SolveUsingDE(model)
     self.assertTrue(
         numpy.allclose(coefficients,
                        coefficientsShouldBe,
                        rtol=1.0E-06,
                        atol=1.0E-300))
def SetParametersAndFit(inEquation, inPrintStatus): # utility function
    global globalDataCache
    global globalReducedDataCache
    global globalRawData

    inEquation.dataCache = globalDataCache
    if inEquation.dataCache.allDataCacheDictionary == {}:
        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(globalRawData, inEquation, False)
        
    inEquation.dataCache.CalculateNumberOfReducedDataPoints(inEquation)
    if globalReducedDataCache.has_key(inEquation.numberOfReducedDataPoints):
        inEquation.dataCache.reducedDataCacheDictionary = globalReducedDataCache[inEquation.numberOfReducedDataPoints]
    else:
        inEquation.dataCache.reducedDataCacheDictionary = {}
 
    try:
        # check for number of coefficients > number of data points to be fitted
        if len(inEquation.GetCoefficientDesignators()) > len(inEquation.dataCache.allDataCacheDictionary['DependentData']):
            return None

        # check for functions requiring non-zero nor non-negative data such as 1/x, etc.
        if inEquation.ShouldDataBeRejected(inEquation):
            return None

        if inPrintStatus:
            print('Process ID', str(os.getpid()), 'Fitting', inEquation.__module__, "'" + inEquation.GetDisplayName() + "'")
        
        inEquation.Solve()

        if not globalReducedDataCache.has_key(inEquation.numberOfReducedDataPoints):
            globalReducedDataCache[inEquation.numberOfReducedDataPoints] = inEquation.dataCache.reducedDataCacheDictionary
        
        target = inEquation.CalculateAllDataFittingTarget(inEquation.solvedCoefficients)
        if target > 1.0E290: # error too large
            return None
    except:
        print("Exception in " + inEquation.__class__.__name__ + '\n' + str(sys.exc_info()[0]) + '\n' + str(sys.exc_info()[1]) + '\n')
        return None

    t0 = copy.deepcopy(inEquation.__module__)
    t1 = copy.deepcopy(inEquation.__class__.__name__)
    t2 = copy.deepcopy(inEquation.extendedVersionHandler.__class__.__name__.split('_')[1])
    t3 = copy.deepcopy(target)
    t4 = copy.deepcopy(inEquation.solvedCoefficients)
    t5 = copy.deepcopy(inEquation.polyfunctional2DFlags)
    t6 = copy.deepcopy(inEquation.xPolynomialOrder)
    t7 = copy.deepcopy(inEquation.rationalNumeratorFlags)
    t8 = copy.deepcopy(inEquation.rationalDenominatorFlags)

    return [t0,t1,t2,t3,t4,t5,t6,t7,t8]
    def test_ExtendedVersion_Asymptotic_Exponential_A_WithExponentialDecayAndOffset_2D(self):
        equation = pyeq2.Models_2D.Exponential.AsymptoticExponentialA('SSQABS', 'Exponential Decay And Offset')
        self.assertEqual(equation.extendedVersionHandler.__class__.__name__, 'ExtendedVersionHandler_ExponentialDecayAndOffset')
        self.assertEqual(equation.GetDisplayHTML(), 'y = 1.0 - a<sup>x</sup><br>y = y / (b * exp(x)) + Offset')
        self.assertEqual(equation.GetDisplayName(), 'Asymptotic Exponential A With Exponential Decay And Offset')
        self.assertEqual(equation.GetCoefficientDesignators(), ['a', 'b', 'Offset'])
        self.assertEqual(len(equation.GetDataCacheFunctions()), 2)
        self.assertFalse(equation.CanLinearSolverBeUsedForSSQABS())

        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_2D, equation, False)
        
        equation.Solve()
        fittingTarget = equation.CalculateAllDataFittingTarget(equation.solvedCoefficients)
        self.assertTrue(fittingTarget <= 0.017)
Example #48
0
    def test_ExtendedVersion_Exponential_WithLinearDecay_2D(self):
        equation = pyeq2.Models_2D.Exponential.Exponential('SSQABS', 'Linear Decay')
        self.assertEqual(equation.extendedVersionHandler.__class__.__name__, 'ExtendedVersionHandler_LinearDecay')
        self.assertEqual(equation.GetDisplayHTML(), 'y = a * exp(bx)<br>y = y / x')
        self.assertEqual(equation.GetDisplayName(), 'Exponential With Linear Decay')
        self.assertEqual(equation.GetCoefficientDesignators(), ['a', 'b'])
        self.assertEqual(len(equation.GetDataCacheFunctions()), 1)
        self.assertFalse(equation.CanLinearSolverBeUsedForSSQABS())

        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_2D, equation, False)
        
        equation.Solve()
        coefficientsShouldBe = numpy.array([0.25868186, 0.57252871])
        self.assertTrue(numpy.allclose(equation.solvedCoefficients, coefficientsShouldBe, rtol=1.0E-06, atol=1.0E-300))
Example #49
0
    def test_ExtendedVersion_Inverse_Exponential_WithOffset_2D(self):
        equation = pyeq2.Models_2D.Exponential.Exponential('SSQABS', 'Inverse With Offset')
        self.assertEqual(equation.extendedVersionHandler.__class__.__name__, 'ExtendedVersionHandler_InverseWithOffset')
        self.assertEqual(equation.GetDisplayHTML(), 'y = a * exp(bx)<br>y = x / y + Offset')
        self.assertEqual(equation.GetDisplayName(), 'Inverse Exponential With Offset')
        self.assertEqual(equation.GetCoefficientDesignators(), ['a', 'b', 'Offset'])
        self.assertEqual(len(equation.GetDataCacheFunctions()), 1)
        self.assertFalse(equation.CanLinearSolverBeUsedForSSQABS())

        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_2D, equation, False)
        
        equation.Solve()
        coefficientsShouldBe = numpy.array([1.55291718, -0.06133912, -4.44443162])
        self.assertTrue(numpy.allclose(equation.solvedCoefficients, coefficientsShouldBe, rtol=1.0E-06, atol=1.0E-300))
Example #50
0
    def test_ExtendedVersion_Inverse_Exponential_2D(self):
        equation = pyeq2.Models_2D.Exponential.Exponential('SSQABS', 'Inverse')
        self.assertEqual(equation.extendedVersionHandler.__class__.__name__, 'ExtendedVersionHandler_Inverse')
        self.assertEqual(equation.GetDisplayHTML(), 'y = a * exp(bx)<br>y = x / y')
        self.assertEqual(equation.GetDisplayName(), 'Inverse Exponential')
        self.assertEqual(equation.GetCoefficientDesignators(), ['a', 'b'])
        self.assertEqual(len(equation.GetDataCacheFunctions()), 1)
        self.assertFalse(equation.CanLinearSolverBeUsedForSSQABS())

        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_2D, equation, False)
        
        equation.Solve()
        coefficientsShouldBe = numpy.array([30.67342834, -0.31776877])
        self.assertTrue(numpy.allclose(equation.solvedCoefficients, coefficientsShouldBe, rtol=1.0E-06, atol=1.0E-300))
Example #51
0
    def test_ExtendedVersion_Reciprocal_Exponential_2D(self):
        equation = pyeq2.Models_2D.Exponential.Exponential('SSQABS', 'Reciprocal')
        self.assertEqual(equation.extendedVersionHandler.__class__.__name__, 'ExtendedVersionHandler_Reciprocal')
        self.assertEqual(equation.GetDisplayHTML(), 'y = a * exp(bx)<br>y = 1.0 / y')
        self.assertEqual(equation.GetDisplayName(), 'Reciprocal Exponential')
        self.assertEqual(equation.GetCoefficientDesignators(), ['a', 'b'])
        self.assertEqual(len(equation.GetDataCacheFunctions()), 1)
        self.assertFalse(equation.CanLinearSolverBeUsedForSSQABS())

        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_2D, equation, False)
        
        equation.Solve()
        coefficientsShouldBe = numpy.array([1.0869969588803379E+01, -4.4497258666306111E-01])
        self.assertTrue(numpy.allclose(equation.solvedCoefficients, coefficientsShouldBe, rtol=1.0E-06, atol=1.0E-300))
Example #52
0
    def test_ExtendedVersion_Asymptotic_Exponential_A_WithExponentialDecayAndOffset_2D(self):
        equation = pyeq2.Models_2D.Exponential.AsymptoticExponentialA('SSQABS', 'Exponential Decay And Offset')
        self.assertEqual(equation.extendedVersionHandler.__class__.__name__, 'ExtendedVersionHandler_ExponentialDecayAndOffset')
        self.assertEqual(equation.GetDisplayHTML(), 'y = 1.0 - a<sup>x</sup><br>y = y / (d * exp(x)) + Offset')
        self.assertEqual(equation.GetDisplayName(), 'Asymptotic Exponential A With Exponential Decay And Offset')
        self.assertEqual(equation.GetCoefficientDesignators(), ['a', 'b', 'Offset'])
        self.assertEqual(len(equation.GetDataCacheFunctions()), 2)
        self.assertFalse(equation.CanLinearSolverBeUsedForSSQABS())

        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_2D, equation, False)
        
        equation.Solve()
        coefficientsShouldBe = numpy.array([2.69273579217, 0.00518863941, 182.725486049])
        self.assertTrue(numpy.allclose(equation.solvedCoefficients, coefficientsShouldBe, rtol=1.0E-06, atol=1.0E-300))
    def test_ExtendedVersion_Inverse_Exponential_WithOffset_2D(self):
        equation = pyeq2.Models_2D.Exponential.Exponential('SSQABS', 'Inverse With Offset')
        self.assertEqual(equation.extendedVersionHandler.__class__.__name__, 'ExtendedVersionHandler_InverseWithOffset')
        self.assertEqual(equation.GetDisplayHTML(), 'y = a * exp(bx)<br>y = x / y + Offset')
        self.assertEqual(equation.GetDisplayName(), 'Inverse Exponential With Offset')
        self.assertEqual(equation.GetCoefficientDesignators(), ['a', 'b', 'Offset'])
        self.assertEqual(len(equation.GetDataCacheFunctions()), 1)
        self.assertFalse(equation.CanLinearSolverBeUsedForSSQABS())

        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_2D, equation, False)
        
        equation.Solve()
        fittingTarget = equation.CalculateAllDataFittingTarget(equation.solvedCoefficients)
        self.assertTrue(fittingTarget <= 0.018)
 def test_SolveUsingLinear_3D(self):
     coefficientsShouldBe = numpy.array([
         2.8658381589774945E-01, -9.0215775175410395E-01,
         1.1548386445491325E+00
     ])
     model = pyeq2.Models_3D.Polynomial.Linear('SSQABS')
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(
         DataForUnitTests.asciiDataInColumns_3D, model, False)
     coefficients = pyeq2.solverService().SolveUsingLinear(model)
     self.assertTrue(
         numpy.allclose(coefficients,
                        coefficientsShouldBe,
                        rtol=1.0E-10,
                        atol=1.0E-300))
 def test_SolveUsingLevenbergMarquardt_2D(self):
     coefficientsShouldBe = numpy.array([-8.01913565, 1.5264473])
     model = pyeq2.Models_2D.Polynomial.Linear('SSQABS')
     model.estimatedCoefficients = numpy.array(
         [-4.0, 2.0])  # starting values for the simplex solver
     pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(
         DataForUnitTests.asciiDataInColumns_2D, model, False)
     coefficients = pyeq2.solverService().SolveUsingLevenbergMarquardt(
         model)
     self.assertTrue(
         numpy.allclose(coefficients,
                        coefficientsShouldBe,
                        rtol=1.0E-06,
                        atol=1.0E-300))
Example #56
0
def SetParametersAndFit(inEquation, inPrintStatus): # utility function
    global globalDataCache
    global globalReducedDataCache
    global globalRawData

    inEquation.dataCache = globalDataCache
    if inEquation.dataCache.allDataCacheDictionary == {}:
        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(globalRawData, inEquation, False)
        
    inEquation.dataCache.CalculateNumberOfReducedDataPoints(inEquation)
    if globalReducedDataCache.has_key(inEquation.numberOfReducedDataPoints):
        inEquation.dataCache.reducedDataCacheDictionary = globalReducedDataCache[inEquation.numberOfReducedDataPoints]
    else:
        inEquation.dataCache.reducedDataCacheDictionary = {}
 
    try:
        # check for number of coefficients > number of data points to be fitted
        if len(inEquation.GetCoefficientDesignators()) > len(inEquation.dataCache.allDataCacheDictionary['DependentData']):
            return None

        # check for functions requiring non-zero nor non-negative data such as 1/x, etc.
        if inEquation.ShouldDataBeRejected(inEquation):
            return None

        if inPrintStatus:
            print 'Process ID', str(os.getpid()), 'Fitting', inEquation.__module__, "'" + inEquation.GetDisplayName() + "'"
        
        inEquation.Solve()

        if not globalReducedDataCache.has_key(inEquation.numberOfReducedDataPoints):
            globalReducedDataCache[inEquation.numberOfReducedDataPoints] = inEquation.dataCache.reducedDataCacheDictionary
        
        target = inEquation.CalculateAllDataFittingTarget(inEquation.solvedCoefficients)
        if target > 1.0E290: # error too large
            return None
    except:
        print "Exception in " + inEquation.__class__.__name__ + '\n' + str(sys.exc_info()[0]) + '\n' + str(sys.exc_info()[1]) + '\n'
        return None

    t0 = copy.deepcopy(inEquation.__module__)
    t1 = copy.deepcopy(inEquation.__class__.__name__)
    t2 = copy.deepcopy(inEquation.extendedVersionHandler.__class__.__name__.split('_')[1])
    t3 = copy.deepcopy(target)
    t4 = copy.deepcopy(inEquation.solvedCoefficients)
    t5 = copy.deepcopy(inEquation.polyfunctional2DFlags)
    t6 = copy.deepcopy(inEquation.xPolynomialOrder)
    t7 = copy.deepcopy(inEquation.rationalNumeratorFlags)
    t8 = copy.deepcopy(inEquation.rationalDenominatorFlags)

    return [t0,t1,t2,t3,t4,t5,t6,t7,t8]
Example #57
0
    def test_ExtendedVersion_Asymptotic_Exponential_A_WithExponentialGrowth_2D(self):
        equation = pyeq2.Models_2D.Exponential.AsymptoticExponentialA('SSQABS', 'Exponential Growth')
        self.assertEqual(equation.extendedVersionHandler.__class__.__name__, 'ExtendedVersionHandler_ExponentialGrowth')
        self.assertEqual(equation.GetDisplayHTML(), 'y = 1.0 - a<sup>x</sup><br>y = y * (c * exp(x))')
        self.assertEqual(equation.GetDisplayName(), 'Asymptotic Exponential A With Exponential Growth')
        self.assertEqual(equation.GetCoefficientDesignators(), ['a', 'b'])
        self.assertEqual(len(equation.GetDataCacheFunctions()), 2)
        self.assertFalse(equation.CanLinearSolverBeUsedForSSQABS())

        pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(DataForUnitTests.asciiDataInColumns_2D, equation, False)
        
        equation.lowerCoefficientBounds = []
        equation.Solve()
        coefficientsShouldBe = numpy.array([0.001, 0.00041378])
        self.assertTrue(numpy.allclose(equation.solvedCoefficients, coefficientsShouldBe, rtol=1.0, atol=1.0E-300))