-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathscalar.py
More file actions
243 lines (182 loc) · 6.42 KB
/
scalar.py
File metadata and controls
243 lines (182 loc) · 6.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
"""
Wrapped native (spla C API) scalar primitive implementation.
"""
__copyright__ = "Copyright (c) 2021-2023 SparseLinearAlgebra"
__license__ = """
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import ctypes
from .bridge import backend, check
from .type import INT, FLOAT
from .object import Object
class Scalar(Object):
"""
Generalized statically-typed scalar primitive.
Notes
-----
Scalar typical usage:
- Create scalar from python value
- Pass scalar as argument to matrix/vector operation
- Get scalar as a return value of some operation
- Unpack value on python side
Avoid intensive creation of scalar values. Prefer python native types.
Use scalars only if you want to parametrise matrix/vector operations.
Details
-------
Scalar class support all spla C API scalar functions.
It provides bind functionality as well as new functions/methods for better python user experience.
Scalar internally stored in the native format of the type it has.
Meta-data additionally stored with each scalar value.
"""
__slots__ = ["_dtype"]
def __init__(self, dtype=INT, value=None, hnd=None, label=None):
"""
Creates new scalar of desired type or retains existing C object.
>>> s = Scalar(INT, 10)
>>> print(s)
'
10
'
:param dtype: optional: Type. default: INT.
Type of the scalar value.
:param value: optional: Any. default: None.
Optional value to store in scalar on creation.
:param hnd: optional: ctypes.c_void_p. default: None.
Optional handle to C object to retain in this scalar instance.
:param label: optional: str. default: None.
Optional debug label of the scalar.
"""
super().__init__(None, None)
self._dtype = dtype
if hnd is None:
hnd = ctypes.c_void_p(0)
check(backend().spla_Scalar_make(ctypes.byref(hnd), dtype._hnd))
super().__init__(label, hnd)
self.set(value)
@property
def dtype(self):
"""
Returns the type of stored value in the scalar.
>>> s = Scalar(INT)
>>> print(s.dtype)
'
<class 'pyspla.type.INT'>
'
"""
return self._dtype
@property
def shape(self):
"""
2-tuple shape of the storage. For scalar object it is always 1 by 1.
>>> s = Scalar(INT)
>>> print(s.shape)
'
(1, 1)
'
"""
return 1, 1
@property
def n_vals(self):
"""
Number of stored values in the scalar. Always 1.
>>> s = Scalar(INT)
>>> print(s.n_vals)
'
1
'
"""
return 1
@classmethod
def from_value(cls, value):
"""
Create scalar and infer type.
>>> s = Scalar.from_value(0.5)
>>> print(s.dtype)
'
<class 'pyspla.type.FLOAT'>
'
:param value: any.
Value to create scalar from.
:return: Scalar with value.
"""
if isinstance(value, float):
return Scalar(dtype=FLOAT, value=value)
elif isinstance(value, int):
return Scalar(dtype=INT, value=value)
elif isinstance(value, bool):
return Scalar(dtype=INT, value=value)
else:
raise Exception("cannot infer type")
def set(self, value=None):
"""
Set the value stored in the scalar. If no value passed the default value is set.
>>> s = Scalar(INT)
>>> s.set(10)
>>> print(s)
'
10
'
:param value: optional: Any. default: None.
Optional value to store in scalar.
"""
check(self._dtype._scalar_set(self._hnd, self._dtype._c_type(value if value else 0)))
def get(self):
"""
Read the value stored in the scalar.
>>> s = Scalar(INT, 10)
>>> print(s.get())
'
10
'
:return: Value from scalar.
"""
value = self._dtype._c_type(0)
check(self._dtype._scalar_get(self._hnd, ctypes.byref(value)))
return self._dtype.cast_value(value)
def __str__(self):
return str(self.get())
def __iter__(self):
return iter([self.get()])
def __add__(self, other):
return Scalar(dtype=self.dtype, value=self.get() + Scalar._value(other))
def __sub__(self, other):
return Scalar(dtype=self.dtype, value=self.get() - Scalar._value(other))
def __mul__(self, other):
return Scalar(dtype=self.dtype, value=self.get() * Scalar._value(other))
def __truediv__(self, other):
return Scalar(dtype=self.dtype, value=self.get() / Scalar._value(other))
def __floordiv__(self, other):
return Scalar(dtype=self.dtype, value=self.get() // Scalar._value(other))
def __iadd__(self, other):
self.set(self.get() + Scalar._value(other))
return self
def __isub__(self, other):
self.set(self.get() - Scalar._value(other))
return self
def __imul__(self, other):
self.set(self.get() * Scalar._value(other))
return self
def __idiv__(self, other):
self.set(self.get() / Scalar._value(other))
return self
@classmethod
def _value(cls, other):
if isinstance(other, Scalar):
return other.get()
else:
return other