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