c4dynamics 2.3.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. c4dynamics/__init__.py +315 -0
  2. c4dynamics/datasets/__init__.py +97 -0
  3. c4dynamics/datasets/_manager.py +613 -0
  4. c4dynamics/datasets/_registry.py +83 -0
  5. c4dynamics/detectors/__init__.py +26 -0
  6. c4dynamics/detectors/yolo3_opencv.py +664 -0
  7. c4dynamics/envs/__init__.py +13 -0
  8. c4dynamics/envs/mountain_car.py +880 -0
  9. c4dynamics/eqm/__init__.py +36 -0
  10. c4dynamics/eqm/derivs.py +194 -0
  11. c4dynamics/eqm/integrate.py +341 -0
  12. c4dynamics/filters/__init__.py +118 -0
  13. c4dynamics/filters/ekf.py +302 -0
  14. c4dynamics/filters/kalman.py +709 -0
  15. c4dynamics/filters/lowpass.py +123 -0
  16. c4dynamics/rotmat/__init__.py +36 -0
  17. c4dynamics/rotmat/animate.py +460 -0
  18. c4dynamics/rotmat/rotmat.py +332 -0
  19. c4dynamics/sensors/__init__.py +65 -0
  20. c4dynamics/sensors/lineofsight.py +78 -0
  21. c4dynamics/sensors/radar.py +721 -0
  22. c4dynamics/sensors/seeker.py +1006 -0
  23. c4dynamics/states/__init__.py +33 -0
  24. c4dynamics/states/lib/__init__.py +40 -0
  25. c4dynamics/states/lib/datapoint.py +639 -0
  26. c4dynamics/states/lib/pixelpoint.py +758 -0
  27. c4dynamics/states/lib/rigidbody.py +647 -0
  28. c4dynamics/states/state.py +1540 -0
  29. c4dynamics/utils/__init__.py +27 -0
  30. c4dynamics/utils/_struct.py +10 -0
  31. c4dynamics/utils/const.py +116 -0
  32. c4dynamics/utils/cprint.py +63 -0
  33. c4dynamics/utils/gen_gif.py +130 -0
  34. c4dynamics/utils/idx2keys.py +8 -0
  35. c4dynamics/utils/images_loader.py +66 -0
  36. c4dynamics/utils/math.py +124 -0
  37. c4dynamics/utils/plottools.py +123 -0
  38. c4dynamics/utils/plottracks.py +307 -0
  39. c4dynamics/utils/printpts.py +39 -0
  40. c4dynamics/utils/slides_gen.py +67 -0
  41. c4dynamics/utils/tictoc.py +174 -0
  42. c4dynamics/utils/video_gen.py +302 -0
  43. c4dynamics/utils/vidgen.py +185 -0
  44. c4dynamics-2.3.3.dist-info/METADATA +205 -0
  45. c4dynamics-2.3.3.dist-info/RECORD +48 -0
  46. c4dynamics-2.3.3.dist-info/WHEEL +5 -0
  47. c4dynamics-2.3.3.dist-info/licenses/LICENSE +21 -0
  48. c4dynamics-2.3.3.dist-info/top_level.txt +1 -0
