Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/test_suite.py
blob: d78b3f0c1b43a0d55e59d1033fd710fe2f4ed145 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
# coding: UTF8
# Copyright 2009 Thomas Jourdan
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import os
import sys
import unittest
import cairo
import ka_debug
import ka_factory
import ka_random
import ka_extensionpoint
import model_protozoon
import model_constraintpool
import model_population
import model_locus
import exon_color
import exon_buzzword
import exon_direction
import exon_position

EPSILON = 0.00001

class TestKandidModel(unittest.TestCase):

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def _neutral(self):
        cpool = model_constraintpool.ConstraintPool.get_pool()
        permitted = [x for x in ka_extensionpoint.list_extensions(exon_position.POSITION_CONSTRAINT) if x not in ['positionconstraint_centered']]
        cpool.set('/Position', exon_position.POSITION_CONSTRAINT, permitted)
        cpool.set('/LetterPress/Position', exon_position.POSITION_CONSTRAINT, permitted)
        cpool.set('/Protozoon/LetterPress/Position', exon_position.POSITION_CONSTRAINT, permitted)
        permitted = ['colorconstraint_none']
        cpool.set('/Color', exon_color.COLOR_CONSTRAINT, permitted)
        cpool.set('/Protozoon/Color/', exon_color.COLOR_CONSTRAINT, permitted)
        cpool.set('/MarkovChainLayer/Color', exon_color.COLOR_CONSTRAINT, permitted)
        cpool.set('/LetterPress/Color', exon_color.COLOR_CONSTRAINT, permitted)
        cpool.set('/Protozoon/LetterPress/Color', exon_color.COLOR_CONSTRAINT, permitted)
        cpool.set('/Protozoon/MarkovChainLayer/Color', exon_color.COLOR_CONSTRAINT, permitted)

        #/Protozoon/mergertypeconstraint ['flip', 'mask', 'rectangulartile', 'straight']
        permitted = [x for x in ka_factory.get_factory('merger').keys() if x not in ['straight', ]]
        cpool.set('/Protozoon', model_protozoon.MERGER_CONSTRAINT, permitted)
        
    def test_locus(self):
        self.assertEqual('/Locus',  model_locus.Locus('/').path)
        self.assertEqual('/A/Locus',  model_locus.Locus('/A').path)
        self.assertEqual('/A', model_locus.Locus('/A').get_trunk())
        self.assertEqual('/A/B', model_locus.Locus('/A/B').get_trunk())

    def test_html_formater(self):
        base_name = 'test_html_formater'
        base_folder = '/dev/shm/'
        formater = ka_extensionpoint.create('formater_html', base_name, 'test', base_folder)
        formater.header('Test title')
        formater.begin_list('l1')
        a_text = '&<>'
        formater.text_item(a_text)

        formater.begin_list('l2')
        cpool = model_constraintpool.ConstraintPool.get_pool()
        key = 'color'
        for cc in ka_extensionpoint.list_extensions(key+'constraint'):
            cpool.set('/'+key.capitalize(), key+'constraint', [cc])
            a_color = exon_color.Color('/', 0.5, 0.6, 0.7, 0.8)
            formater.color_item(a_color, 'Color ' + str(cc))
        formater.end_list()

        formater.end_list()
        formater.footer()
        file_path = formater.get_pathname('html')
        formater.write_html_file(file_path)
        exit_code = os.spawnvp(os.P_WAIT, 'tidy', ['tidy', '-i', file_path])
        self.assertEqual(0, exit_code)

    def test_protozon_formater(self):
        ka_random.set_flurry(9)
        cpool = model_constraintpool.ConstraintPool.get_pool()
        cpool.clear_all()

        ep_list = ka_extensionpoint.list_extensions('formater')
        self.assertTrue(len(ep_list) > 0)
        for ep_key in ep_list:
            a_protozoon = model_protozoon.Protozoon()
            a_protozoon.randomize()
            
            base_name = 'index'
            base_folder = '/dev/shm/'
            formater = ka_extensionpoint.create(ep_key, base_name, a_protozoon.get_unique_id(), base_folder)
            a_protozoon.explain(formater)

            file_path = formater.get_pathname('html')
            formater.write_html_file(file_path)
            exit_code = os.spawnvp(os.P_WAIT, 'tidy', ['tidy', '-i', file_path])
            self.assertEqual(0, exit_code)

    def _write_file(self, file_path, page):
        out_file = None
        try:
            out_file = open(file_path, 'w')
            out_file.write(page)
        except:
            self.fail('failed writing [%s] [%s] [%s]' % \
                       (out_file.name, sys.exc_info()[0], sys.exc_info()[1]))
        finally:
            if out_file:
                out_file.close()

    def test_constrain_pool(self):
        position = exon_position.Position('/', 0.1, 0.2)
        cpool = model_constraintpool.ConstraintPool.get_pool()
        cpool.get(position, exon_position.POSITION_CONSTRAINT)
        print cpool

    def test_limit(self):
        self.assertTrue(ka_random.limitate(-0.01) == 0.0)
        self.assertTrue(ka_random.limitate(0.01) == 0.01)
        self.assertTrue(ka_random.limitate(1.01) == 1.0)
        self.assertTrue(ka_random.limitate_range(-0.02, -0.01, 0.01) == -0.01)
        self.assertTrue(ka_random.limitate_range(0.01, -0.01, 0.01) == 0.01)
        self.assertTrue(ka_random.limitate_range(0.011, -0.01, 0.01) == 0.01)
        self.assertTrue(abs(ka_random.cyclic_limitate(-0.01) - 0.99) < EPSILON)
        self.assertTrue(abs(ka_random.cyclic_limitate(0.01) - 0.01) < EPSILON)
        self.assertTrue(abs(ka_random.cyclic_limitate(1.01) - 0.01) < EPSILON)
        for value in range(-20, 20):
            self.assertTrue(0.0 <= ka_random.limitate(0.1 * value) <= 1.0)
            self.assertTrue(0.0 <= ka_random.cyclic_limitate(0.1 * value) <= 1.0)

    def test_extensionpoint(self):
