• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

WassimTenachi / PhySO / #13

10 Jun 2024 12:28AM UTC coverage: 52.052% (-30.3%) from 82.385%
#13

push

coveralls-python

WassimTenachi
Update requirements.txt

2980 of 5725 relevant lines covered (52.05%)

0.52 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

48.89
/physo/physym/tests/library_UnitTest.py
1
import unittest
1✔
2
import numpy as np
1✔
3
import warnings
×
4

5
# Internal imports
6
from physo.physym import library as Lib
1✔
7
from physo.physym import token as Tok
×
8

9

10
class LibraryTest(unittest.TestCase):
×
11

12
    # Check all library creation + append configuration, sizes, types of data contained within library
13
    def test_library_creation_and_types(self):
1✔
14
        def test_lib_types_and_size(my_lib, expected_n_lib):
×
15
            # Idx of superparent
16
            self.assertEqual(my_lib.lib_name[my_lib.superparent_idx], my_lib.superparent.name)
1✔
17
            self.assertEqual(my_lib.lib_name[my_lib.dummy_idx      ], my_lib.dummy.name)
×
18
            # Sizes
19
            self.assertEqual(my_lib.n_library, expected_n_lib + len(my_lib.placeholders))
1✔
20
            self.assertEqual(my_lib.n_choices, expected_n_lib)
×
21
            # Shapes
22
            bool_works = np.array_equal(my_lib.phy_units, my_lib.properties.phy_units[0,:], equal_nan=True)
1✔
23
            self.assertEqual(bool_works, True)
1✔
24
            bool_works = np.array_equal(my_lib.arity, my_lib.properties.arity[0, :], equal_nan=True)
1✔
25
            self.assertEqual(bool_works, True)
×
26
            # Test properties vectors types # https://numpy.org/doc/stable/reference/arrays.scalars.html
27
            self.assertEqual( my_lib            .lib_function                 .dtype , np.object_ )
1✔
28
            self.assertEqual( my_lib.properties .arity                        .dtype , np.int_    )
1✔
29
            self.assertEqual( my_lib.properties .complexity                   .dtype , np.float_  )
1✔
30
            self.assertEqual( my_lib.properties .var_type                     .dtype , np.int_   )
1✔
31
            self.assertEqual( my_lib.properties .var_id                       .dtype , np.int_    )
1✔
32
            self.assertEqual( my_lib.properties .is_constraining_phy_units    .dtype , np.bool_   )
1✔
33
            self.assertEqual( my_lib.properties .phy_units                    .dtype , np.float_  )
1✔
34
            self.assertEqual( my_lib.properties .behavior_id                  .dtype , np.int_    )
1✔
35
            self.assertEqual( my_lib.properties .is_power                     .dtype , np.bool_   )
1✔
36
            self.assertEqual( my_lib.properties .power                        .dtype , np.float_  )
×
37

38
        # -------- Test args --------
39
        custom_tokens = [
1✔
40
        Tok.TokenInputVar(name='x0', sympy_repr='x0', complexity=0,
41
                       var_id=0,
42
                       is_constraining_phy_units=True,
43
                       phy_units=[1.,0.,0.,0.,0.,0.,0.]),
44
        Tok.TokenInputVar(name='x1', sympy_repr='x1', complexity=0,
45
                       var_id=1),
46
        Tok.TokenOp(name='add', sympy_repr='add', arity=2, complexity=0,
47
                        function=np.add,),
48
        Tok.TokenOp(name='cos', sympy_repr='cos', arity=1, complexity=0,
49
                        function=np.cos,),
50
        Tok.TokenOp(name='pi', sympy_repr='pi', arity=0, complexity=0,
51
                       function=lambda const=np.pi: const,),
52
                        ]
53
        n_tokens_via_custom = len(custom_tokens)
1✔
54
        # Initial values
55
        a,b,c = 1.,10.,1.
×
56
        n_realizations = 5
1✔
57
        aa, bb, cc = [1.,2.,3.,4.,5.], [10.,20.,30.,40.,50.] , 1.
