source: sasview/sansrealspace/src/realspace/test/simulation_stimuli.py @ 8c050c1

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 8c050c1 was 8c050c1, checked in by Mathieu Doucet <doucetm@…>, 17 years ago

updated stimuli frequency to reflect usage model described in certification plan

  • Property mode set to 100644
File size: 10.8 KB
Line 
1"""Automated testing for simulation
2
3    To be compatible with testcase_generator, a simulus
4    class must have:
5        setup(self):  to initialize the test-case
6        getRandomStimulus(self): to get a random stimulus name
7        stimuli that inherit from the Stimulus class
8       
9    @copyright: University of Tennessee, 2007
10    @license: This software is provided as part of the DANSE project.
11
12"""
13
14import testcase_generator as generator
15from testcase_generator import Stimulus
16try:
17    import VolumeCanvas
18    print "Testing local VolumeCanvas\n"
19except:
20    import sans.realspace.VolumeCanvas as VolumeCanvas
21
22def randomModel():
23    """ Return a random model name """
24    from random import random
25    from math import floor
26   
27    model_list = ['sphere', 'cylinder', 'ellipsoid', 'singlehelix']
28    rnd_id = int(floor(random()*len(model_list)))
29   
30    return model_list[rnd_id]
31
32
33class Simulation:
34    """Simulation testing class"""
35   
36    # Probability of stopping a test case without
37    # adding additional stimuli
38    end_frequency = 0.1
39   
40    def __init__(self):
41        self.end_flag = False
42       
43    def reset(self):
44        self.end_flag = False
45   
46    def setup(self):
47        """Setup the canvas for stimuli application"""
48        return VolumeCanvas.VolumeCanvas()
49   
50    def getRandomStimulus(self):
51        """Return the name of a random stimulus"""
52       
53        from random import random
54       
55        # If the end flag is up, compute I(q) one last time
56        if self.end_flag == True:
57            return None
58       
59        # Get the list of stimuli
60        attrs = dir(self)
61        stim_list = []
62       
63        # Get the list of simuli and
64        # compute the total normalization
65        sum = 0
66        for item in attrs:
67            if item.endswith('Stimulus'):
68                obj = getattr(self, item)
69                if hasattr(obj, 'frequency'):
70                    stim_list.append(item)
71                    sum += getattr(self, item).frequency
72       
73        # Choose a stimulus
74        rnd = random()
75       
76        # Check if we need to stop
77        if rnd < self.end_frequency:
78            self.end_flag = True
79            return "GetIq"
80       
81        run_sum = 0
82        for item in stim_list:
83            run_sum += getattr(self, item).frequency/sum 
84            if run_sum >= rnd:
85                pos = item.index('Stimulus')
86               
87                return item[0:pos]
88       
89    class AddStimulus(Stimulus):
90        """Add an object to the canvas"""
91
92        frequency = 0.1
93       
94        def __call__(self, canvas):
95            """Apply stimulus"""
96            report = generator.StimulusReport(tag=self.name)
97       
98            # Select random model
99            add_model = randomModel()
100
101            # Add the model
102            handle = canvas.add(add_model)
103           
104            # Check that it is in the list of objects
105            if handle in canvas.getShapeList():
106                report.passed = 1
107            else:
108                report.log = "Add: tried to add %s" % add_model
109           
110            report.trace = "Added %s" % add_model
111           
112            return canvas, report
113   
114    class GetParamStimulus(Stimulus):
115        """Get the value of a canvas or shape parameter"""
116
117        frequency = 0.05
118       
119        def __call__(self, canvas):
120            """Apply stimulus"""
121            from random import random
122            import math
123           
124            report = generator.StimulusReport(tag=self.name)
125       
126            # Read a parameter
127            #TODO: access shape parameters
128            rnd = random()
129            i_rnd = int(math.floor(rnd*len(canvas.params)))
130            par_name = canvas.params.keys()[i_rnd]
131            value = canvas.getParam(par_name)
132           
133            # Check that it is in the list of objects
134            try:
135                float(value)
136                report.passed = 1
137            except:
138                report.log = "get: bad value for [%s]" % par_name
139           
140            report.trace = "Read %s" % par_name
141           
142            return canvas, report
143   
144    class GetIqStimulus(Stimulus):
145        """Calculate I(q)"""
146
147        frequency = 0.25
148       
149        def __call__(self, canvas):
150            report = generator.StimulusReport(tag=self.name)
151           
152            # Check that a float is returned
153            # Validation testing will be done elsewhere
154            value = canvas.getIq(0.1)
155           
156            # Check that it is in the list of objects
157            try:
158                float(value)
159                report.passed = 1
160            except:
161                report.log = "GetIq: bad value for Iq "+str(value)
162           
163            report.trace = "I(q) = %g" % value
164            return canvas, report
165   
166    class GetIq2DStimulus(Stimulus):
167        """Calculate I(q)"""
168
169        frequency = 0.25
170       
171        def __call__(self, canvas):
172            report = generator.StimulusReport(tag=self.name)
173           
174            # Check that a float is returned
175            # Validation testing will be done elsewhere
176            value = canvas.getIq2D(0.01,0.01)
177           
178            # Check that it is in the list of objects
179            try:
180                float(value)
181                report.passed = 1
182            except:
183                report.log = "GetIq2D: bad value for Iq "+str(value)
184           
185            report.trace = "I(q) = %g" % value
186            return canvas, report
187   
188    class SetCanvasParamStimulus(Stimulus):
189        """Set the value of a canvas parameter"""
190
191        frequency = 0.05
192       
193        def __call__(self, canvas):
194            """Apply stimulus"""
195            from random import random
196            import math
197           
198            report = generator.StimulusReport(tag=self.name)
199       
200            # Read a parameter
201            rnd = random()
202            i_rnd = int(math.floor(rnd*len(canvas.params)))
203            par_name = canvas.params.keys()[i_rnd]
204           
205            # Get current value
206            current = canvas.getParam(par_name)
207           
208            # Set new value
209            rnd2 = random()
210            new_value = current*(1.0+rnd2)
211            canvas.setParam(par_name, new_value)
212           
213            # Read it back
214            current = canvas.getParam(par_name)
215           
216            # Check that the new value is correct
217            if current == new_value:
218                report.passed = 1
219            else:
220                report.log = "get: bad value for [%s]" % par_name
221           
222            report.trace = "Read %s" % par_name
223           
224            return canvas, report
225   
226    class SetShapeParamStimulus(Stimulus):
227        """Set the value of a canvas parameter"""
228
229        frequency = 0.1
230       
231        def __call__(self, canvas):
232            """Apply stimulus"""
233            from random import random
234            import math
235           
236            report = generator.StimulusReport(tag=self.name)
237       
238            # Read a parameter
239            rnd = random()
240            shape_list = canvas.getShapeList()
241
242            if len(shape_list)==0:
243                # No object available, let's test an error condition
244                try:
245                    canvas.setParam("shape0.test-radius", 1.0)
246                    report.log = "SetShapeParam: set didn't throw exception"
247                except:
248                    report.passed = 1
249                report.trace = "SetShapeParam: testing failure behavior"
250               
251            else: 
252                i_rnd = int(math.floor(rnd*len(shape_list)))
253                shape_name = shape_list[i_rnd]
254               
255                found = False
256                while found==False:
257                    rnd2 = random()
258                    par_keys = canvas.shapes[shape_name].params.keys()
259                    i_rnd2 = int(math.floor(rnd2*(len(par_keys))))
260                   
261                    short_name = par_keys[i_rnd2]
262                    par_name = "%s.%s" % (shape_name, short_name)
263                    if not short_name.lower() == "type":
264                        found= True
265               
266                # Get current value
267                current = canvas.getParam(par_name)
268               
269                # Set new value
270                if short_name in ['orientation', 'center']:
271                    new_value = [random(), random(), random()]
272                else:
273                    new_value = current*(1.0+random())
274
275                canvas.setParam(par_name, new_value)
276               
277                # Read it back
278                current = canvas.getParam(par_name)
279               
280                # Check that the new value is correct
281                if current == new_value:
282                    report.passed = 1
283                else:
284                    report.log = "get: bad value for [%s]" % par_name
285               
286                report.trace = "Read %s" % par_name
287           
288            return canvas, report
289   
290
291    class RemoveStimulus(Stimulus):
292        """Calculate I(q)"""
293
294        frequency = 0.05
295       
296        def __call__(self, canvas):
297            from random import random
298            import math
299           
300            report = generator.StimulusReport(tag=self.name)
301           
302            # Get list of shapes
303            if len(canvas.shapes)>0:
304                rnd = random()
305                i_rnd = int(math.floor(rnd*len(canvas.shapes)))
306                shape_name = canvas.shapes.keys()[i_rnd]
307               
308                canvas.delete(shape_name)
309                if shape_name in canvas.shapes.keys() \
310                    or shape_name in canvas.getShapeList():
311                    report.log = "Remove: object was not removed"
312                else:
313                    report.passed = 1
314               
315            else:
316                # No shape to remove: test bad remove call
317                try:
318                    canvas.delete("test-shape")
319                    report.log = "Remove: delete didn't throw exception"
320                except:
321                    report.passed = 1
322                report.trace = "Remove: testing failure behavior"
323           
324            return canvas, report
325   
326
327
328if __name__ == '__main__':
329    import sys
330   
331    stimuli = Simulation()
332   
333    if len(sys.argv)>1:
334        #t = generator.TestCase(stimuli, filename = "test-case.xml")
335        t = generator.TestCase(stimuli, filename = sys.argv[1])
336        print "Test passed =", t.run() 
337    else:   
338        g = generator.TestCaseGenerator(stimuli)
339        g.generateAndRun(200)
340   
341
342   
343   
Note: See TracBrowser for help on using the repository browser.