source: sasview/test/corfunc/test/utest_corfunc.py @ 932519a

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalcmagnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 932519a was 932519a, checked in by Paul Kienzle <pkienzle@…>, 7 years ago

Merge branch 'master' into corfunc3d

  • Property mode set to 100644
File size: 4.4 KB
Line 
1"""
2Unit Tests for CorfuncCalculator class
3"""
4
5import unittest
6import time
7import numpy as np
8from sas.sascalc.corfunc.corfunc_calculator import CorfuncCalculator
9from sas.sascalc.dataloader.data_info import Data1D
10
11
12class TestCalculator(unittest.TestCase):
13
14    def setUp(self):
15        self.data = load_data()
16        # Note: to generate target values from the GUI:
17        # * load the data from test/corfunc/test/98929.txt
18        # * set qrange to (0, 0.013), (0.15, 0.24)
19        # * select fourier transform type
20        # * click Calculate Bg
21        # * click Extrapolate
22        # * click Compute Parameters
23        # * copy the Guinier and Porod values to the extrapolate function
24        # * for each graph, grab the data from DataInfo and store it in _out.txt
25        self.calculator = CorfuncCalculator(data=self.data, lowerq=0.013,
26            upperq=(0.15, 0.24))
27        self.calculator.background = 0.3
28        self.extrapolation = None
29        self.transformation = None
30        self.results = [np.loadtxt(filename+"_out.txt").T[2]
31                        for filename in ("gamma1", "gamma3", "idf")]
32
33    def extrapolate(self):
34        params, extrapolation, s2 = self.calculator.compute_extrapolation()
35        # Check the extrapolation parameters
36        self.assertAlmostEqual(params['A'], 4.18970, places=5)
37        self.assertAlmostEqual(params['B'], -25469.9, places=1)
38        self.assertAlmostEqual(params['K'], 4.44660e-5, places=10)
39        self.assertAlmostEqual(params['sigma'], 1.70181e-10, places=15)
40
41        # Ensure the extraplation tends to the background value
42        self.assertAlmostEqual(extrapolation.y[-1], self.calculator.background)
43
44        # Test extrapolation for q values between 0.02 and 0.24
45        mask = np.logical_and(self.data.x > 0.02, self.data.x < 0.24)
46        qs = self.data.x[mask]
47        iqs = self.data.y[mask]
48
49        for q, iq in zip(qs, iqs):
50            # Find the q value in the extraplation nearest to the value in
51            # the data
52            q_extrap = min(extrapolation.x, key=lambda x:abs(x-q))
53            # Find the index of this value in the extrapolation
54            index = list(extrapolation.x).index(q_extrap)
55            # Find it's corresponding intensity value
56            iq_extrap = extrapolation.y[index]
57            # Check the extrapolation agrees to the data at this point to 1 d.p
58            self.assertAlmostEqual(iq_extrap, iq, 1)
59
60        self.extrapolation = extrapolation
61
62    def transform(self):
63        self.calculator.compute_transform(self.extrapolation, 'fourier',
64            completefn=self.transform_callback)
65        # Transform is performed asynchronously; give it time to run
66        while True:
67            time.sleep(0.001)
68            if not self.calculator.transform_isrunning():
69                break
70
71    def transform_callback(self, transforms):
72        transform1, transform3, idf = transforms
73        self.assertIsNotNone(transform1)
74        self.assertAlmostEqual(transform1.y[0], 1)
75        self.assertAlmostEqual(transform1.y[-1], 0, 5)
76        self.transformation = transforms
77
78    def extract_params(self):
79        params = self.calculator.extract_parameters(self.transformation[0])
80        self.assertIsNotNone(params)
81        self.assertEqual(len(params), 6)
82        self.assertLess(abs(params['max']-75), 2.5) # L_p ~= 75
83
84    def check_transforms(self):
85        gamma1, gamma3, idf = self.transformation
86        gamma1_out, gamma3_out, idf_out = self.results
87        def compare(a, b):
88            return max(abs((a-b)/b))
89        #np.savetxt("gamma1_test.txt", np.vstack((gamma1.x[gamma1.x<=200.], gamma1.y[gamma1.x<=200.])).T)
90        self.assertLess(compare(gamma1.y[gamma1.x<=200.], gamma1_out), 1e-10)
91        self.assertLess(compare(gamma3.y[gamma3.x<=200.], gamma3_out), 1e-10)
92        self.assertLess(compare(idf.y[idf.x<=200.], idf_out), 1e-10)
93
94    # Ensure tests are ran in correct order;
95    # Each test depends on the one before it
96    def test_calculator(self):
97        steps = [self.extrapolate, self.transform, self.extract_params, self.check_transforms]
98        for test in steps:
99            try:
100                test()
101            except Exception as e:
102                raise
103                self.fail("{} failed ({}: {})".format(test, type(e), e))
104
105
106def load_data(filename="98929.txt"):
107    data = np.loadtxt(filename, dtype=np.float64)
108    q = data[:,0]
109    iq = data[:,1]
110    return Data1D(x=q, y=iq)
111
112if __name__ == '__main__':
113    unittest.main()
Note: See TracBrowser for help on using the repository browser.