1✔
58
        expected_class_init_vals = np.array([a, b, c,])
×
59
        expected_spe_init_vals   = np.array([np.array(aa), np.array(bb), np.array([cc]),], dtype=object)
1✔
60
        expected_spe_init_vals_after_pad = np.array([aa, bb, np.full((n_realizations,), cc)])
1✔
61
        # -------- Test args_make_tokens --------
62
        args_make_tokens = {
1✔
63
                # operations
64
                "op_names"             : ["mul", "neg", "inv", "sin"],
65
                "use_protected_ops"    : False,
66
                # input variables
67
                "input_var_ids"        : {"x" : 0         , "v" : 1          , "t" : 2,        },
68
                "input_var_units"      : {"x" : [1, 0, 0] , "v" : [1, -1, 0] , "t" : [0, 1, 0] },
69
                "input_var_complexity" : {"x" : 0.        , "v" : 1.         , "t" : 0.,       },
70
                # constants
71
                "constants"            : {"pi" : np.pi     , "c" : 3e8       , "M" : 1e6       },
72
                "constants_units"      : {"pi" : [0, 0, 0] , "c" : [1, -1, 0], "M" : [0, 0, 1] },
73
                "constants_complexity" : {"pi" : 0.        , "c" : 0.        , "M" : 1.        },
74
                # free constants
75
                "free_constants"            : {"c0"             , "c1"               , "c2"             },
76
                "free_constants_init_val"   : {"c0" : a         , "c1"  : b          , "c2" : c         },
77
                "free_constants_units"      : {"c0" : [0, 0, 0] , "c1"  : [1, -1, 0] , "c2" : [0, 0, 1] },
78
                "free_constants_complexity" : {"c0" : 0.        , "c1"  : 0.         , "c2" : 1.        },
79
                # free constants
80
                "spe_free_constants"            : {"k0"              , "k1"                   , "k2"             },
81
                "spe_free_constants_init_val"   : {"k0" : aa         , "k1"  : bb             , "k2" : cc        },
82
                "spe_free_constants_units"      : {"k0" : [0, 0, 0]  , "k1"  : [1, -1, 0]     , "k2" : [0, 0, 1] },
83
                "spe_free_constants_complexity" : {"k0" : 0.         , "k1"  : 0.             , "k2" : 1.        },
84
                           }
85
        n_tokens_via_make = len(args_make_tokens["op_names"]) + len(args_make_tokens["input_var_ids"])\
1✔
86
                            + len(args_make_tokens["constants"]) + len(args_make_tokens["free_constants"]) \
87
                            + len(args_make_tokens["spe_free_constants"])
88

89
        # -------- Test args_make_tokens only --------
90
        try:
1✔
91
            with warnings.catch_warnings():
1✔
92
                warnings.simplefilter("ignore")
×
93
                # Raises some warnings due to some units provided (this is ok)
94
                my_lib = Lib.Library(args_make_tokens = args_make_tokens)
1✔
95
        except:
1✔
96
            self.fail("Library creation failed.")
×
97
        # Test lib
98
        test_lib_types_and_size(my_lib=my_lib, expected_n_lib=n_tokens_via_make)
×
99
        # Test superparent units
100
        bool_works = np.array_equal(my_lib.superparent.phy_units, np.full(Tok.UNITS_VECTOR_SIZE, np.NAN), equal_nan=True)
×
101
        self.assertEqual(bool_works, True)
1✔
102
        # Test sample token units
103
        bool_works = np.array_equal(my_lib.phy_units[my_lib.lib_name_to_idx["v"]][0:3],
1✔
104
                                    args_make_tokens["input_var_units"]["v"])
105
        self.assertEqual(bool_works, True)
1✔
106
        # Test initial values
107
        bool_works = np.array_equal(my_lib.class_free_constants_init_val, expected_class_init_vals)
×
108
        self.assertEqual(bool_works, True)
