h2lib 0.0.4__cp310-cp310-win_amd64.whl → 13.0.705__cp310-cp310-win_amd64.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.
@@ -0,0 +1,184 @@
1
+ import multiprocessing
2
+ import atexit
3
+ import numpy as np
4
+ from threading import Thread
5
+ from functools import wraps
6
+ import traceback
7
+ from _queue import Empty
8
+ import os
9
+ from contextlib import contextmanager
10
+ import sys
11
+ import inspect
12
+ from multiclass_interface.multi_object_list import MultiObjectList
13
+
14
+
15
+ def run(cls, inputQueue, outputQueue, cls_args, **kwargs):
16
+ o = cls(*cls_args, **kwargs)
17
+ while True:
18
+ method, args, kwargs = inputQueue.get()
19
+ try:
20
+ if method == 'getattr':
21
+ name = args[0]
22
+ outputQueue.put(getattr(o, name))
23
+ elif method == 'setattr':
24
+ name, value = args
25
+ if hasattr(value, '__call__'): # pragma: no cover # cov not registered?
26
+
27
+ def wrap(*args, func=value, **kwargs):
28
+ if inspect.getfullargspec(func).args[:1] == ['self']:
29
+ args = (o,) + args
30
+ return func(*args, **kwargs)
31
+ outputQueue.put(setattr(o, name, wrap))
32
+ else:
33
+ outputQueue.put(setattr(o, name, value))
34
+ elif method == 'iscallable':
35
+ name = args[0]
36
+ outputQueue.put(hasattr(getattr(o, name), '__call__'))
37
+ else:
38
+ att = getattr(o, method)
39
+ outputQueue.put(att(*args, **kwargs))
40
+ if method == 'close':
41
+ outputQueue.put('Exit process')
42
+ return
43
+ except BaseException as e:
44
+ outputQueue.put((e, traceback.format_exc()))
45
+
46
+
47
+ class ProcessClass():
48
+ cls = None
49
+
50
+ def __init__(self, cls, cls_attrs={}):
51
+ self.cls_attrs = cls_attrs
52
+ self.cls = cls
53
+ self.ctx = multiprocessing.get_context('spawn')
54
+ self.inputQueue = self.ctx.Queue()
55
+ self.outputQueue = self.ctx.Queue()
56
+ atexit.register(self.close)
57
+ self.closed = False
58
+
59
+ def __call__(self, *args, **kwargs):
60
+ kwargs.update({'cls': self.cls, 'inputQueue': self.inputQueue, 'outputQueue': self.outputQueue,
61
+ 'cls_args': args})
62
+ s = 'vs_debug.py'
63
+ if s in "".join(traceback.format_stack()): # pragma: no cover
64
+ self.process = Thread(target=run, kwargs=kwargs) # use this to debug from Visual studio
65
+ else:
66
+ self.process = self.ctx.Process(target=run, kwargs=kwargs, daemon=True)
67
+
68
+ self.process.start()
69
+ return self
70
+
71
+ def __enter__(self):
72
+ return self
73
+
74
+ def __exit__(self, exc_type, exc_val, exc_tb):
75
+ self.close()
76
+
77
+ def __getattribute__(self, name):
78
+ try:
79
+ if name != 'cls_attrs' and name in self.cls_attrs:
80
+ raise AttributeError()
81
+ return object.__getattribute__(self, name)
82
+ except AttributeError:
83
+ if self.is_callable(name):
84
+ @wraps(getattr(self.cls, name, None))
85
+ def wrap(*args, wait_for_result=True, **kwargs):
86
+ self.inputQueue.put((name, args, kwargs))
87
+ if wait_for_result:
88
+ return self.get_result(raise_exception=True,
89
+ cmd=lambda: f'executing {name}({", ".join(list(map(str,args))+["%s=%s"%(k,v) for k,v in kwargs.items()])})')
90
+ return wrap
91
+ else:
92
+ self.inputQueue.put(('getattr', (name,), {}))
93
+ return self.get_result(raise_exception=True, cmd=lambda: f"getting attribute '{name}'")
94
+
95
+ def is_callable(self, name):
96
+ self.inputQueue.put(('iscallable', (name,), {}))
97
+ return self.get_result(raise_exception=True, cmd=lambda: f"checking if '{name}' is callable")
98
+
99
+ def __setattr__(self, name, value):
100
+ if name in {'cls', 'ctx', 'inputQueue', 'outputQueue', 'closed', 'process', 'cls_attrs'}:
101
+ return object.__setattr__(self, name, value)
102
+ else:
103
+ self.inputQueue.put(('setattr', (name, value), {}))
104
+ return self.get_result(raise_exception=True, cmd=lambda: f"setting attribute '{name}'")
105
+
106
+ def get_result(self, raise_exception, cmd):
107
+ while True:
108
+ if self.process.is_alive() or self.closed:
109
+ try:
110
+ res = self.outputQueue.get(timeout=2)
111
+ if isinstance(res, tuple) and len(res) > 1 and isinstance(res[0], BaseException):
112
+ res = res[0].__class__(res[1])
113
+ if raise_exception:
114
+ raise res
115
+ return res
116
+ except Empty:
117
+ pass # time out. Check process is alive and try again
118
+ else:
119
+ if hasattr(cmd, '__call__'):
120
+ cmd = cmd()
121
+ e = Exception(f'{self.cls.__name__} process died before or while {cmd}')
122
+ if raise_exception:
123
+ raise e
124
+ return e
125
+
126
+ def close(self, wait_for_result=False):
127
+ if not self.closed:
128
+ self.inputQueue.put(('close', [], {}))
129
+ r = self.get_result(False, 'close')
130
+ self.process.join()
131
+ self.inputQueue.close()
132
+ self.outputQueue.close()
133
+ self.closed = True
134
+ return r
135
+
136
+
137
+ class MultiProcessClassInterface(MultiObjectList):
138
+
139
+ def __init__(self, cls, args_lst, cls_attrs={}):
140
+ MultiObjectList.__init__(self, [ProcessClass(cls, cls_attrs)(*args) for args in args_lst], SubsetProcessWrapper)
141
+
142
+ def __getattr__(self, name):
143
+ obj_lst = self.obj_lst
144
+ if obj_lst[0].is_callable(name):
145
+ def wrap(*args, **kwargs):
146
+ for obj, (o_args, o_kwargs) in zip(obj_lst, self.get_obj_args_lst(args, kwargs)):
147
+ getattr(obj, name)(*o_args, wait_for_result=False, **o_kwargs)
148
+ res = [o.get_result(raise_exception=False, cmd=lambda: f"executing {name}(...)")
149
+ for o in obj_lst]
150
+ for r in res:
151
+ if isinstance(r, Exception):
152
+ raise r
153
+ return res
154
+ return wrap
155
+ else:
156
+ return [getattr(o, name) for o in obj_lst]
157
+
158
+ def __enter__(self):
159
+ return self
160
+
161
+ def __exit__(self, exc_type, exc_val, exc_tb):
162
+ self.close()
163
+
164
+ def close(self, wait_for_result=False):
165
+ for obj in self.obj_lst:
166
+ obj.inputQueue.put(('close', [], {}))
167
+ obj.process.join()
168
+ obj.closed = True
169
+
170
+
171
+ class SubsetProcessWrapper(MultiProcessClassInterface):
172
+ def __init__(self, obj_lst):
173
+ MultiObjectList.__init__(self, obj_lst)
174
+
175
+ def __getitem__(self, slice):
176
+ if np.all(np.atleast_1d(self.obj_lst[slice]) == self.obj_lst):
177
+ return self
178
+ raise Exception('Cannot make subset of SubsetProcessWrapper')
179
+
180
+ def __getattribute__(self, name):
181
+ if name == 'close':
182
+ raise Exception("Cannot close SubsetProcessWrapper. Please close all instances at once")
183
+
184
+ return MultiProcessClassInterface.__getattribute__(self, name)
@@ -0,0 +1,33 @@
1
+ import time
2
+ import os
3
+
4
+
5
+ class MyTest():
6
+ def __init__(self, id):
7
+ self.id = id
8
+ self.name = self.__class__.__name__
9
+
10
+ def get_id(self,):
11
+ return self.id
12
+
13
+ def work(self, t):
14
+ start_time = time.time()
15
+ s1 = f'{self.id} starts working for {t}s at t={start_time}. '
16
+ # print (s1)
17
+ while time.time() < start_time + t:
18
+ pass
19
+ s2 = f'{self.id} ends working at {time.time()}.'
20
+ # print (s2)
21
+ return s1 + s2
22
+
23
+ def return_input(self, *args, **kwargs):
24
+ return f"{self.id} got: {str(args)} and {str(kwargs)}"
25
+
26
+ def get_ld_library_path(self):
27
+ return os.environ['LD_LIBRARY_PATH']
28
+
29
+ def close(self):
30
+ return f"closing {self.get_id()}"
31
+
32
+ def raise_exception(self):
33
+ 1 / 0 # raise ZeroDivisionError
Binary file
@@ -1 +0,0 @@
1
- from ._h2lib import H2Lib
@@ -1,13 +0,0 @@
1
- from h2lib.dll_wrapper import DLLWrapper
2
- import os
3
-
4
-
5
- class H2Lib(DLLWrapper):
6
- def __init__(self, filename=None):
7
- if filename is None:
8
- if os.name == 'nt':
9
- filename = os.path.dirname(__file__) + '/TestLib.dll'
10
- else:
11
- filename = os.path.dirname(__file__) + '/TestLib.so'
12
-
13
- DLLWrapper.__init__(self, filename, cdecl=True)
@@ -1,21 +0,0 @@
1
- import ctypes
2
- from ctypes import CDLL, cdll, c_double
3
- import os
4
- from h2lib.dll_wrapper import DLLWrapper, c_double_p
5
- import numpy as np
6
-
7
-
8
- def add(a, b):
9
- return a + b
10
-
11
-
12
- def square(a):
13
- print(os.getcwd())
14
- f = os.path.abspath('../../../build/TestLib_64.dll')
15
- dll = DLLWrapper(filename=f, cdecl=True)
16
- print(dll.sqr2(3))
17
- print(dll.getSquare(3., restype=np.float64))
18
-
19
-
20
- if __name__ == '__main__':
21
- square(3)
@@ -1,14 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: h2lib
3
- Version: 0.0.4
4
- Summary: Python interface to HAWC2
5
- Download-URL:
6
- Author: S.G.Horcas and N.G.Ramos
7
- Author-email:
8
- Maintainer:
9
- Maintainer-email:
10
- Requires-Dist: intel-fortran-rt ==2021.3.0
11
- Requires-Dist: mkl ==2021.3.0
12
- Requires-Dist: numpy
13
- Requires-Dist: pytest
14
-
@@ -1,9 +0,0 @@
1
- h2lib-0.0.4.data/purelib/h2lib/TestLib.dll,sha256=iRgC1hyKxjIoAoh4FruOU0Q78Gplh9BgxNOII00_9Q8,2859008
2
- h2lib-0.0.4.data/purelib/h2lib/__init__.py,sha256=v4RtCtR7Cfv-LSx-9tnLK0WSefKVjIKrGjfBVBhONzI,27
3
- h2lib-0.0.4.data/purelib/h2lib/_h2lib.py,sha256=tapiHobRD2T7jZhizOHCW9uX2sGjkDWMa-Na9oIBcYE,417
4
- h2lib-0.0.4.data/purelib/h2lib/calc.py,sha256=eqPH_ruyWpnXVJDH8jVjuV3u-Dh_MiwSlgEV-hjDM_w,448
5
- h2lib-0.0.4.data/purelib/h2lib/dll_wrapper.py,sha256=KWbqOu42EtO2WeP8T6ne5aYOEszs9QoheaKDbYS8JAQ,8903
6
- h2lib-0.0.4.dist-info/METADATA,sha256=hACt34y2BAVpm3ZM6meuatN9gy6trlEFq0kTtrZkCFQ,310
7
- h2lib-0.0.4.dist-info/WHEEL,sha256=Wb1el1iP4ORW7FiLElw7HfxLpDiHzwvd2B382b2Idl0,102
8
- h2lib-0.0.4.dist-info/top_level.txt,sha256=y_a-tUqphEZQ_0nsWSMaSb21P8Lsd8hUxUdE9g2Dcbk,6
9
- h2lib-0.0.4.dist-info/RECORD,,
@@ -1 +0,0 @@
1
- h2lib