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 numpy as np
16import exudyn.graphics as graphics
17from exudyn.advancedUtilities import * 
18
19#Recursively compare two dictionaries for equality.
20def CompareDicts(dict1, dict2):
21    if dict1.keys() != dict2.keys():
22        return False
23    for key in dict1:
24        val1, val2 = dict1[key], dict2[key]
25        if isinstance(val1, dict) and isinstance(val2, dict):
26            if not CompareDicts(val1, val2):
27                return False
28        elif isinstance(val1, list) and isinstance(val2, list):
29            if len(val1) != len(val2):
30                return False
31            for item1, item2 in zip(val1, val2):
32                if isinstance(item1, dict) and isinstance(item2, dict):
33                    if not CompareDicts(item1, item2):
34                        return False
35                elif isinstance(item1, np.ndarray) and isinstance(item2, np.ndarray):
36                    if not np.array_equal(item1, item2):
37                        return False
38                elif item1 != item2:
39                    return False
40        elif isinstance(val1, np.ndarray) and isinstance(val2, np.ndarray):
41            if not np.array_equal(val1, val2):
42                return False
43        elif val1 != val2:
44            return False
45    return True
46
47gChecker=graphics.CheckerBoard(nTiles=1)
48gSphere=graphics.Sphere(nTiles=3)
49
50test = {
51    'a': [np.array([1.0, 2.0, 3.0]), [3, 4, 5]],
52    'b': {'x': 10, 'y': 20.5, 'z': [np.array([1, 2]), 'hello']},
53    'c': [True, False, None],
54    'd': 'This is a test string',
55    'e': np.array([[1, 2], [3, 4]]),
56    'f': [np.array([5.5, 6.5]), {'nested': 'value', 'list': [1,2,np.array([1,2]),{'g':[1.,2.,'message']}]}],
57    'h': [gChecker,gSphere],
58}
59
60#generated output, not input: goes to the ignored solution/ (#2491)
61fileName = OutputFilePath('solution/test.hdf5', 'testHDF5loadSave')
62SaveDictToHDF5(fileName, test)
63test2 = LoadDictFromHDF5(fileName)
64
65if CompareDicts(test, test2):
66    exu.Print('TestHDF5loadSave: test successful!')
67else:
68    #this is used in Examples and will just show that example failed
69    raise ValueError('***********\nTestHDF5loadSave: failed!\n***********\n')