×
109
        bool_works = np.array([np.array_equal(a,b) for i, (a,b) in enumerate(zip(my_lib.spe_free_constants_init_val, expected_spe_init_vals))]).all()
1✔
110
        self.assertEqual(bool_works, True)
1✔
111
        my_lib.check_and_pad_spe_free_const_init_val(n_realizations=n_realizations)
1✔
112
        bool_works = np.array_equal(my_lib.spe_free_constants_init_val, expected_spe_init_vals_after_pad)
×
113
        self.assertEqual(bool_works, True)
×
114

115
        # -------- Test custom_tokens only --------
116
        try:
1✔
117
            with warnings.catch_warnings():
×
118
                warnings.simplefilter("ignore")
1✔
119
                # Raises some warnings due to some units provided (this is ok)
120
                my_lib = Lib.Library(custom_tokens = custom_tokens)
1✔
121
        except:
1✔
122
            self.fail("Library creation failed.")
1✔
123
        # Test lib
124
        test_lib_types_and_size(my_lib=my_lib, expected_n_lib=n_tokens_via_custom)
×
125
        # Test superparent units
126
        bool_works = np.array_equal(my_lib.superparent.phy_units, np.full(Tok.UNITS_VECTOR_SIZE, np.NAN), equal_nan=True)
×
127
        self.assertEqual(bool_works, True)
1✔
128
        # Test sample token units
129
        bool_works = np.array_equal(my_lib.phy_units[my_lib.lib_name_to_idx["x0"]][0:3],
1✔
130
                                    custom_tokens[0].phy_units[0:3])
131
        self.assertEqual(bool_works, True)
×
132

133
        # -------- Test append custom_tokens then args_make_tokens --------
134
        with warnings.catch_warnings():
1✔
135
            warnings.simplefilter("ignore")
×
136
            # Raises some warnings due to some units provided (this is ok)
137
            my_lib = Lib.Library(custom_tokens=custom_tokens)
1✔
138
            my_lib.append_from_tokenize(args_make_tokens=args_make_tokens)
1✔
139
        test_lib_types_and_size(my_lib=my_lib, expected_n_lib=n_tokens_via_custom+n_tokens_via_make)
1✔
140

141
        # Test superparent units
142
        bool_works = np.array_equal(my_lib.superparent.phy_units, np.full(Tok.UNITS_VECTOR_SIZE, np.NAN),
×
143
                                    equal_nan=True)
144
        self.assertEqual(bool_works, True)
1✔
145
        # Test sample token units
146
        bool_works = np.array_equal(my_lib.phy_units[my_lib.lib_name_to_idx["x0"]][0:3],
×
147
                                    custom_tokens[0].phy_units[0:3])
148
        self.assertEqual(bool_works, True)
×
149
        bool_works = np.array_equal(my_lib.phy_units[my_lib.lib_name_to_idx["v"]][0:3],
1✔
150
                                    args_make_tokens["input_var_units"]["v"])
151
        self.assertEqual(bool_works, True)
1✔
152

153
        # -------- Test append args_make_tokens then custom_tokens --------
154
        with warnings.catch_warnings():
×
155
            warnings.simplefilter("ignore")
1✔
156
            # Raises some warnings due to some units provided (this is ok)
157
            my_lib = Lib.Library(args_make_tokens=args_make_tokens)
1✔
158
            my_lib.append_custom_tokens(custom_tokens=custom_tokens)
1✔
159
        test_lib_types_and_size(my_lib=my_lib, expected_n_lib=n_tokens_via_custom + n_tokens_via_make)
1✔
160

161
        # Test superparent units
162
        bool_works = np.array_equal(my_lib.superparent.phy_units, np.full(Tok.UNITS_VECTOR_SIZE, np.NAN),
1✔
163
                                    equal_nan=True)
164
        self.assertEqual(bool_works, True)
1✔
165
        # Test sample token units
166
        bool_works = np.array_equal(my_lib.phy_units[my_lib.lib_name_to_idx["x0"]][0:3],
×
167
                                    custom_tokens[0].phy_units[0:3])
