testHDF5loadSave.py

You can view and download this file on Github: testHDF5loadSave.py

 1#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 2# This is an EXUDYN example
 3#
 4# Details:  A test for HDF5 load and save functionality
 5#
 6# Author:   Johannes Gerstmayr
 7# Date:     2025-06-08
 8#
 9# Copyright:This file is part of Exudyn. Exudyn is free software. You can redistribute it and/or modify it under the terms of the Exudyn license. See 'LICENSE.txt' for more details.
10#
11#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
12
13import exudyn as exu               #EXUDYN package including C++ core part
14from exudyn.utilities import *
15import exudyn.graphics as graphics
16from exudyn.advancedUtilities import *
17
18#Recursively compare two dictionaries for equality.
19def CompareDicts(dict1, dict2):
20    if dict1.keys() != dict2.keys():
21        return False
22    for key in dict1:
23        val1, val2 = dict1[key], dict2[key]
24        if isinstance(val1, dict) and isinstance(val2, dict):
25            if not CompareDicts(val1, val2):
26                return False
27        elif isinstance(val1, list) and isinstance(val2, list):
28            if len(val1) != len(val2):
29                return False
30            for item1, item2 in zip(val1, val2):
31                if isinstance(item1, dict) and isinstance(item2, dict):
32                    if not CompareDicts(item1, item2):
33                        return False
34                elif isinstance(item1, np.ndarray) and isinstance(item2, np.ndarray):
35                    if not np.array_equal(item1, item2):
36                        return False
37                elif item1 != item2:
38                    return False
39        elif isinstance(val1, np.ndarray) and isinstance(val2, np.ndarray):
40            if not np.array_equal(val1, val2):
41                return False
42        elif val1 != val2:
43            return False
44    return True
45
46gChecker=graphics.CheckerBoard(nTiles=1)
47gSphere=graphics.Sphere(nTiles=3)
48
49test = {
50    'a': [np.array([1.0, 2.0, 3.0]), [3, 4, 5]],
51    'b': {'x': 10, 'y': 20.5, 'z': [np.array([1, 2]), 'hello']},
52    'c': [True, False, None],
53    'd': 'This is a test string',
54    'e': np.array([[1, 2], [3, 4]]),
55    'f': [np.array([5.5, 6.5]), {'nested': 'value', 'list': [1,2,np.array([1,2]),{'g':[1.,2.,'message']}]}],
56    'h': [gChecker,gSphere],
57}
58
59fileName = 'testData/test.hdf5'
60SaveDictToHDF5(fileName, test)
61test2 = LoadDictFromHDF5(fileName)
62
63if CompareDicts(test, test2):
64    exu.Print('TestHDF5loadSave: test successful!')
65else:
66    #this is used in Examples and will just show that example failed
67    raise ValueError('***********\nTestHDF5loadSave: failed!\n***********\n')