#        ka_extensionpoint.scann()
        ep_types = ka_extensionpoint.list_extension_types()
        self.assertTrue(len(ep_types) > 0)

        ep_list = ka_extensionpoint.list_extensions('colorconstraint')
        self.assertTrue(len(ep_list) > 0)
        for ep_key in ep_list:
            colorconstraint = ka_extensionpoint.create(ep_key, '/')
            self.assertEqual(4, len(colorconstraint.filter((.5, .5, .5, 1.))))

    def test_deepcopy(self):
        self._neutral()
        list1 = [exon_buzzword.Buzzword('/', [u'sugar', u'kandid', u'']), \
                 exon_color.Color('/', 0.1, 0.2, 0.3, 1.0), \
                 exon_direction.Direction('/', 0.1, 0.2), \
                 exon_position.Position('/', 0.1, 0.2), \
                ]
        list2 = ka_random.copy_list(list1)
        self.assertEqual(len(list1), len(list2))
        for index, i in enumerate(list1):
            self.assertEqual(list1[index], list2[index])
            self.assertTrue(list1[index] is not list2[index])
        
    def test_random(self):
        ka_random.set_flurry(0)
        seq = ka_random.crossing_sequence(10)
        for index in range(1,len(seq)):
            self.assertEqual(seq[0], seq[index])
        ka_random.set_flurry(9)
        seq = ka_random.crossingover([11], [21, 22, 23, 24, 25])
        print seq
        seq = ka_random.crossingover([11, 12, 13], [21, 22, 23, 24, 25])
        print seq
        seq = ka_random.crossingover([11, 12, 13], [21])
        print seq

    def test_positionconstraint(self):
        self._run_ep_test('position')

    def test_directionconstraint(self):
        self._run_ep_test('direction')

    def _run_ep_test(self, key):
        for flavor in ka_extensionpoint.list_extensions(key+'constraint'):
            constraint = ka_extensionpoint.create(flavor, '/')
            x_pos, y_pos = 0.1, 0.2
            x_pos, y_pos = constraint.filter(x_pos, y_pos)
            x_pos, y_pos = constraint.randomize()
            x_pos, y_pos = constraint.mutate(x_pos, y_pos)
            self.assertTrue(isinstance(x_pos, float))
            self.assertTrue(isinstance(y_pos, float))

    def test_classification(self):
        population_size = 12
        model = model_population.KandidModel(population_size)
        self.assertEqual(population_size, len(model.fitness))
        for fa in [1, 2, population_size-1]:
            model.fade_away = fa
            for i in range(population_size):
                model.fitness[i] = (population_size-i-1)*(1.0 / population_size)
            self._check_classification(population_size, model)
            for ft in [0.0, 5.0, 9.0]:
                for i in range(population_size):
                    model.fitness[i] = ft
                self._check_classification(population_size, model)

    def _check_classification(self, population_size, model):
        good, moderate, poor = model.classify()
        self.assertEqual(model.fade_away, len(poor))
        self.assertEqual(population_size, len(good) + len(moderate) + len(poor))
        self.assertTrue(good[0] in model.protozoans)
        self.assertFalse(model_population.contains_reference(good[0], moderate))
        self.assertFalse(model_population.contains_reference(good[0], poor))
        for mo in moderate:
            self.assertFalse(model_population.contains_reference(mo, poor))
            self.assertFalse(model_population.contains_reference(mo, good))
        for po in poor:
            self.assertFalse(model_population.contains_reference(po, moderate))
            self.assertFalse(model_population.contains_reference(po, good))

    def test_exon_position(self):
        self._run_exon_test('position', exon_position.Position, 0.5, 0.5)
            
    def test_exon_direction(self):
        self._run_exon_test('direction', exon_direction.Direction, 0.3, 0.4)
            
    def test_exon_buzzword(self):
        self._run_exon_test('buzzword', exon_buzzword.Buzzword, [u'a', u'b'])
            
    def _run_exon_test(self, key, constructor, *params):
        ka_random.set_flurry(9)
        self._neutral()
        
        cpool = model_constraintpool.ConstraintPool.get_pool()
        for cc in ka_extensionpoint.list_extensions(key+'constraint'):
            cpool.set('/'+key.capitalize(), key+'constraint', [cc])
            element1 = constructor('/', *params)
            element2 = element1.copy()
            for i in range(32):
                element3 = element1.crossingover(element2)
                self.assertEqual(element1, element2)
                self.assertEqual(element1, element3)
            equal = True
            for i in range(32):
                element2.randomize()
                element2.mutate()
                element2.shuffle()
                equal = equal and element1 == element2
            self.assertFalse(equal)
            self.assertEqual(element1, element3)
            
    def test_exon_color(self):
        ka_random.set_flurry(9)
        cpool = model_constraintpool.ConstraintPool.get_pool()
        cpool.clear_all()

        key = 'color'
        cpool = model_constraintpool.ConstraintPool.get_pool()

        for cc in ka_extensionpoint.list_extensions(key+'constraint'):
            cpool.set('/'+key.capitalize(), key+'constraint', [cc])
            a_color = exon_color.Color('/', 0.5, 0.5, 0.5, 1.0)
            self.assertFalse(a_color is a_color.crossingover( \
                                        exon_color.Color('/', 0.5, 0.5, 0.5, 1.0)))
            self.assertEqual(4, len(a_color.copy().rgba))
            a_color.randomize()
            self.assertEqual(4, len(a_color.rgba))
            for i in range(32):
                a_color.mutate()
            self.assertEqual(4, len(a_color.rgba))

        self._neutral()
        color1 = exon_color.Color('/', 1.0, 1.0, 1.0, 1.0)
        color2 = color1.copy()
        self.assertTrue(color2 is not color1)
        self.assertTrue(color2 == color1)
        color1.randomize()
        self.assertFalse(color2 == color1)
        for i in range(32):
            color3 = color1.crossingover(color2)
            self.assertTrue(color3 is not color1)
            self.assertTrue(color3 is not color2)
            self.assertTrue(color3 == color1 or color3 == color2)
        color4 = color3.copy()
        eq = True
        for i in range(32):
            color4.mutate()
            color4.shuffle()
            eq = eq and color4 == color3
        self.assertFalse(eq)
        
    def test_layer_factory(self):
        self._neutral()
        layer_factory = ka_factory.get_factory('layer')
        keys = layer_factory.keys()
        self.assertTrue(layer_factory.count() >= 1)
        self.assertEqual(len(keys), layer_factory.count())
        for layer_key in keys:
            self.assertTrue(layer_factory.create(layer_key, '/') is not None)
        self.assertTrue(layer_factory.create_random([keys[0]], '/') is not None)
        
    def test_layer(self):
        ka_random.set_flurry(9)
        self._neutral()
        
        layer_factory = ka_factory.get_factory('layer')
        for layer_key in layer_factory.keys():
            layer1 = layer_factory.create(layer_key, '/')
            layer2 = layer1.copy()
            self.assertTrue(layer2 is not layer1)
            self.assertTrue(layer2 == layer1)
            layer1.randomize()
            layer1.shuffle()
            if layer2 == layer1:
                pass
            self.assertFalse(layer2 == layer1)
            layer3 = layer1.crossingover(layer2)
            self.assertTrue(layer3 is not layer1)
            self.assertTrue(layer3 is not layer2)
            layer4 = layer3.copy()
            layer4.mutate()
            for i in range(32):
                layer4.shuffle()
