hdmrlib 0.1.0__tar.gz

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-0.1.0/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 HDMR-Lib Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
@@ -0,0 +1,10 @@
1
+ include README.md
2
+ include LICENSE
3
+ include requirements.txt
4
+ recursive-include examples *.py *.md
5
+ recursive-include tests *.py
6
+ exclude examples/__pycache__
7
+ exclude tests/__pycache__
8
+ global-exclude *.pyc
9
+ global-exclude __pycache__
10
+
hdmrlib-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,480 @@
1
+ Metadata-Version: 2.4
2
+ Name: hdmrlib
3
+ Version: 0.1.0
4
+ Summary: High Dimensional Model Representation (HDMR) and Enhanced Multivariate Products Representation (EMPR) library
5
+ Author: HDMR-Lib Contributors
6
+ Author-email: Muhammed Enis Sen <m.enis.97@gmail.com>, Bugra Eyidogan <bugra.eyidogan@gmail.com>, Pinar Guler <yalcin.pinar2@gmail.com>
7
+ License-Expression: MIT
8
+ Project-URL: Homepage, https://github.com/hdmrlib/HDMR-Lib
9
+ Project-URL: Documentation, https://github.com/hdmrlib/HDMR-Lib#readme
10
+ Project-URL: Repository, https://github.com/hdmrlib/HDMR-Lib
11
+ Project-URL: Bug Tracker, https://github.com/hdmrlib/HDMR-Lib/issues
12
+ Keywords: hdmr,empr,tensor,decomposition,sensitivity-analysis
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Requires-Python: >=3.8
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: numpy>=1.22
24
+ Requires-Dist: torch>=2.2
25
+ Requires-Dist: tensorflow>=2.14
26
+ Provides-Extra: torch
27
+ Requires-Dist: torch>=2.2; extra == "torch"
28
+ Provides-Extra: tensorflow
29
+ Requires-Dist: tensorflow>=2.14; extra == "tensorflow"
30
+ Provides-Extra: all
31
+ Requires-Dist: torch>=2.2; extra == "all"
32
+ Requires-Dist: tensorflow>=2.14; extra == "all"
33
+ Provides-Extra: dev
34
+ Requires-Dist: pytest>=7.0; extra == "dev"
35
+ Requires-Dist: pytest-cov>=4.0; extra == "dev"
36
+ Requires-Dist: matplotlib>=3.5; extra == "dev"
37
+ Dynamic: license-file
38
+
39
+ # HDMR-Lib
40
+
41
+ **High Dimensional Model Representation and Enhanced Multivariate Products Representation**
42
+
43
+ A powerful Python library for tensor decomposition using HDMR and EMPR methods with multi-backend support (NumPy, PyTorch, TensorFlow).
44
+
45
+ ---
46
+
47
+ ## 🎯 **What is HDMR-Lib?**
48
+
49
+ HDMR-Lib implements two state-of-the-art tensor decomposition methods:
50
+
51
+ - **HDMR (High Dimensional Model Representation)**: Decomposes multivariate functions into hierarchical components with weighted support vectors
52
+ - **EMPR (Enhanced Multivariate Products Representation)**: An optimized variant using unweighted support vectors for better computational efficiency
53
+
54
+ Both methods represent complex multivariate functions as sums of lower-dimensional components, making them ideal for:
55
+ - **Sensitivity Analysis** - Identify which variables matter most
56
+ - **Uncertainty Quantification** - Understand how input uncertainties propagate
57
+ - **Function Approximation** - Approximate complex functions with simpler components
58
+ - **Dimensionality Reduction** - Reduce computational complexity while preserving accuracy
59
+
60
+ ---
61
+
62
+ ## πŸš€ **Quick Start**
63
+
64
+ ### Installation
65
+
66
+ #### Option 1: Install from PyPI (Recommended)
67
+
68
+ ```bash
69
+ # Install with all backends (NumPy, PyTorch, TensorFlow)
70
+ pip install hdmrlib
71
+
72
+ # Development installation (includes testing tools)
73
+ pip install hdmrlib[dev]
74
+ ```
75
+
76
+ #### Option 2: Install from Source
77
+
78
+ 1. **Clone the repository:**
79
+ ```bash
80
+ git clone https://github.com/hdmrlib/HDMR-Lib.git
81
+ cd HDMR-Lib
82
+ ```
83
+
84
+ 2. **Install in development mode:**
85
+ ```bash
86
+ pip install -e .
87
+
88
+ # Or with development tools
89
+ pip install -e .[dev]
90
+ ```
91
+
92
+ ### GPU Acceleration (Optional)
93
+
94
+ For CUDA/GPU support:
95
+
96
+ ```bash
97
+ # PyTorch with CUDA
98
+ pip install torch --index-url https://download.pytorch.org/whl/cu118 # CUDA 11.8
99
+
100
+ # TensorFlow (GPU support included)
101
+ pip install tensorflow
102
+ ```
103
+
104
+ **Requirements:**
105
+ - NVIDIA GPU with CUDA capability
106
+ - CUDA Toolkit (11.8 or 12.1)
107
+ - cuDNN library
108
+
109
+ ### Basic Usage
110
+
111
+ ```python
112
+ import numpy as np
113
+ from hdmrlib import HDMR, EMPR, set_backend
114
+
115
+ # Create test data
116
+ tensor = np.random.rand(5, 5, 5)
117
+
118
+ # Set backend (numpy, torch, tensorflow)
119
+ set_backend('numpy')
120
+
121
+ # EMPR Decomposition
122
+ empr_model = EMPR(tensor)
123
+ empr_result = empr_model.decompose(order=2)
124
+ empr_components = empr_model.components(max_order=2)
125
+
126
+ # HDMR Decomposition
127
+ hdmr_model = HDMR(tensor)
128
+ hdmr_result = hdmr_model.decompose(order=2)
129
+ hdmr_components = hdmr_model.components(max_order=2)
130
+
131
+ print(f"EMPR MSE: {np.mean((tensor - empr_result) ** 2):.6e}")
132
+ print(f"Available components: {list(empr_components.keys())}")
133
+ ```
134
+
135
+ ---
136
+
137
+ ## πŸ“š **Detailed Usage Guide**
138
+
139
+ ### 1. **Backend Selection**
140
+
141
+ HDMR-Lib supports multiple computational backends:
142
+
143
+ ```python
144
+ from hdmrlib import set_backend, get_backend
145
+
146
+ # Available backends
147
+ set_backend('numpy') # NumPy (default, always available)
148
+ set_backend('torch') # PyTorch (requires torch>=2.2)
149
+ set_backend('tensorflow') # TensorFlow (requires tensorflow>=2.14)
150
+
151
+ # Check current backend
152
+ print(f"Current backend: {get_backend()}")
153
+ ```
154
+
155
+ ### 2. **EMPR (Enhanced Multivariate Products Representation)**
156
+
157
+ EMPR provides efficient decomposition with configurable support vectors:
158
+
159
+ ```python
160
+ import numpy as np
161
+ from hdmrlib import EMPR
162
+
163
+ # Create test tensor
164
+ x, y, z = np.meshgrid(np.linspace(0, 1, 6), np.linspace(0, 1, 6), np.linspace(0, 1, 6), indexing='ij')
165
+ tensor = 1 + 2*x + 3*y + 4*z + x*y + x*z + y*z
166
+
167
+ # Initialize EMPR with different support vectors
168
+ empr_das = EMPR(tensor, supports='das') # Data-Adaptive Supports (recommended)
169
+ empr_ones = EMPR(tensor, supports='ones') # Uniform supports
170
+
171
+ # Decompose at different orders
172
+ result_order1 = empr_das.decompose(order=1) # Main effects only
173
+ result_order2 = empr_das.decompose(order=2) # Main effects + 2-way interactions
174
+ result_order3 = empr_das.decompose(order=3) # Full decomposition
175
+
176
+ # Extract components
177
+ components = empr_das.components(max_order=3)
178
+ print("Available components:", list(components.keys()))
179
+ # Output: ['g1', 'g2', 'g3', 'g12', 'g13', 'g23', 'g123']
180
+
181
+ # Component interpretation:
182
+ # g1, g2, g3: Main effects (univariate)
183
+ # g12, g13, g23: Two-way interactions (bivariate)
184
+ # g123: Three-way interaction (trivariate)
185
+ ```
186
+
187
+ ### 3. **HDMR (High Dimensional Model Representation)**
188
+
189
+ HDMR uses weighted support vectors for enhanced numerical stability:
190
+
191
+ ```python
192
+ from hdmrlib import HDMR
193
+
194
+ # Initialize HDMR with different weight types
195
+ hdmr_avg = HDMR(tensor, weight='avg') # Average weights (default)
196
+ hdmr_gauss = HDMR(tensor, weight='gaussian') # Gaussian weights
197
+ hdmr_cheb = HDMR(tensor, weight='chebyshev') # Chebyshev weights
198
+
199
+ # Custom weights
200
+ custom_weights = [np.ones((6, 1)), np.ones((6, 1)), np.ones((6, 1))]
201
+ hdmr_custom = HDMR(tensor, weight='custom', custom_weights=custom_weights)
202
+
203
+ # Decompose and analyze
204
+ result = hdmr_avg.decompose(order=2)
205
+ components = hdmr_avg.components(max_order=2)
206
+
207
+ # Calculate reconstruction quality
208
+ mse = np.mean((tensor - result) ** 2)
209
+ print(f"HDMR Reconstruction MSE: {mse:.6e}")
210
+ ```
211
+
212
+ ### 4. **Custom Support Vectors**
213
+
214
+ For advanced users, you can provide custom support vectors:
215
+
216
+ ```python
217
+ # Define custom support vectors for each dimension
218
+ custom_supports = [
219
+ np.linspace(0, 1, 6).reshape(-1, 1), # Linear support for dimension 1
220
+ np.exp(np.linspace(-1, 1, 6)).reshape(-1, 1), # Exponential for dimension 2
221
+ np.sin(np.linspace(0, np.pi, 6)).reshape(-1, 1) # Sinusoidal for dimension 3
222
+ ]
223
+
224
+ # Use custom supports
225
+ empr_custom = EMPR(tensor, supports='custom', custom_supports=custom_supports)
226
+ result = empr_custom.decompose(order=2)
227
+ ```
228
+
229
+ ### 5. **Multi-Backend Comparison**
230
+
231
+ Compare performance across different backends:
232
+
233
+ ```python
234
+ import time
235
+ from hdmrlib import set_backend
236
+
237
+ backends = ['numpy', 'torch', 'tensorflow']
238
+ tensor = np.random.rand(8, 8, 8)
239
+
240
+ for backend in backends:
241
+ try:
242
+ set_backend(backend)
243
+
244
+ start_time = time.time()
245
+ model = EMPR(tensor)
246
+ result = model.decompose(order=2)
247
+ elapsed = time.time() - start_time
248
+
249
+ mse = np.mean((tensor - result) ** 2)
250
+ print(f"{backend:>12}: {elapsed:.4f}s, MSE: {mse:.6e}")
251
+
252
+ except Exception as e:
253
+ print(f"{backend:>12}: Error - {e}")
254
+ ```
255
+
256
+ ---
257
+
258
+ ## πŸ”¬ **Advanced Examples**
259
+
260
+ ### Sensitivity Analysis
261
+
262
+ Analyze which variables contribute most to function variation:
263
+
264
+ ```python
265
+ # Create function with known variable importance
266
+ x1, x2, x3 = np.meshgrid(np.linspace(-1, 1, 8), np.linspace(-1, 1, 8), np.linspace(-1, 1, 8), indexing='ij')
267
+ tensor = 5*x1**2 + 2*x2 + 0.1*x3 + x1*x2 # x1 most important, x3 least
268
+
269
+ # Decompose with EMPR
270
+ model = EMPR(tensor, supports='das')
271
+ components = model.components(max_order=2)
272
+
273
+ # Calculate component variances (sensitivity indicators)
274
+ sensitivities = {}
275
+ for comp_name, comp_tensor in components.items():
276
+ sensitivities[comp_name] = np.var(comp_tensor)
277
+
278
+ # Sort by importance
279
+ sorted_sens = sorted(sensitivities.items(), key=lambda x: x[1], reverse=True)
280
+ print("Component sensitivities (most to least important):")
281
+ for comp, sens in sorted_sens:
282
+ print(f" {comp}: {sens:.4f}")
283
+ ```
284
+
285
+ ### Function Approximation
286
+
287
+ Use HDMR/EMPR for efficient function approximation:
288
+
289
+ ```python
290
+ # Original expensive function
291
+ def expensive_function(x, y, z):
292
+ return np.sin(np.pi*x) * np.cos(np.pi*y) * np.exp(z) + x*y*z
293
+
294
+ # Create training data
295
+ x, y, z = np.meshgrid(np.linspace(0, 1, 10), np.linspace(0, 1, 10), np.linspace(0, 1, 10), indexing='ij')
296
+ training_data = expensive_function(x, y, z)
297
+
298
+ # Train EMPR surrogate
299
+ surrogate = EMPR(training_data, supports='das')
300
+
301
+ # Test approximation quality at different orders
302
+ for order in [1, 2, 3]:
303
+ approx = surrogate.decompose(order=order)
304
+
305
+ # Compare on training grid
306
+ error = np.mean((training_data - approx) ** 2)
307
+ print(f"Order {order} approximation MSE: {error:.6e}")
308
+ ```
309
+
310
+ ### Performance Optimization
311
+
312
+ Optimize performance for large tensors:
313
+
314
+ ```python
315
+ # For large tensors, use appropriate backend
316
+ tensor_large = np.random.rand(20, 20, 20)
317
+
318
+ # Try PyTorch backend for potential GPU acceleration
319
+ try:
320
+ set_backend('torch')
321
+ model_torch = EMPR(tensor_large)
322
+ result_torch = model_torch.decompose(order=2)
323
+ print("PyTorch backend successful")
324
+ except:
325
+ print("PyTorch not available, using NumPy")
326
+ set_backend('numpy')
327
+ model_cpu = EMPR(tensor_large)
328
+ result_cpu = model_cpu.decompose(order=2)
329
+
330
+ # For very large tensors, consider lower order approximations
331
+ model = EMPR(tensor_large)
332
+ result_fast = model.decompose(order=1) # Faster, main effects only
333
+ result_accurate = model.decompose(order=3) # Slower, full interactions
334
+ ```
335
+
336
+ ---
337
+
338
+ ## πŸ“Š **Component Interpretation**
339
+
340
+ Understanding HDMR/EMPR components:
341
+
342
+ | Component | Description | Mathematical Form | Interpretation |
343
+ |-----------|-------------|-------------------|----------------|
344
+ | `g1`, `g2`, `g3` | Main effects | f(x₁), f(xβ‚‚), f(x₃) | Individual variable impacts |
345
+ | `g12`, `g13`, `g23` | Two-way interactions | f(x₁,xβ‚‚), f(x₁,x₃), f(xβ‚‚,x₃) | Pairwise variable interactions |
346
+ | `g123` | Three-way interactions | f(x₁,xβ‚‚,x₃) | Complex multi-variable interactions |
347
+
348
+ **Decomposition Formula:**
349
+ ```
350
+ F(x₁,xβ‚‚,x₃) β‰ˆ fβ‚€ + g₁(x₁) + gβ‚‚(xβ‚‚) + g₃(x₃) + g₁₂(x₁,xβ‚‚) + g₁₃(x₁,x₃) + g₂₃(xβ‚‚,x₃) + g₁₂₃(x₁,xβ‚‚,x₃)
351
+ ```
352
+
353
+ ---
354
+
355
+ ## 🎯 **Best Practices**
356
+
357
+ ### 1. **Backend Selection**
358
+ - **NumPy**: Default choice, good for most applications (CPU only)
359
+ - **PyTorch**: Better for integration with deep learning workflows (CPU/GPU)
360
+ - **TensorFlow**: Good for large-scale distributed computing (CPU/GPU)
361
+
362
+ ### 2. **Support Vector Choice**
363
+ - **DAS (Data-Adaptive Supports)**: Usually provides best approximation quality
364
+ - **Ones**: Simpler, faster, good for well-behaved functions
365
+ - **Custom**: For domain-specific knowledge or special function properties
366
+
367
+ ### 3. **Order Selection**
368
+ - **Order 1**: Fast, captures main effects only
369
+ - **Order 2**: Good balance of speed and accuracy for most applications
370
+ - **Order 3+**: Full accuracy but exponentially more expensive
371
+
372
+ ### 4. **Weight Configuration (HDMR)**
373
+ - **Average**: Good default choice for most functions
374
+ - **Gaussian**: Better for smooth functions
375
+ - **Chebyshev**: Good for polynomial-like functions
376
+ - **Custom**: When you have domain knowledge about function behavior
377
+
378
+ ---
379
+
380
+ ## πŸ”§ **Troubleshooting**
381
+
382
+ ### Common Issues
383
+
384
+ **1. Import Errors**
385
+ ```python
386
+ # If you get import errors, ensure you're in the project directory
387
+ import sys
388
+ import os
389
+ sys.path.insert(0, os.path.dirname(__file__))
390
+ ```
391
+
392
+ **2. Backend Not Available**
393
+ ```python
394
+ from hdmrlib import set_backend
395
+
396
+ try:
397
+ set_backend('torch')
398
+ except ValueError as e:
399
+ print(f"Backend error: {e}")
400
+ set_backend('numpy') # Fallback to NumPy
401
+ ```
402
+
403
+ **3. Memory Issues with Large Tensors**
404
+ ```python
405
+ # For memory issues, reduce decomposition order or tensor size
406
+ tensor_large = np.random.rand(50, 50, 50)
407
+
408
+ # Instead of order=3, use order=2 or order=1
409
+ model = EMPR(tensor_large)
410
+ result = model.decompose(order=1) # Uses less memory
411
+ ```
412
+
413
+ **4. Poor Approximation Quality**
414
+ ```python
415
+ # Try different support vectors or increase order
416
+ model_das = EMPR(tensor, supports='das')
417
+ model_ones = EMPR(tensor, supports='ones')
418
+
419
+ result_das = model_das.decompose(order=2)
420
+ result_ones = model_ones.decompose(order=2)
421
+
422
+ mse_das = np.mean((tensor - result_das) ** 2)
423
+ mse_ones = np.mean((tensor - result_ones) ** 2)
424
+
425
+ print(f"DAS MSE: {mse_das:.6e}, Ones MSE: {mse_ones:.6e}")
426
+ ```
427
+
428
+ ---
429
+
430
+ ## πŸ“ˆ **Performance Benchmarks**
431
+
432
+ Typical performance on various tensor sizes (NumPy backend, order=2):
433
+
434
+ | Tensor Size | Elements | Time (seconds) | Memory (MB) |
435
+ |-------------|----------|----------------|-------------|
436
+ | 5Γ—5Γ—5 | 125 | 0.001 | <1 |
437
+ | 10Γ—10Γ—10 | 1,000 | 0.01 | ~5 |
438
+ | 20Γ—20Γ—20 | 8,000 | 0.1 | ~50 |
439
+ | 50Γ—50Γ—50 | 125,000 | 2.0 | ~500 |
440
+
441
+ *Performance varies with hardware and decomposition order*
442
+
443
+ ---
444
+
445
+ ## 🀝 **Contributing**
446
+
447
+ We welcome contributions! To contribute:
448
+
449
+ 1. Fork the repository
450
+ 2. Create a feature branch: `git checkout -b feature-name`
451
+ 3. Make your changes and add tests
452
+ 4. Run tests: `python -m pytest tests/`
453
+ 5. Submit a pull request
454
+
455
+ ---
456
+
457
+ ## πŸ“ **License**
458
+
459
+ This project is licensed under the MIT License - see the LICENSE file for details.
460
+
461
+ ---
462
+
463
+ ## πŸ“š **References**
464
+
465
+ 1. Sobol, I. M. (2001). Global sensitivity indices for nonlinear mathematical models and their Monte Carlo estimates. *Mathematics and Computers in Simulation*, 55(1-3), 271-280.
466
+
467
+ 2. Rabitz, H., & Aliş, Γ–. F. (1999). General foundations of high‐dimensional model representations. *Journal of Mathematical Chemistry*, 25(2-3), 197-233.
468
+
469
+ 3. Li, G., Wang, S. W., & Rabitz, H. (2002). Practical approaches to construct RS-HDMR component functions. *The Journal of Physical Chemistry A*, 106(37), 8721-8733.
470
+
471
+ ---
472
+
473
+ ## πŸ“ž **Support**
474
+ - πŸ› Issues: [GitHub Issues](https://github.com/hdmrlib/HDMR-Lib/issues)
475
+ - πŸ’¬ Discussions: [GitHub Discussions](https://github.com/hdmrlib/HDMR-Lib/discussions)
476
+
477
+ ---
478
+
479
+ **Made with ❀️ for the scientific computing community**
480
+