168
        self.assertEqual(bool_works, True)
×
169
        bool_works = np.array_equal(my_lib.phy_units[my_lib.lib_name_to_idx["v"]][0:3],
1✔
170
                                    args_make_tokens["input_var_units"]["v"])
171
        self.assertEqual(bool_works, True)
1✔
172

173
        # -------- Test custom_tokens and args_make_tokens --------
174
        try:
1✔
175
            with warnings.catch_warnings():
1✔
176
                warnings.simplefilter("ignore")
1✔
177
                # Raises some warnings due to some units provided (this is ok)
178
                my_lib = Lib.Library(custom_tokens=custom_tokens, args_make_tokens=args_make_tokens)
1✔
179
        except:
1✔
180
            self.fail("Library creation failed.")
×
181
        # Test lib
182
        test_lib_types_and_size(my_lib=my_lib, expected_n_lib=n_tokens_via_custom + n_tokens_via_make)
×
183
        # Test superparent units
184
        bool_works = np.array_equal(my_lib.superparent.phy_units, np.full(Tok.UNITS_VECTOR_SIZE, np.NAN),
1✔
185
                                    equal_nan=True)
186
        self.assertEqual(bool_works, True)
1✔
187
        # Test sample token units
188
        bool_works = np.array_equal(my_lib.phy_units[my_lib.lib_name_to_idx["x0"]][0:3],
1✔
189
                                    custom_tokens[0].phy_units[0:3])
190
        self.assertEqual(bool_works, True)
1✔
191
        bool_works = np.array_equal(my_lib.phy_units[my_lib.lib_name_to_idx["v"]][0:3],
1✔
192
                                    args_make_tokens["input_var_units"]["v"])
193
        self.assertEqual(bool_works, True)
1✔
194

195
        # -------- Test custom_tokens and args_make_tokens and customized superparent --------
196
        try:
1✔
197
            with warnings.catch_warnings():
1✔
198
                warnings.simplefilter("ignore")
1✔
199
                # Raises some warnings due to some units provided (this is ok)
200
                my_lib = Lib.Library(custom_tokens=custom_tokens, args_make_tokens=args_make_tokens,
1✔
201
                                     superparent_units=[1, -1, 0], superparent_name="v")
202
        except:
1✔
203
            self.fail("Library creation failed.")
1✔
204
        # Test lib
205
        test_lib_types_and_size(my_lib=my_lib, expected_n_lib=n_tokens_via_custom + n_tokens_via_make)
1✔
206
        # Test superparent units
207
        bool_works = np.array_equal(my_lib.superparent.phy_units[0:3], [1, -1, 0], equal_nan=True)
×
208
        self.assertEqual(bool_works, True)
1✔
209
        # Test sample token units
210
        bool_works = np.array_equal(my_lib.phy_units[my_lib.lib_name_to_idx["x0"]][0:3],
1✔
211
                                    custom_tokens[0].phy_units[0:3])
212
        self.assertEqual(bool_works, True)
1✔
213
        bool_works = np.array_equal(my_lib.phy_units[my_lib.lib_name_to_idx["v"]][0:3],
1✔
214
                                    args_make_tokens["input_var_units"]["v"])
215
        self.assertEqual(bool_works, True)
1✔
216
        # Superparent name
217
        self.assertEqual(my_lib.superparent.name, "v")
×
218

219
    # Check that library containing free units terminal tokens raises error
220
    def test_some_units_not_provided_warning(self):
1✔
221
        # -------- Test args --------
222

223
        x0 = Tok.TokenInputVar(name='x0', sympy_repr='x0', complexity=0,
1✔
224
                       var_id=0,
225
                       is_constraining_phy_units=True,
226
                       phy_units=[1.,0.,0.,0.,0.,0.,0.])
227
        x1 = Tok.TokenInputVar(name='x1', sympy_repr='x1', complexity=0,
1✔
228
                       var_id=1)