#            self.assertFalse(layer4 == layer3)

    def test_protozoon(self):
        ka_random.set_flurry(9)
        self._neutral()

        protozoon1 = model_protozoon.Protozoon()
        protozoon1.randomize()
        protozoon2 = protozoon1.copy()
        self.assertTrue(protozoon2 is not protozoon1)
        self.assertTrue(protozoon2 == protozoon1)
        protozoon1.randomize()
        protozoon1.shuffle()
        self.assertFalse(protozoon2 == protozoon1)
        protozoon3 = protozoon1.crossingover(protozoon2)
        self.assertTrue(protozoon3 is not protozoon1)
        self.assertTrue(protozoon3 is not protozoon2)
        protozoon4 = protozoon3.copy()
        protozoon4.mutate()
        for i in range(32):
            protozoon4.shuffle()
#        self.assertFalse(protozoon4 == protozoon3)

    def test_draw(self):
        self._neutral()

        width, height = 200, 200
        surface = cairo.SVGSurface('testoutput_p.svg', width, height)
        ctx = cairo.Context(surface)
        protozoon1 = model_protozoon.Protozoon()
        protozoon1.randomize()
        protozoon1.draw(ctx, width, height)

        layer_factory = ka_factory.get_factory('layer')
        for strategy in layer_factory.keys():
            layer = layer_factory.create(strategy, '/')
            layer.randomize()
            outname = 'testoutput_' + strategy
#            surface = cairo.SVGSurface(outname + '.svg', width, height)
            surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
            ctx = cairo.Context(surface)
            ctx.scale(width, height)
            # paint background
            ctx.set_operator(cairo.OPERATOR_SOURCE)
            ctx.set_source_rgb(0.0, 0.0, 0.0)
            ctx.paint()
            layer.draw(ctx, width, height)
            surface.write_to_png(outname + '.png')

ka_debug.info('starting TestSuite')
ka_debug.err('testing error message channel.')
alltests = unittest.TestSuite((\
                 unittest.makeSuite(TestKandidModel), \
                             ))
unittest.TextTestRunner(verbosity=2).run(alltests)