hdmrlib 0.1.0__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.
hdmrlib/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """
2
+ HDMR-Lib: High Dimensional Model Representation and Enhanced Multivariate Products Representation
3
+
4
+ A Python library for tensor decomposition using HDMR and EMPR methods with multi-backend support.
5
+ """
6
+
7
+ __version__ = "0.1.0"
8
+ __author__ = "HDMR-Lib Contributors"
9
+ __license__ = "MIT"
10
+
11
+ from .hdmr import HDMR
12
+ from .empr import EMPR
13
+ from .backends import set_backend, get_backend
14
+
15
+ __all__ = ['HDMR', 'EMPR', 'set_backend', 'get_backend', '__version__']
@@ -0,0 +1,41 @@
1
+ try:
2
+ from .numpy_backend import NumPyBackend
3
+ except Exception:
4
+ NumPyBackend = None
5
+
6
+ try:
7
+ from .torch_backend import TorchBackend
8
+ except Exception:
9
+ TorchBackend = None
10
+
11
+ try:
12
+ from .tensorflow_backend import TensorFlowBackend
13
+ except Exception:
14
+ TensorFlowBackend = None
15
+
16
+ _BACKEND_MAP = {}
17
+ if NumPyBackend is not None:
18
+ _BACKEND_MAP['numpy'] = NumPyBackend()
19
+ if TorchBackend is not None:
20
+ _BACKEND_MAP['torch'] = TorchBackend()
21
+ if TensorFlowBackend is not None:
22
+ _BACKEND_MAP['tensorflow'] = TensorFlowBackend()
23
+
24
+ _CURRENT_BACKEND = 'numpy' if 'numpy' in _BACKEND_MAP else (next(iter(_BACKEND_MAP.keys()), None))
25
+
26
+
27
+ def set_backend(name):
28
+ global _CURRENT_BACKEND
29
+ if name not in _BACKEND_MAP:
30
+ raise ValueError(f"Unknown backend: {name}")
31
+ _CURRENT_BACKEND = name
32
+
33
+
34
+ def get_backend():
35
+ return _CURRENT_BACKEND
36
+
37
+
38
+ def get_backend_instance():
39
+ if _CURRENT_BACKEND is None:
40
+ raise RuntimeError("No available backend. Please install a supported backend and try again.")
41
+ return _BACKEND_MAP[_CURRENT_BACKEND]
@@ -0,0 +1,20 @@
1
+ from abc import ABC, abstractmethod
2
+
3
+ class BaseBackend(ABC):
4
+ @abstractmethod
5
+ def hdmr_decompose(self, tensor, order=2):
6
+ pass
7
+
8
+ @abstractmethod
9
+ def empr_decompose(self, tensor, order=2):
10
+ pass
11
+
12
+ @abstractmethod
13
+ def hdmr_components(self, tensor, max_order=None, **kwargs):
14
+ """Return a dict of component arrays keyed like 'g1','g12',... up to max_order (or full)."""
15
+ pass
16
+
17
+ @abstractmethod
18
+ def empr_components(self, tensor, max_order=None, **kwargs):
19
+ """Return a dict of component arrays keyed like 'g1','g12',... up to max_order (or full)."""
20
+ pass
@@ -0,0 +1,297 @@
1
+ import numpy as np
2
+ from itertools import combinations
3
+ from .base import BaseBackend
4
+
5
+ class NumPyBackend(BaseBackend):
6
+ # HDMR implementation
7
+ class _HDMR:
8
+ def __init__(self, G, weight="avg", custom_weights=None, supports='ones', custom_supports=None):
9
+ self.G = np.array(G, dtype=np.float64)
10
+ self.dimensions = G.shape
11
+ self.custom_supports = custom_supports
12
+ self.support_vectors = self.initialize_support_vectors(supports)
13
+ self.custom_weights = custom_weights
14
+ self.weights = self.initialize_weights(weight)
15
+ self.g0 = self.calculate_g0()
16
+ self.g_components = {}
17
+ self.calculate_hdmr_component(np.arange(len(self.dimensions)))
18
+
19
+ def initialize_weights(self, weight):
20
+ weights = []
21
+ if weight == 'average' or weight == 'avg':
22
+ for dim_size in self.dimensions:
23
+ w = np.ones((dim_size, 1), dtype=np.float64)
24
+ l2_norm = np.linalg.norm(w, ord=2)
25
+ modified_w = (w * (dim_size ** 0.5)) / l2_norm
26
+ weights.append(modified_w / dim_size)
27
+ elif weight == 'custom':
28
+ if self.custom_weights is None:
29
+ raise ValueError("Custom weights must be provided for 'custom' weight type.")
30
+ if len(self.custom_weights) != len(self.dimensions):
31
+ raise ValueError("The number of custom weights must match the number of dimensions.")
32
+ for w in self.custom_weights:
33
+ if not isinstance(w, np.ndarray):
34
+ w = np.array(w, dtype=np.float64)
35
+ weights.append(w)
36
+ elif weight == 'gaussian':
37
+ for dim_size in self.dimensions:
38
+ w = np.random.randn(dim_size, 1).astype(np.float64)
39
+ l2_norm = np.linalg.norm(w, ord=2)
40
+ modified_w = (w * (dim_size ** 0.5)) / l2_norm
41
+ weights.append(modified_w / dim_size)
42
+ elif weight == 'chebyshev':
43
+ for dim_size in self.dimensions:
44
+ k = np.arange(1, dim_size + 1, dtype=np.float64)
45
+ w = np.cos((2 * k - 1) * np.pi / (2 * dim_size))
46
+ w = w.reshape(dim_size, 1)
47
+ l2_norm = np.linalg.norm(w, ord=2)
48
+ modified_w = (w * (dim_size ** 0.5)) / l2_norm
49
+ weights.append(modified_w / dim_size)
50
+ return weights
51
+
52
+ def initialize_support_vectors(self, supports):
53
+ support_vectors = []
54
+ if supports == 'das':
55
+ for i in range(len(self.dimensions)):
56
+ temp = self.G
57
+ ind = 0
58
+ for j in range(len(self.dimensions)):
59
+ if j != i:
60
+ temp = np.mean(temp, axis=ind)
61
+ else:
62
+ ind += 1
63
+ temp = np.expand_dims(temp, axis=-1)
64
+ support_vectors.append(temp)
65
+ elif supports == 'ones':
66
+ for dim_size in self.dimensions:
67
+ s = np.ones((dim_size, 1), dtype=np.float64)
68
+ l2_norm = np.linalg.norm(s, ord=2)
69
+ modified_s = (s * (dim_size ** 0.5)) / l2_norm
70
+ support_vectors.append(modified_s)
71
+ elif supports == 'custom':
72
+ if self.custom_supports is None:
73
+ raise ValueError("Custom supports must be provided for 'custom' support type.")
74
+ if len(self.custom_supports) != len(self.dimensions):
75
+ raise ValueError("The number of custom supports must match the number of dimensions.")
76
+ for s in self.custom_supports:
77
+ if not isinstance(s, np.ndarray):
78
+ s = np.array(s, dtype=np.float64)
79
+ support_vectors.append(s)
80
+ return support_vectors
81
+
82
+ def calculate_g0(self):
83
+ g0 = self.G
84
+ for i, (s, w) in enumerate(zip(self.support_vectors, self.weights)):
85
+ g0 = np.tensordot(g0, s * w, axes=([0], [0]))
86
+ return float(np.squeeze(g0))
87
+
88
+ def convert_g_to_string(self, dims):
89
+ return 'g_' + ','.join(map(str, list(map(lambda x: x+1, dims))))
90
+
91
+ def check_required_components(self, dims):
92
+ for i in range(1, len(dims)):
93
+ for g_combination in combinations(dims, i):
94
+ component_name = self.convert_g_to_string(g_combination)
95
+ if component_name not in self.g_components.keys():
96
+ self.calculate_hdmr_component(g_combination)
97
+
98
+ def calculate_hdmr_component(self, involved_dims):
99
+ self.check_required_components(involved_dims)
100
+ G_component = self.G
101
+ involved_dims = sorted(involved_dims)
102
+ # First part
103
+ ind = 0
104
+ for j, (s, w) in enumerate(zip(self.support_vectors, self.weights)):
105
+ if j not in involved_dims:
106
+ G_component = np.tensordot(G_component, s * w, axes=([ind], [0]))
107
+ else:
108
+ ind += 1
109
+ # Second part
110
+ subtracted = np.squeeze((self.support_vectors[involved_dims[0]] * self.weights[involved_dims[0]]) * self.g0)
111
+ for i in range(1, len(involved_dims)):
112
+ subtracted = np.einsum('...i,jk->...ij', subtracted,
113
+ (self.support_vectors[involved_dims[i]] * self.weights[involved_dims[i]]))
114
+ # Third part
115
+ if len(involved_dims) > 1:
116
+ for i in range(1, len(involved_dims)):
117
+ for g_combination in combinations(involved_dims, i):
118
+ s = [x for x in involved_dims if x not in g_combination]
119
+ term = np.squeeze(self.g_components[self.convert_g_to_string(g_combination)])
120
+ for k in range(len(s)):
121
+ term = np.einsum('...i,jk->...ij', term,
122
+ (self.support_vectors[s[k]] * self.weights[s[k]]))
123
+ subtracted += np.transpose(term, axes=np.argsort(list(g_combination) + s))
124
+ G_component = np.squeeze(G_component)
125
+ subtracted = np.squeeze(subtracted)
126
+ G_component = np.copy(G_component) - subtracted
127
+ self.g_components[self.convert_g_to_string(involved_dims)] = G_component
128
+
129
+ def calculate_approximation(self, order):
130
+ involved_dims = np.arange(len(self.dimensions))
131
+ # First part
132
+ overall_sum = np.squeeze((self.support_vectors[involved_dims[0]] * self.weights[involved_dims[0]]) * self.g0)
133
+ for i in range(1, len(involved_dims)):
134
+ overall_sum = np.einsum('...i,jk->...ij', overall_sum,
135
+ (self.support_vectors[involved_dims[i]] * self.weights[involved_dims[i]]))
136
+ # Second-N'th part
137
+ for i in range(1, order+1):
138
+ for g_combination in combinations(involved_dims, i):
139
+ s = [x for x in involved_dims if x not in g_combination]
140
+ term = np.squeeze(self.g_components[self.convert_g_to_string(g_combination)])
141
+ for k in range(len(s)):
142
+ term = np.einsum('...i,jk->...ij', term,
143
+ (self.support_vectors[s[k]] * self.weights[s[k]]))
144
+ overall_sum += np.transpose(term, axes=np.argsort(list(g_combination) + s))
145
+ return np.squeeze(overall_sum)
146
+
147
+ def calculate_mse(self, order):
148
+ T_empr = self.calculate_approximation(order)
149
+ squared_error = np.linalg.norm(self.G - T_empr, ord='fro')
150
+ num_elements = self.G.size
151
+ mse = squared_error / num_elements
152
+ return float(mse)
153
+
154
+ # EMPR implementation
155
+ class _EMPR:
156
+ def __init__(self, G, supports='das', custom_supports=None):
157
+ self.G = np.array(G, dtype=np.float64)
158
+ self.dimensions = G.shape
159
+ self.custom_supports = custom_supports
160
+ self.support_vectors = self.initialize_support_vectors(supports)
161
+ self.g0 = self.calculate_g0()
162
+ self.g_components = {}
163
+ self.calculate_empr_component(np.arange(len(self.dimensions)))
164
+
165
+ def initialize_support_vectors(self, supports):
166
+ support_vectors = []
167
+ if supports == 'das':
168
+ for i in range(len(self.dimensions)):
169
+ temp = self.G
170
+ ind = 0
171
+ for j in range(len(self.dimensions)):
172
+ if j != i:
173
+ temp = np.mean(temp, axis=ind)
174
+ else:
175
+ ind += 1
176
+ temp = np.expand_dims(temp, -1)
177
+ support_vectors.append(temp)
178
+ elif supports == 'ones':
179
+ for dim_size in self.dimensions:
180
+ s = np.ones((dim_size, 1), dtype=np.float64)
181
+ support_vectors.append(s)
182
+ elif supports == 'custom':
183
+ if self.custom_supports is None:
184
+ raise ValueError("Custom supports must be provided for 'custom' support type.")
185
+ if len(self.custom_supports) != len(self.dimensions):
186
+ raise ValueError("The number of custom supports must match the number of dimensions.")
187
+ for s in self.custom_supports:
188
+ if not isinstance(s, np.ndarray):
189
+ s = np.array(s, dtype=np.float64)
190
+ support_vectors.append(s)
191
+ return support_vectors
192
+
193
+ def calculate_g0(self):
194
+ g0 = self.G
195
+ for i, s in enumerate(self.support_vectors):
196
+ g0 = np.tensordot(g0, s, axes=([0], [0]))
197
+ return float(np.squeeze(g0))
198
+
199
+ def convert_g_to_string(self, dims):
200
+ return 'g_' + ','.join(map(str, list(map(lambda x: x+1, dims))))
201
+
202
+ def check_required_components(self, dims):
203
+ for i in range(1, len(dims)):
204
+ for g_combination in combinations(dims, i):
205
+ component_name = self.convert_g_to_string(g_combination)
206
+ if component_name not in self.g_components.keys():
207
+ self.calculate_empr_component(g_combination)
208
+
209
+ def calculate_empr_component(self, involved_dims):
210
+ self.check_required_components(involved_dims)
211
+ G_component = self.G
212
+ involved_dims = sorted(involved_dims)
213
+ # First part
214
+ ind = 0
215
+ for j, s in enumerate(self.support_vectors):
216
+ if j not in involved_dims:
217
+ G_component = np.tensordot(G_component, s, axes=([ind], [0]))
218
+ else:
219
+ ind += 1
220
+ # Second part
221
+ subtracted = np.squeeze(self.support_vectors[involved_dims[0]] * self.g0)
222
+ for i in range(1, len(involved_dims)):
223
+ subtracted = np.einsum('...i,jk->...ij', subtracted,
224
+ self.support_vectors[involved_dims[i]])
225
+ # Third part
226
+ if len(involved_dims) > 1:
227
+ for i in range(1, len(involved_dims)):
228
+ for g_combination in combinations(involved_dims, i):
229
+ s = [x for x in involved_dims if x not in g_combination]
230
+ term = np.squeeze(self.g_components[self.convert_g_to_string(g_combination)])
231
+ for k in range(len(s)):
232
+ term = np.einsum('...i,jk->...ij', term,
233
+ self.support_vectors[s[k]])
234
+ subtracted += np.transpose(term, np.argsort(list(g_combination) + s))
235
+ G_component = np.squeeze(G_component)
236
+ subtracted = np.squeeze(subtracted)
237
+ G_component = G_component - subtracted
238
+ self.g_components[self.convert_g_to_string(involved_dims)] = G_component
239
+
240
+ def calculate_approximation(self, order):
241
+ involved_dims = np.arange(len(self.dimensions))
242
+ # First part
243
+ overall_sum = np.squeeze(self.support_vectors[involved_dims[0]] * self.g0)
244
+ for i in range(1, len(involved_dims)):
245
+ overall_sum = np.einsum('...i,jk->...ij', overall_sum,
246
+ self.support_vectors[involved_dims[i]])
247
+ # Second-N'th part
248
+ for i in range(1, order+1):
249
+ for g_combination in combinations(involved_dims, i):
250
+ s = [x for x in involved_dims if x not in g_combination]
251
+ term = np.squeeze(self.g_components[self.convert_g_to_string(g_combination)])
252
+ for k in range(len(s)):
253
+ term = np.einsum('...i,jk->...ij', term,
254
+ self.support_vectors[s[k]])
255
+ overall_sum += np.transpose(term, np.argsort(list(g_combination) + s))
256
+ return np.squeeze(overall_sum)
257
+
258
+ def calculate_mse(self, order):
259
+ T_empr = self.calculate_approximation(order)
260
+ squared_error = np.linalg.norm(self.G - T_empr)
261
+ num_elements = self.G.size
262
+ mse = squared_error / num_elements
263
+ return float(mse)
264
+
265
+ def hdmr_decompose(self, tensor, order=2, **kwargs):
266
+ model = self._HDMR(tensor, **kwargs)
267
+ return model.calculate_approximation(order)
268
+
269
+ def empr_decompose(self, tensor, order=2, **kwargs):
270
+ model = self._EMPR(tensor, **kwargs)
271
+ return model.calculate_approximation(order)
272
+
273
+ def hdmr_components(self, tensor, max_order=None, **kwargs):
274
+ model = self._HDMR(tensor, **kwargs)
275
+ num_dims = len(model.dimensions)
276
+ if max_order is None:
277
+ max_order = num_dims
278
+ components = {}
279
+ dims = list(range(num_dims))
280
+ for r in range(1, min(max_order, num_dims) + 1):
281
+ for comb in combinations(dims, r):
282
+ key = model.convert_g_to_string(comb)
283
+ components[key] = model.g_components[key]
284
+ return components
285
+
286
+ def empr_components(self, tensor, max_order=None, **kwargs):
287
+ model = self._EMPR(tensor, **kwargs)
288
+ num_dims = len(model.dimensions)
289
+ if max_order is None:
290
+ max_order = num_dims
291
+ components = {}
292
+ dims = list(range(num_dims))
293
+ for r in range(1, min(max_order, num_dims) + 1):
294
+ for comb in combinations(dims, r):
295
+ key = model.convert_g_to_string(comb)
296
+ components[key] = model.g_components[key]
297
+ return components