229
        add = Tok.TokenOp(name='add', sympy_repr='add', arity=2, complexity=0,
1✔
230
                        function=np.add,)
231
        cos = Tok.TokenOp(name='cos', sympy_repr='cos', arity=1, complexity=0,
1✔
232
                        function=np.cos,)
233
        pi = Tok.TokenOp(name='pi', sympy_repr='pi', arity=0, complexity=0,
1✔
234
                       function=lambda const=np.pi: const,)
235
        c0 = Tok.TokenClassFreeConst(name='c0', sympy_repr='c0', complexity=0,
1✔
236
                       init_val=1.,
237
                       var_id=0)
238
        args_make_tokens = {
×
239
                # operations
240
                "op_names"             : ["mul", "neg", "inv", "sin"],
241
                "use_protected_ops"    : False,
242
                # input variables
243
                "input_var_ids"        : {"x" : 0         , "v" : 1          , "t" : 2,        },
244
                "input_var_units"      : {"x" : [1, 0, 0] , "v" : [1, -1, 0] , "t" : [0, 1, 0] },
245
                "input_var_complexity" : {"x" : 0.        , "v" : 1.         , "t" : 0.,       },
246
                # constants
247
                "constants"            : {"pi" : np.pi     , "c" : 3e8       , "M" : 1e6       },
248
                "constants_complexity" : {"pi" : 0.        , "c" : 0.        , "M" : 1.        },
249
                           }
250
        with self.assertWarns(Warning):
×
251
            my_lib = Lib.Library(custom_tokens = [c0,add] , args_make_tokens = None,)
×
252
        with self.assertWarns(Warning):
×
253
            my_lib = Lib.Library(custom_tokens = [x0,x1,add] , args_make_tokens = None,)
×
254
        with self.assertWarns(Warning):
×
255
            my_lib = Lib.Library(custom_tokens = None        , args_make_tokens = args_make_tokens,)
×
256
        with self.assertWarns(Warning):
×
257
            my_lib = Lib.Library(custom_tokens = [x0,x1,add] , args_make_tokens = args_make_tokens,)
×
258
        with self.assertWarns(Warning):
×
259
            my_lib = Lib.Library(custom_tokens = [x0]        , args_make_tokens = None,)
×
260
            my_lib.append_from_tokenize(args_make_tokens = args_make_tokens)
×
261
        with self.assertWarns(Warning):
×
262
            my_lib = Lib.Library(custom_tokens=[x0], args_make_tokens=None,
×
263
                                 superparent_units=None, superparent_name="v")
264
        with self.assertWarns(Warning):
×
265
            my_lib = Lib.Library(custom_tokens=[x0, x1, add], args_make_tokens=args_make_tokens,
×
266
                                 superparent_units=None, superparent_name="v")
267

268
    def test_spe_free_const_init_val_consistency_check(self):
×
269
        # Initial values
270
        a,b,c = 1.,10.,1.
×
271
        n_realizations = 5
×
272
        def get_args_make_tokens (aa, bb, cc):