c4dynamics/__init__.py ADDED
@@ -0,0 +1,315 @@
1
+ '''
2
+
3
+ C4DYNAMICS
4
+ ==========
5
+
6
+ c4dynamics provides
7
+ 1. State objects as fundamental data structure for dynamic systems.
8
+ 2. Internal systems and 3rd party integrated libraries.
9
+ 3. Fast algorithmic operations over objects and systems.
10
+
11
+
12
+ How to use the documentation
13
+ ----------------------------
14
+ Documentation is currently availble through examples,
15
+ readme pages, and inline comments.
16
+
17
+
18
+ Available subpackages
19
+ ---------------------
20
+ sensors
21
+ Models of EO and EM sensors.
22
+ detectors
23
+ Objects detection models.
24
+ filters
25
+ Kalman and lowpass filters.
26
+ eqm
27
+ Runge Kutta solvers for integrating the equations of motion.
28
+ rotmat
29
+ Rotation matrices and rotational operations.
30
+ '''
31
+
32
+
33
+ import os
34
+ import doctest
35
+ import warnings
36
+
37
+
38
+
39
+ #
40
+ # body objects
41
+ ##
42
+ from .states.state import state
43
+ from .states.lib.pixelpoint import pixelpoint
44
+ from .states.lib.datapoint import datapoint, create
45
+ from . import rotmat
46
+ # rotmat is required to importing rigidbody:
47
+ from .states.lib.rigidbody import rigidbody # rotmat is required to import rigidbody.
48
+
49
+ #
50
+ # routines
51
+ ##
52
+ from . import eqm
53
+
54
+ #
55
+ # utils
56
+ ##
57
+ from .utils.const import *
58
+ from .utils.math import *
59
+ from .utils.gen_gif import gif
60
+ from .utils.cprint import cprint
61
+ from .utils.plottools import plotdefaults, _figdef, _legdef
62
+ from .utils import tictoc
63
+ from .utils.tictoc import tic, toc
64
+ from .utils._struct import struct
65
+ from .utils.idx2keys import idx2keys
66
+ from . import datasets
67
+
68
+
69
+ #
70
+ # sensors
71
+ ##
72
+ from . import sensors
73
+ from . import filters
74
+ from . import detectors
75
+
76
+
77
+ #
78
+ # reinforcement learning
79
+ ##
80
+ from . import envs
81
+
82
+
83
+ #
84
+ # version
85
+ ##
86
+ __version__ = '2.3.3' # update also in pyproject.toml & setup.py
87
+
88
+
89
+ #
90
+ # some convinient mirroring
91
+ ##
92
+ j = os.path.join
93
+
94
+
95
+
96
+ '''
97
+ WARNINGS
98
+ '''
99
+ class c4warn(UserWarning): pass
100
+
101
+ # customize the warning messages:
102
+ YELLOW = "\033[93m"
103
+ RESET = "\033[0m" # Reset color to default
104
+ # Override showwarning to globally apply custom formatting
105
+ def show_warning(message, category, filename, lineno, file = None, line = None):
106
+
107
+ if issubclass(category, c4warn):
108
+ # Apply formatting for c4warn warnings
109
+
110
+ # FIXME suppressing is absolutely not working.
111
+ message1 = str(message) + f"\n"
112
+ message2 = f"To suppress c4dynamics' warnings, run: import warnings, import c4dynamics as c4d, warnings.simplefilter('ignore', c4d.c4warn)\n"
113
+
114
+ print(f"\n{YELLOW}{message1}{RESET}{message2} (File: {filename}, Line: {lineno})")
115
+ else:
116
+ # For other warnings, use the default behavior
117
+ print(f"{category.__name__}: {message} (File: {filename}, Line: {lineno})")
118
+
119
+ warnings.showwarning = show_warning
120
+
121
+ '''
122
+ TESTING
123
+ '''
124
+
125
+ class IgnoreOutputChecker(doctest.OutputChecker):
126
+ from typing import Union
127
+
128
+ IGNORE_OUTPUT = doctest.register_optionflag("IGNORE_OUTPUT") # 2048
129
+ NUMPY_FORMAT = doctest.register_optionflag("NUMPY_FORMAT") # 4096
130
+
131
+ def check_output(self, want, got, optionflags):
132
+
133
+
134
+ # If the IGNORE_OUTPUT flag is set, always return True
135
+ if optionflags & self.IGNORE_OUTPUT:
136
+ return True
137
+
138
+ # If NUMPY_FORMAT flag is set, compare NumPy arrays with formatting tolerance
139
+ if optionflags & self.NUMPY_FORMAT:
140
+
141
+ want = self._convert_to_array(want)
142
+ got = self._convert_to_array(got)
143
+
144
+ if want is not None and got is not None:
145
+
146
+ abs_tol = 1e-3
147
+ rel_tol = 1e-3
148
+
149
+ if False:
150
+
151
+ # Calculate element-wise absolute and relative differences
152
+ # if diff < abs (for small values) OR diff/want < rel (for large values)
153
+ np.abs(want - got) < abs_tol
154
+ np.abs((want - got) / np.where(want != 0, want, np.inf)) < rel_tol
155
+
156
+
157
+ return np.allclose(want, got, atol = abs_tol, rtol = rel_tol)
158
+
159
+ # Otherwise, fall back to the original behavior
160
+ return super().check_output(want, got, optionflags) # type: ignore
161
+
162
+
163
+ def _convert_to_array(self, text):
164
+
165
+ import re
166
+
167
+ """Attempt to convert text to a NumPy array for comparison."""
168
+ try:
169
+
170
+ if ',' not in text:
171
+ text = re.sub(r'\s+', ',', text.strip())
172
+
173
+ # Remove 'np.type'
174
+ text = re.sub(r'np\.\w+', '', text)
175
+ # Remove 'array(' and strip leading/trailing whitespace characters
176
+ text = re.sub(r'(array\()', '', text).strip()
177
+ # Remove brackets and parantheses
178
+ text = re.sub(r'[\[\]\(\)]', '', text)
179
+ # remove ellipsis
180
+ text = re.sub(r'\.\.\.', '', text)
181
+ # Convert to NumPy array
182
+ return np.fromstring(text, sep = ',')
183
+
184
+ except ValueError:
185
+ print(f"\n \033[31m DOCSTRING ERROR: Could not convert to an array \033[0m", file = sys.stderr)
186
+ return None # Return None if conversion fails
187
+
188
+
189
+
190
+ # Filter out tests for the animate method by overriding the testmod.
191
+
192
+
193
+ def testmod_filtering(module, filter_functions = [], **kwargs):
194
+
195
+ tests = []
196
+
197
+ for test in doctest.DocTestFinder().find(module):
198
+ filtfunc = False
199
+ for func in filter_functions:
200
+ if func == test.name:
201
+ filtfunc = True
202
+ break
203
+ if filtfunc: continue
204
+ tests.append(test)
205
+
206
+
207
+ runner = doctest.DocTestRunner(**kwargs)
208
+ for test in tests:
209
+ runner.run(test)
210
+ return runner.summarize()
211
+
212
+
213
+ def rundoctests(module, exclude_functions = []):
214
+ import doctest, contextlib, os
215
+ from c4dynamics import IgnoreOutputChecker, cprint
216
+ from matplotlib import pyplot as plt
217
+ from pathlib import Path
218
+
219
+ tofile = False
220
+ # pltbe = plt.get_backend()
221
+ # plt.switch_backend("tkAgg")
222
+
223
+ # Register the custom OutputChecker
224
+ doctest.OutputChecker = IgnoreOutputChecker
225
+
226
+ optionflags = doctest.FAIL_FAST
227
+ np.set_printoptions(legacy = "1.25")
228
+
229
+ if tofile:
230
+ with open(os.path.join('tests', '_out', 'output.txt'), 'w') as f:
231
+ with contextlib.redirect_stdout(f), contextlib.redirect_stderr(f):
232
+ # result = doctest.testmod(optionflags = optionflags)
233
+ result = testmod_filtering(module, exclude_functions, optionflags = optionflags)
234
+ else:
235
+ # result = doctest.testmod(optionflags = optionflags)
236
+ result = testmod_filtering(module, exclude_functions, optionflags = optionflags)
237
+
238
+ if result.failed == 0:
239
+ cprint(Path(module.__file__).parts[-1] + ": all tests passed!", 'g')
240
+ else:
241
+ print(f"{result.failed}")
242
+
243
+
244
+ # plt.switch_backend(pltbe)
245
+
246
+
247
+ '''
248
+ ROOT FOLDER
249
+ '''
250
+ # just find the package root folder:
251
+ def c4dir(dir, addpath = ''):
252
+ # dirname and basename are supplamentary:
253
+ # c:\dropbox\c4dynamics\text.txt
254
+ # dirname: c:\dropbox\c4dynamics
255
+ # basename: text.txt
256
+
257
+ inc4d = os.path.basename(dir) == 'c4dynamics'
258
+ hasc4d = any(f == 'c4dynamics' for f in os.listdir(dir)
259
+ if os.path.isdir(os.path.join(dir, f)))
260
+
261
+ if inc4d and hasc4d:
262
+ addpath += ''
263
+ return addpath
264
+
265
+ addpath += '..\\'
266
+ return c4dir(os.path.dirname(dir), addpath)
267
+
268
+
269
+ '''
270
+ KEYWORDS
271
+ '''
272
+ #
273
+ # TODO BUG FIXME HACK NOTE XXX
274
+ #
275
+ # TODO IMPROVMEMNT
276
+ #
277
+ # BUG LOGICAL FAILURE PROBABLY COMES WITH XXX
278
+ # Highlights the presence of a bug or an issue.
279
+ # FIXME NOT SEVERE BUT A BETTER IDEA IS TO DO SO
280
+ # Indicates that there is a problem or bug that needs to be fixed.
281
+ # HACK I KNOW ITS NOT BEST SOLUTION TREAT IF U HAVE SPARE TIME
282
+ # Suggests that a workaround or temporary solution has been implemented and should be revisited.
283
+ # NOTE MORE IMPORTANT THAN A CASUAL COMMENT
284
+ # Provides additional information or context about the code.
285
+ # XXX TREAT THIS BEFORE OTHERS
286
+ # Used to highlight something that is problematic, needs attention, or should be addressed later.
287
+
288
+
289
+
290
+ # FIXME
291
+ # dependencies: for time limits requirementx.txt currently
292
+ # install all. actually maybe 90% of the users use only numpy
293
+ # and pyplot so it's a good practice to offer another full-req.txt
294
+ # file and add an import check for those not necessary:
295
+ import os
296
+ import subprocess
297
+ def ensure_package(package_name):
298
+ try:
299
+ __import__(package_name)
300
+ except ImportError:
301
+ # Check if the user is in a conda environment
302
+ in_conda_env = os.environ.get("CONDA_PREFIX") is not None
303
+ manager = "conda" if in_conda_env else "pip"
304
+
305
+ user_input = input(
306
+ f"{package_name} is required but not installed. "
307
+ f"Would you like to install it with {manager}? (y/n): "
308
+ )
309
+
310
+ if user_input.lower() == 'y':
311
+ if manager == "conda":
312
+ subprocess.check_call(["conda", "install", package_name, "-y"])
313
+ else:
314
+ subprocess.check_call(["pip", "install", package_name])
315
+
@@ -0,0 +1,97 @@
1
+ '''
2
+
3
+ Usage of Datasets
4
+ =================
5
+
6
+ C4dynamics dataset functions can be simply called as follows:
7
+ :code:`c4dynamics.datasets.module(file)`,
8
+ where ``module`` and ``file`` define the dataset.
9
+ The available modules and files are detailed on the corresponding pages.
10
+ This downloads the dataset file over the network once, saves it to the cache,
11
+ and returns the path to the file.
12
+
13
+
14
+
15
+
16
+ Dataset retrieval and storage
17
+ =============================
18
+
19
+ The YOLOv3 weights file can be found at the official YOLO
20
+ site: `Joseph Redmon <https://pjreddie.com/darknet/yolo/>`_.
21
+ Oher dataset files are available in the
22
+ C4dynamics GitHub repository under
23
+ `datasets <https://github.com/C4dynamics/C4dynamics/blob/main/datasets/>`_
24
+
25
+
26
+ C4dynamics.datasets uses
27
+ `Pooch <https://www.fatiando.org/pooch/latest/>`_,
28
+ a Python package designed to simplify fetching data files.
29
+ `Pooch` retrieves the necessary dataset files
30
+ from these repositories when the dataset function is called.
31
+
32
+
33
+ A registry file of all datasets provides a mapping of filenames
34
+ to their SHA256 hashes and repository URLs
35
+ Pooch uses this registry to manage and verify downloads when the function is called.
36
+ After downloading the dataset once, the files are saved
37
+ in the system cache directory under ``'c4data'``.
38
+
39
+
40
+ Dataset cache locations may vary on different platforms.
41
+
42
+ For Windows::
43
+
44
+ 'C:\\Users\\<user>\\AppData\\Local\\c4data'
45
+
46
+ For macOS::
47
+
48
+ '~/Library/Caches/c4data'
49
+
50
+ For Linux and other Unix-like platforms::
51
+
52
+ '~/.cache/c4data' # or the value of the XDG_CACHE_HOME env var, if defined
53
+
54
+
55
+ In environments with constrained network connectivity for various security
56
+ reasons or on systems without continuous internet connections,
57
+ one may manually
58
+ load the cache of the datasets by placing the contents of the dataset repo in
59
+ the above mentioned cache directory to avoid fetching dataset errors without
60
+ the internet connectivity.
61
+
62
+ '''
63
+
64
+ import sys, os
65
+ sys.path.append('.')
66
+
67
+ from c4dynamics.datasets._manager import sha256, image, video, nn_model, d3_model, download_all, clear_cache
68
+
69
+
70
+
71
+
72
+ if __name__ == "__main__":
73
+
74
+ # import doctest, contextlib
75
+ # from c4dynamics import IgnoreOutputChecker, cprint
76
+
77
+ # # Register the custom OutputChecker
78
+ # doctest.OutputChecker = IgnoreOutputChecker
79
+
80
+ # tofile = False
81
+ # optionflags = doctest.FAIL_FAST
82
+
83
+ # if tofile:
84
+ # with open(os.path.join('tests', '_out', 'output.txt'), 'w') as f:
85
+ # with contextlib.redirect_stdout(f), contextlib.redirect_stderr(f):
86
+ # result = doctest.testmod(optionflags = optionflags)
87
+ # else:
88
+ # result = doctest.testmod(optionflags = optionflags)
89
+
90
+ # if result.failed == 0:
91
+ # cprint(os.path.basename(__file__) + ": all tests passed!", 'g')
92
+ # else:
93
+ # print(f"{result.failed}")
94
+ from c4dynamics import rundoctests
95
+ rundoctests(sys.modules[__name__])
96
+
97
+