×
273
            args_make_tokens = {
×
274
                # operations
275
                "op_names"             : ["mul", "neg", "inv", "sin"],
276
                "use_protected_ops"    : False,
277
                # input variables
278
                "input_var_ids"        : {"x" : 0         , "v" : 1          , "t" : 2,        },
279
                "input_var_units"      : {"x" : [1, 0, 0] , "v" : [1, -1, 0] , "t" : [0, 1, 0] },
280
                "input_var_complexity" : {"x" : 0.        , "v" : 1.         , "t" : 0.,       },
281
                # constants
282
                "constants"            : {"pi" : np.pi     , "c" : 3e8       , "M" : 1e6       },
283
                "constants_units"      : {"pi" : [0, 0, 0] , "c" : [1, -1, 0], "M" : [0, 0, 1] },
284
                "constants_complexity" : {"pi" : 0.        , "c" : 0.        , "M" : 1.        },
285
                # free constants
286
                "free_constants"            : {"c0"             , "c1"               , "c2"             },
287
                "free_constants_init_val"   : {"c0" : a         , "c1"  : b          , "c2" : c         },
288
                "free_constants_units"      : {"c0" : [0, 0, 0] , "c1"  : [1, -1, 0] , "c2" : [0, 0, 1] },
289
                "free_constants_complexity" : {"c0" : 0.        , "c1"  : 0.         , "c2" : 1.        },
290
                # free constants
291
                "spe_free_constants"            : {"k0"              , "k1"                   , "k2"             },
292
                "spe_free_constants_init_val"   : {"k0" : aa         , "k1"  : bb             , "k2" : cc        },
293
                "spe_free_constants_units"      : {"k0" : [0, 0, 0]  , "k1"  : [1, -1, 0]     , "k2" : [0, 0, 1] },
294
                "spe_free_constants_complexity" : {"k0" : 0.         , "k1"  : 0.             , "k2" : 1.        },
295
                       }
296
            return args_make_tokens
×
297

298
        # Test that everything works fine in the nominal case
299
        try:
×
300
            with warnings.catch_warnings():
×
301
                warnings.simplefilter("ignore")
×
302
                # Raises some warnings due to some units provided (this is ok)
303
                my_lib = Lib.Library(args_make_tokens = get_args_make_tokens([1.,2.,3.,4.,5.], [10.,20.,30.,40.,50.] , 1.))
×
304
        except:
×
305
            self.fail("Library creation failed.")
×
306
        try:
×
307
            my_lib.check_and_pad_spe_free_const_init_val(n_realizations=n_realizations)
×
308
        except:
×
309
            self.fail("Library check_and_pad_spe_free_const_init_val failed.")
×
310
        bool_works = np.array_equal(my_lib.spe_free_constants_init_val, np.array([[1.,2.,3.,4.,5.], [10.,20.,30.,40.,50.] , np.full((n_realizations,), 1.)]))
×
311
        self.assertEqual(bool_works, True)
×
312

313
        # Test that everything works fine in the nominal case
314
        try:
×
315
            with warnings.catch_warnings():
×
316
                warnings.simplefilter("ignore")
×
317
                # Raises some warnings due to some units provided (this is ok)
318
                my_lib = Lib.Library(args_make_tokens = get_args_make_tokens(1., 1. , 1.))
×
319
        except:
×
320
            self.fail("Library creation failed.")
×
321
        try:
×
322
            my_lib.check_and_pad_spe_free_const_init_val(n_realizations=n_realizations)
×
323
        except:
×
324
            self.fail("Library check_and_pad_spe_free_const_init_val failed.")
×
325
        bool_works = np.array_equal(my_lib.spe_free_constants_init_val, np.array([np.full((n_realizations,), 1.), np.full((n_realizations,), 1.) , np.full((n_realizations,), 1.)]))
×
326
        self.assertEqual(bool_works, True)
×
327

328
        # Inconsistent number of realizations
329
        with self.assertRaises(AssertionError):
×
330
            with warnings.catch_warnings():
×
331
                warnings.simplefilter("ignore")
×
332
                my_lib = Lib.Library(args_make_tokens = get_args_make_tokens([1.,2.,3.,4.,5.], [10.,20.,30.,40.,50.] , 1.))
×
333
            my_lib.check_and_pad_spe_free_const_init_val(n_realizations=2)
×
334

335
        # Inconsistent shapes of initial values
336
        with self.assertRaises(AssertionError):
×
337
            with warnings.catch_warnings():
×
338
                warnings.simplefilter("ignore")
×
339
                my_lib = Lib.Library(args_make_tokens = get_args_make_tokens([1.,2.,3.,4.,5.], [10.,20.,30.,] , 1.))
×
340
            my_lib.check_and_pad_spe_free_const_init_val(n_realizations=5)
×
341

342
        return None
×
343

344
if __name__ == '__main__':
×
345
    unittest.main(verbosity=2)
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc