nrl-tracker 1.5.0__py3-none-any.whl → 1.7.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: nrl-tracker
3
- Version: 1.5.0
3
+ Version: 1.7.0
4
4
  Summary: Python port of the U.S. Naval Research Laboratory's Tracker Component Library for target tracking algorithms
5
5
  Author: Original: David F. Crouse, Naval Research Laboratory
6
6
  Maintainer: Python Port Contributors
@@ -63,15 +63,16 @@ Requires-Dist: plotly>=5.15.0; extra == "visualization"
63
63
 
64
64
  # Tracker Component Library (Python)
65
65
 
66
- [![PyPI version](https://img.shields.io/badge/pypi-v1.5.0-blue.svg)](https://pypi.org/project/nrl-tracker/)
66
+ [![PyPI version](https://img.shields.io/badge/pypi-v1.7.0-blue.svg)](https://pypi.org/project/nrl-tracker/)
67
67
  [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
68
68
  [![License: Public Domain](https://img.shields.io/badge/License-Public%20Domain-brightgreen.svg)](https://en.wikipedia.org/wiki/Public_domain)
69
69
  [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
70
- [![Tests](https://img.shields.io/badge/tests-1850%20passing-success.svg)](https://github.com/nedonatelli/TCL)
70
+ [![Tests](https://img.shields.io/badge/tests-1988%20passing-success.svg)](https://github.com/nedonatelli/TCL)
71
+ [![MATLAB Parity](https://img.shields.io/badge/MATLAB%20Parity-100%25-brightgreen.svg)](docs/gap_analysis.rst)
71
72
 
72
73
  A Python port of the [U.S. Naval Research Laboratory's Tracker Component Library](https://github.com/USNavalResearchLaboratory/TrackerComponentLibrary), a comprehensive collection of algorithms for target tracking, estimation, coordinate systems, and related mathematical functions.
73
74
 
74
- **840+ functions** | **148 modules** | **1,850 tests** | **15+ algorithm categories**
75
+ **1,070+ functions** | **153 modules** | **1,988 tests** | **100% MATLAB parity**
75
76
 
76
77
  ## Overview
77
78
 
@@ -79,12 +80,15 @@ The Tracker Component Library provides building blocks for developing target tra
79
80
 
80
81
  - **Coordinate Systems**: Conversions between Cartesian, spherical, geodetic, and other coordinate systems
81
82
  - **Dynamic Models**: State transition matrices for constant velocity, coordinated turn, and other motion models
82
- - **Estimation Algorithms**: Kalman filters (EKF, UKF, etc.), particle filters, and batch estimation
83
- - **Assignment Algorithms**: Hungarian algorithm, auction algorithms, and multi-dimensional assignment
83
+ - **Estimation Algorithms**: Kalman filters (EKF, UKF, CKF, H-infinity), particle filters, smoothers, and batch estimation
84
+ - **Assignment Algorithms**: Hungarian algorithm, auction algorithms, 3D/ND assignment, k-best assignments
85
+ - **Data Association**: Global Nearest Neighbor, JPDA, MHT for multi-target tracking
84
86
  - **Mathematical Functions**: Special functions, statistics, numerical integration, and more
85
- - **Astronomical Code**: Ephemeris calculations, time systems, celestial mechanics
86
- - **Navigation**: Geodetic calculations, INS algorithms, GNSS utilities
87
- - **Geophysical Models**: Gravity, magnetism, atmosphere, and terrain models
87
+ - **Astronomical Code**: SGP4/SDP4 propagation, TLE parsing, special orbits (parabolic/hyperbolic), ephemerides, relativistic corrections
88
+ - **Reference Frames**: GCRF, ITRF, TEME, TOD, MOD with full transformation chains
89
+ - **Navigation**: Geodetic calculations, INS mechanization, GNSS utilities, INS/GNSS integration
90
+ - **Geophysical Models**: Gravity (WGS84, EGM96/2008), magnetism (WMM, IGRF), atmosphere, tides, terrain
91
+ - **Signal Processing**: Digital filters, matched filtering, CFAR detection, transforms (FFT, STFT, wavelets)
88
92
 
89
93
  ## Installation
90
94
 
@@ -1,24 +1,30 @@
1
- pytcl/__init__.py,sha256=our-crvOz-5G39s3UNhw5wyM7pe9wFNrJJooFLorYeQ,1893
1
+ pytcl/__init__.py,sha256=MzvSIKPmRaoieVDhHJbYHqNeZpQbRSj8sVclDiW8wbY,1893
2
2
  pytcl/logging_config.py,sha256=j7Zrkal5LwUIos-_Dm3cGKUR-jMkFdSZZikJTtzTeoE,8883
3
- pytcl/assignment_algorithms/__init__.py,sha256=f9V-TkEVmiKYYyth4PTpDfJvA7yYV_ys6Zix-QwWIYY,2136
3
+ pytcl/assignment_algorithms/__init__.py,sha256=XI5qIP4CWqf3SyVA2RIXcJC5pp6_BKd60GZAduDheg8,2976
4
4
  pytcl/assignment_algorithms/data_association.py,sha256=tsRxWJZk9aAPmE99BKXGouEpFfZrjPjb4HXvgxFUHhU,11405
5
5
  pytcl/assignment_algorithms/gating.py,sha256=fN_oAOkv7nYYOWE1oPOLrcCn3xEpKdMVlFSbRMAURxY,10815
6
6
  pytcl/assignment_algorithms/jpda.py,sha256=Hv55j3J9qVwzlUfWdXdSasodTyB1ZKdgEpo5dBh95O8,19582
7
+ pytcl/assignment_algorithms/nd_assignment.py,sha256=dqsvV1tSIlpVlVzhxCD_KOQBwYn63zgXEPpXxr3hLO0,11328
8
+ pytcl/assignment_algorithms/network_flow.py,sha256=nfghUOk1c1i0j43nYsKQwLfPwrYuuhJ4nOVvuWunoRw,10162
7
9
  pytcl/assignment_algorithms/three_dimensional/__init__.py,sha256=1Q40OUlUQoo7YKEucwdrSNo3D4A0Zibvkr8z4TpueBg,526
8
10
  pytcl/assignment_algorithms/three_dimensional/assignment.py,sha256=9BJhwlYu3JJ0kZ9sRyKKfpdvQdL4WYYHCtLbvaWycBw,19212
9
11
  pytcl/assignment_algorithms/two_dimensional/__init__.py,sha256=4Evsn__9hTfI2i8m8Ngl-Zy0Fa2OydKmDKlZlH6jaao,778
10
12
  pytcl/assignment_algorithms/two_dimensional/assignment.py,sha256=eh87MBb-uiUSI1MXj4HrreRKB6Z8rxAyDkNQ8-u4SbM,11848
11
13
  pytcl/assignment_algorithms/two_dimensional/kbest.py,sha256=yiTToLuP7xWxQlQ8E-fpgXg-5iu0nnXcJXStjUB0nOE,17284
12
- pytcl/astronomical/__init__.py,sha256=Dtf6hqXyKyFL5VP-sqI7m2QGK6l-rqRGxVIhgDuYHOg,7182
14
+ pytcl/astronomical/__init__.py,sha256=12uVzUd9lRSb_o47pdJa0xUuYvI0Ipnrw2Y2-nJbgvY,9737
13
15
  pytcl/astronomical/ephemerides.py,sha256=x2500S0rF1D2h0dMR_2BnZaChbBZTooHLdrevttxlAc,16471
14
16
  pytcl/astronomical/lambert.py,sha256=Lc8FT1JmpI9WSXsG2s5vIRkSoBSV7r5hd3o2bGh2Ojo,15607
15
17
  pytcl/astronomical/orbital_mechanics.py,sha256=8GssRanwTowCl6PJYqmB_SDnNznLUq5gkPa3j6iEo3U,19965
16
- pytcl/astronomical/reference_frames.py,sha256=gkbQrhHY_EN0xt8i7m0dIJp67GgpEcDArY7J3YH-Mb8,17981
18
+ pytcl/astronomical/reference_frames.py,sha256=oZkU3i_6dy6UUsx0iVyBkevO24Mexk-dvcBkDTx28aI,35509
17
19
  pytcl/astronomical/relativity.py,sha256=YPsXLD-VRh-nqs1laC-wKpRO00fflm4GkyLhojPydbo,15441
20
+ pytcl/astronomical/sgp4.py,sha256=iNZrqMRUzR-LFeZiluzlNmkwxeYbIyF2F1cygyeEZVE,21546
21
+ pytcl/astronomical/special_orbits.py,sha256=WccNjezmjPkL1f-Wn1ugHZTm37RrdRWIJAG3P-v8lao,12745
18
22
  pytcl/astronomical/time_systems.py,sha256=Jg0Zaq60hc4Ts1aQtb5bK4KSZhz-uQse8gYC89Y0-TA,15243
19
- pytcl/atmosphere/__init__.py,sha256=swugW8rY2Jof-z_kPQ2P9vInBYjr1M69C1Q8AgN3RVo,1457
23
+ pytcl/astronomical/tle.py,sha256=t3e2-0f3Wiz77q-pC2jfpohkrDfoYOEHacpNgWMNLAk,14638
24
+ pytcl/atmosphere/__init__.py,sha256=uotCJzu_5W1XlIfQmRAVdx368HG9TU7-kZQrNCPi4u0,1685
20
25
  pytcl/atmosphere/ionosphere.py,sha256=1qC3hY-27pD0XcLBjU735deKYmmi6qnj2fDG1zNbTqg,14681
21
26
  pytcl/atmosphere/models.py,sha256=pMLv8D7qoFqLZrlbTHLJJULOdDdhPskJ1m7KVKLV63E,9584
27
+ pytcl/atmosphere/nrlmsise00.py,sha256=PYMb6negGr6IFk2-CFoq6KpvcSpPAHYXr8Q154JrA1U,26966
22
28
  pytcl/clustering/__init__.py,sha256=bYdhC_XJEt6KUUni9bIPxaddXNEGmIJQvGkA14rK4J8,1697
23
29
  pytcl/clustering/dbscan.py,sha256=PS6QlOwHFerbZNEb3zcNhN4oNQpgOOw5y0WskQzyKIo,7364
24
30
  pytcl/clustering/gaussian_mixture.py,sha256=U5U0Z46tZWdTLNdNNNJenoeviwZRAOvexVFYVLt4QMc,22865
@@ -35,7 +41,7 @@ pytcl/containers/track_list.py,sha256=6q9Qgcwm-8H_JqtOCsMssF27av4XaSkhfDl-MWb1AB
35
41
  pytcl/containers/vptree.py,sha256=4tUq0ktafusU1PILZkQxi27CZryKlsHtFbym-vZYQWk,8747
36
42
  pytcl/coordinate_systems/__init__.py,sha256=jwYhu_-9AvOeP9WLG9PYtyDwfe0GjxNZ9-xCqiLymW4,3909
37
43
  pytcl/coordinate_systems/conversions/__init__.py,sha256=PkNevB78vBw0BkalydJBbQO91AyiMJxKRrgJNt4HsYc,1100
38
- pytcl/coordinate_systems/conversions/geodetic.py,sha256=qQSnJRt3jg5KiostvzyslPIbfn-1xBluo1r12oavWTQ,15737
44
+ pytcl/coordinate_systems/conversions/geodetic.py,sha256=Ieacxtco_wQkXeHjI6gMc_B3_gIoaNq440w4WgLbTIY,23172
39
45
  pytcl/coordinate_systems/conversions/spherical.py,sha256=q7k9l5mJbVzVdNj9Gcq4ibFxax8z_mVpJfITRBzx630,10812
40
46
  pytcl/coordinate_systems/jacobians/__init__.py,sha256=CRGB8GzvGT_sr4Ynm51S7gSX8grqt1pO1Pq1MWmHPTs,890
41
47
  pytcl/coordinate_systems/jacobians/jacobians.py,sha256=1KufIoktm9mXLO34X9KjysdMpu7itGwfssRyAdkTTN8,11703
@@ -47,13 +53,17 @@ pytcl/core/__init__.py,sha256=3GFQX_Q9f7fhmWlA6OQiS6OpM7HWhyT9iQhB8Mhi_kk,1580
47
53
  pytcl/core/array_utils.py,sha256=SsgEiAoRCWxAVKq1aa5-nPdOi-2AB6XNObu0IaGClUk,13983
48
54
  pytcl/core/constants.py,sha256=lZVDK5zsSR02_4b2Nqx9KDtZT9QaYhkZ9wuoODbifd4,8693
49
55
  pytcl/core/validation.py,sha256=nUmG8UmUk85dQ4CxJRipACb8zjsrAJPiyK8ADZN_KvU,23426
50
- pytcl/dynamic_estimation/__init__.py,sha256=jA5FF6kHYklY5LMOfZaKcCeiPTpVe8vHIMp3ECDOmsc,4582
56
+ pytcl/dynamic_estimation/__init__.py,sha256=JUirqRsnswY8Ge6MVZOuqLseOI5JGRwA6H8RRdgTV4U,5191
57
+ pytcl/dynamic_estimation/gaussian_sum_filter.py,sha256=z9DiKtafQriDXnmkXhT4QHmpEArzTZ6psiFi5tU5DGM,13654
51
58
  pytcl/dynamic_estimation/imm.py,sha256=IbKmouUiyzaYJbhWty63r3n_xV8thD-wd0qgZP1SxOI,22067
52
59
  pytcl/dynamic_estimation/information_filter.py,sha256=x7iQwO_iJT1dCSvDws5LqD3yAtjw9QVGUfMPcXn1IA4,17349
60
+ pytcl/dynamic_estimation/rbpf.py,sha256=jerIkfIvOLWtlFnHyS5KxI5X4RpAVTdWENaIIXg3WTU,17595
53
61
  pytcl/dynamic_estimation/smoothers.py,sha256=x2j-nR--EI5JNZvMywPeDHcrfW8b5PYK0DCU4Rmig_g,18914
54
62
  pytcl/dynamic_estimation/batch_estimation/__init__.py,sha256=JQ0s76Enov5a7plA4EnUua4t-7etikQrwr5z4WIjUeo,46
55
- pytcl/dynamic_estimation/kalman/__init__.py,sha256=yoFLj0n-NRkdZnRVL-BkHBlATk8pfZEVlsY3BhSYgKc,2387
63
+ pytcl/dynamic_estimation/kalman/__init__.py,sha256=rmMP6gLgfFdge5S6LSLhFZe2MeAk9FFtDQrQdzHjvtM,3163
64
+ pytcl/dynamic_estimation/kalman/constrained.py,sha256=cZpqMrCkp6fB3al16_zw7kv4P6Th6a9mUin1322oYMk,10652
56
65
  pytcl/dynamic_estimation/kalman/extended.py,sha256=51uhCqkZmErCx6MBfMq8eIQW8bD7n34zCe4v4dxNiMQ,10384
66
+ pytcl/dynamic_estimation/kalman/h_infinity.py,sha256=RRqv-kMkDeyeke_gHs_XDmUid97JNC4y3SxaO5q6ctA,16512
57
67
  pytcl/dynamic_estimation/kalman/linear.py,sha256=1Zgg9gZya0Vxs9im7sPUqLj0Luo463vS-RSa6GCReFI,12248
58
68
  pytcl/dynamic_estimation/kalman/square_root.py,sha256=N7-lDml7Nw5HM5b5D11WOwG7rY1JlVoyis0ho-vk0H4,13345
59
69
  pytcl/dynamic_estimation/kalman/sr_ukf.py,sha256=LeRGBSDpvSP9CyTZjEroz2Z2uueb6YpmzYricba0PDk,8640
@@ -148,8 +158,8 @@ pytcl/trackers/mht.py,sha256=7mwhMmja3ri2wnx7W1wueDGn2r3ArwAxJDPUJ7IZAkQ,20617
148
158
  pytcl/trackers/multi_target.py,sha256=hvt89ERhMwpcHcIJeKHnkQSKdE3_LoRiX-gbaGoo300,10516
149
159
  pytcl/trackers/single_target.py,sha256=Yy3FwaNTArMWcaod-0HVeiioNV4xLWxNDn_7ZPVqQYs,6562
150
160
  pytcl/transponders/__init__.py,sha256=5fL4u3lKCYgPLo5uFeuZbtRZkJPABntuKYGUvVgMMEI,41
151
- nrl_tracker-1.5.0.dist-info/LICENSE,sha256=rB5G4WppIIUzMOYr2N6uyYlNJ00hRJqE5tie6BMvYuE,1612
152
- nrl_tracker-1.5.0.dist-info/METADATA,sha256=fB1_KydehvDdL2UE8J4hyTuDcodKGN7CLHyoSUqgdV4,10145
153
- nrl_tracker-1.5.0.dist-info/WHEEL,sha256=pL8R0wFFS65tNSRnaOVrsw9EOkOqxLrlUPenUYnJKNo,91
154
- nrl_tracker-1.5.0.dist-info/top_level.txt,sha256=17megxcrTPBWwPZTh6jTkwTKxX7No-ZqRpyvElnnO-s,6
155
- nrl_tracker-1.5.0.dist-info/RECORD,,
161
+ nrl_tracker-1.7.0.dist-info/LICENSE,sha256=rB5G4WppIIUzMOYr2N6uyYlNJ00hRJqE5tie6BMvYuE,1612
162
+ nrl_tracker-1.7.0.dist-info/METADATA,sha256=Tifq_bsT8RjJE-_Ty5DDFPUomTamE68K7v6uIDs28iA,10664
163
+ nrl_tracker-1.7.0.dist-info/WHEEL,sha256=pL8R0wFFS65tNSRnaOVrsw9EOkOqxLrlUPenUYnJKNo,91
164
+ nrl_tracker-1.7.0.dist-info/top_level.txt,sha256=17megxcrTPBWwPZTh6jTkwTKxX7No-ZqRpyvElnnO-s,6
165
+ nrl_tracker-1.7.0.dist-info/RECORD,,
pytcl/__init__.py CHANGED
@@ -20,7 +20,7 @@ References
20
20
  no. 5, pp. 18-27, May 2017.
21
21
  """
22
22
 
23
- __version__ = "1.5.0"
23
+ __version__ = "1.6.0"
24
24
  __author__ = "Python Port Contributors"
25
25
  __original_author__ = "David F. Crouse, Naval Research Laboratory"
26
26
 
@@ -51,6 +51,21 @@ from pytcl.assignment_algorithms.two_dimensional import (
51
51
  murty,
52
52
  ranked_assignments,
53
53
  )
54
+ from pytcl.assignment_algorithms.nd_assignment import (
55
+ AssignmentNDResult,
56
+ auction_assignment_nd,
57
+ detect_dimension_conflicts,
58
+ greedy_assignment_nd,
59
+ relaxation_assignment_nd,
60
+ validate_cost_tensor,
61
+ )
62
+ from pytcl.assignment_algorithms.network_flow import (
63
+ FlowStatus,
64
+ MinCostFlowResult,
65
+ assignment_to_flow_network,
66
+ min_cost_assignment_via_flow,
67
+ min_cost_flow_successive_shortest_paths,
68
+ )
54
69
 
55
70
  __all__ = [
56
71
  # 2D Assignment
@@ -91,4 +106,17 @@ __all__ = [
91
106
  "jpda_update",
92
107
  "jpda_probabilities",
93
108
  "compute_likelihood_matrix",
109
+ # N-Dimensional Assignment (4D+)
110
+ "AssignmentNDResult",
111
+ "validate_cost_tensor",
112
+ "greedy_assignment_nd",
113
+ "relaxation_assignment_nd",
114
+ "auction_assignment_nd",
115
+ "detect_dimension_conflicts",
116
+ # Network Flow-Based Assignment
117
+ "FlowStatus",
118
+ "MinCostFlowResult",
119
+ "assignment_to_flow_network",
120
+ "min_cost_flow_successive_shortest_paths",
121
+ "min_cost_assignment_via_flow",
94
122
  ]
@@ -0,0 +1,378 @@
1
+ """
2
+ N-dimensional assignment algorithms (4D and higher).
3
+
4
+ This module extends the 3D assignment solver to arbitrary dimensions,
5
+ enabling more complex assignment scenarios such as:
6
+ - 4D: Measurements × Tracks × Hypotheses × Sensors
7
+ - 5D+: Additional dimensions for time frames, maneuver classes, etc.
8
+
9
+ The module provides a unified interface for solving high-dimensional
10
+ assignment problems using generalized relaxation methods.
11
+
12
+ References
13
+ ----------
14
+ .. [1] Poore, A. B., "Multidimensional Assignment Problem and Data
15
+ Association," IEEE Transactions on Aerospace and Electronic Systems,
16
+ 2013.
17
+ .. [2] Cramer, R. D., et al., "The Emerging Role of Chemical Similarity in
18
+ Drug Discovery," Perspectives in Drug Discovery and Design, 2003.
19
+ """
20
+
21
+ from typing import NamedTuple, Optional, Tuple
22
+
23
+ import numpy as np
24
+ from numpy.typing import NDArray
25
+
26
+
27
+ class AssignmentNDResult(NamedTuple):
28
+ """Result of an N-dimensional assignment problem.
29
+
30
+ Attributes
31
+ ----------
32
+ assignments : ndarray
33
+ Array of shape (n_assignments, n_dimensions) containing assigned
34
+ index tuples. Each row is an n-tuple of indices.
35
+ cost : float
36
+ Total assignment cost.
37
+ converged : bool
38
+ Whether the algorithm converged (for iterative methods).
39
+ n_iterations : int
40
+ Number of iterations used (for iterative methods).
41
+ gap : float
42
+ Optimality gap (upper_bound - lower_bound) for relaxation methods.
43
+ """
44
+
45
+ assignments: NDArray[np.intp]
46
+ cost: float
47
+ converged: bool
48
+ n_iterations: int
49
+ gap: float
50
+
51
+
52
+ def validate_cost_tensor(cost_tensor: NDArray[np.float64]) -> Tuple[int, ...]:
53
+ """
54
+ Validate cost tensor and return dimensions.
55
+
56
+ Parameters
57
+ ----------
58
+ cost_tensor : ndarray
59
+ Cost tensor of arbitrary dimension.
60
+
61
+ Returns
62
+ -------
63
+ dims : tuple
64
+ Dimensions of the cost tensor.
65
+
66
+ Raises
67
+ ------
68
+ ValueError
69
+ If tensor has fewer than 2 dimensions.
70
+ """
71
+ if cost_tensor.ndim < 2:
72
+ raise ValueError(
73
+ f"Cost tensor must have at least 2 dimensions, got {cost_tensor.ndim}"
74
+ )
75
+
76
+ return cost_tensor.shape
77
+
78
+
79
+ def greedy_assignment_nd(
80
+ cost_tensor: NDArray[np.float64],
81
+ max_assignments: Optional[int] = None,
82
+ ) -> AssignmentNDResult:
83
+ """
84
+ Greedy solver for N-dimensional assignment.
85
+
86
+ Selects minimum-cost tuples in order until no more valid assignments
87
+ exist (no dimension index is repeated).
88
+
89
+ Parameters
90
+ ----------
91
+ cost_tensor : ndarray
92
+ Cost tensor of shape (n1, n2, ..., nk).
93
+ max_assignments : int, optional
94
+ Maximum number of assignments to find (default: min(dimensions)).
95
+
96
+ Returns
97
+ -------
98
+ AssignmentNDResult
99
+ Assignments, total cost, and algorithm info.
100
+
101
+ Notes
102
+ -----
103
+ Greedy assignment is fast O(n log n) but not optimal. Used as
104
+ heuristic or starting solution for optimization methods.
105
+ """
106
+ dims = cost_tensor.shape
107
+ n_dims = len(dims)
108
+
109
+ if max_assignments is None:
110
+ max_assignments = min(dims)
111
+
112
+ # Flatten tensor with index mapping
113
+ flat_costs = cost_tensor.ravel()
114
+ sorted_indices = np.argsort(flat_costs)
115
+
116
+ assignments: list[tuple[int, ...]] = []
117
+ used_indices: list[set[int]] = [set() for _ in range(n_dims)]
118
+
119
+ for flat_idx in sorted_indices:
120
+ if len(assignments) >= max_assignments:
121
+ break
122
+
123
+ # Convert flat index to multi-dimensional index
124
+ multi_idx = np.unravel_index(flat_idx, dims)
125
+
126
+ # Check if any dimension index is already used
127
+ conflict = False
128
+ for d, idx in enumerate(multi_idx):
129
+ if idx in used_indices[d]:
130
+ conflict = True
131
+ break
132
+
133
+ if not conflict:
134
+ assignments.append(multi_idx)
135
+ for d, idx in enumerate(multi_idx):
136
+ used_indices[d].add(idx)
137
+
138
+ assignments_array = np.array(assignments, dtype=np.intp)
139
+ if assignments_array.size > 0:
140
+ total_cost = float(np.sum(cost_tensor[tuple(assignments_array.T)]))
141
+ else:
142
+ total_cost = 0.0
143
+
144
+ return AssignmentNDResult(
145
+ assignments=assignments_array,
146
+ cost=total_cost,
147
+ converged=True,
148
+ n_iterations=1,
149
+ gap=0.0, # Greedy doesn't compute lower bound
150
+ )
151
+
152
+
153
+ def relaxation_assignment_nd(
154
+ cost_tensor: NDArray[np.float64],
155
+ max_iterations: int = 100,
156
+ tolerance: float = 1e-6,
157
+ verbose: bool = False,
158
+ ) -> AssignmentNDResult:
159
+ """
160
+ Lagrangian relaxation solver for N-dimensional assignment.
161
+
162
+ Uses iterative subgradient optimization on Lagrange multipliers
163
+ to tighten the lower bound and find good solutions.
164
+
165
+ Parameters
166
+ ----------
167
+ cost_tensor : ndarray
168
+ Cost tensor of shape (n1, n2, ..., nk).
169
+ max_iterations : int, optional
170
+ Maximum iterations (default 100).
171
+ tolerance : float, optional
172
+ Convergence tolerance for gap (default 1e-6).
173
+ verbose : bool, optional
174
+ Print iteration info (default False).
175
+
176
+ Returns
177
+ -------
178
+ AssignmentNDResult
179
+ Assignments, total cost, convergence info, and optimality gap.
180
+
181
+ Notes
182
+ -----
183
+ The relaxation approach:
184
+ 1. Maintain Lagrange multipliers for each dimension
185
+ 2. Solve relaxed problem (select best entries per tuple)
186
+ 3. Update multipliers based on constraint violations
187
+ 4. Iterate until convergence or gap tolerance met
188
+
189
+ This guarantees a lower bound on optimal cost and often finds
190
+ near-optimal or optimal solutions.
191
+ """
192
+ dims = cost_tensor.shape
193
+ n_dims = len(dims)
194
+
195
+ # Initialize Lagrange multipliers (one per dimension per index)
196
+ lambdas = [np.zeros(dim) for dim in dims]
197
+
198
+ best_cost = np.inf
199
+ best_assignments = None
200
+ lower_bound = -np.inf
201
+
202
+ for iteration in range(max_iterations):
203
+ # Compute relaxed costs: original - Lagrange penalty
204
+ relaxed_cost = cost_tensor.copy()
205
+ for d in range(n_dims):
206
+ # Reshape lambda[d] to broadcast correctly
207
+ shape = [1] * n_dims
208
+ shape[d] = dims[d]
209
+ relaxed_cost = relaxed_cost - lambdas[d].reshape(shape)
210
+
211
+ # Solve relaxed problem: greedy on relaxed costs
212
+ result_relaxed = greedy_assignment_nd(relaxed_cost)
213
+
214
+ # Compute lower bound from relaxed solution
215
+ lower_bound = (
216
+ result_relaxed.cost
217
+ + sum(np.sum(lambdas[d]) for d in range(n_dims))
218
+ )
219
+
220
+ # Extract solution from relaxed problem
221
+ if len(result_relaxed.assignments) > 0:
222
+ actual_cost = float(np.sum(cost_tensor[tuple(result_relaxed.assignments.T)]))
223
+
224
+ if actual_cost < best_cost:
225
+ best_cost = actual_cost
226
+ best_assignments = result_relaxed.assignments
227
+
228
+ # Compute constraint violations and update multipliers
229
+ violations = [np.zeros(dim) for dim in dims]
230
+
231
+ for assignment in result_relaxed.assignments:
232
+ for d, idx in enumerate(assignment):
233
+ violations[d][idx] += 1
234
+
235
+ # Subgradient descent on multipliers
236
+ step_size = 1.0 / (iteration + 1)
237
+ for d in range(n_dims):
238
+ lambdas[d] -= step_size * (violations[d] - 1.0)
239
+
240
+ # Compute gap
241
+ gap = best_cost - lower_bound if best_cost != np.inf else np.inf
242
+
243
+ if verbose:
244
+ print(
245
+ f"Iter {iteration+1}: LB={lower_bound:.4f}, UB={best_cost:.4f}, "
246
+ f"Gap={gap:.6f}"
247
+ )
248
+
249
+ if gap < tolerance:
250
+ if verbose:
251
+ print(f"Converged at iteration {iteration+1}")
252
+ break
253
+
254
+ if best_assignments is None:
255
+ best_assignments = np.empty((0, n_dims), dtype=np.intp)
256
+ best_cost = 0.0
257
+
258
+ gap = best_cost - lower_bound if best_cost != np.inf else np.inf
259
+
260
+ return AssignmentNDResult(
261
+ assignments=best_assignments,
262
+ cost=best_cost,
263
+ converged=gap < tolerance,
264
+ n_iterations=iteration + 1,
265
+ gap=gap,
266
+ )
267
+
268
+
269
+ def auction_assignment_nd(
270
+ cost_tensor: NDArray[np.float64],
271
+ max_iterations: int = 100,
272
+ epsilon: float = 0.01,
273
+ verbose: bool = False,
274
+ ) -> AssignmentNDResult:
275
+ """
276
+ Auction algorithm for N-dimensional assignment.
277
+
278
+ Inspired by the classical auction algorithm for 2D assignment,
279
+ adapted to higher dimensions. Objects bid for assignments based
280
+ on relative costs.
281
+
282
+ Parameters
283
+ ----------
284
+ cost_tensor : ndarray
285
+ Cost tensor of shape (n1, n2, ..., nk).
286
+ max_iterations : int, optional
287
+ Maximum iterations (default 100).
288
+ epsilon : float, optional
289
+ Bid increment (default 0.01). Larger epsilon → fewer iterations,
290
+ worse solution; smaller epsilon → more iterations, better solution.
291
+ verbose : bool, optional
292
+ Print iteration info (default False).
293
+
294
+ Returns
295
+ -------
296
+ AssignmentNDResult
297
+ Assignments, total cost, convergence info, gap estimate.
298
+
299
+ Notes
300
+ -----
301
+ The algorithm maintains a "price" for each index and allows bidding
302
+ (price adjustment) to maximize value. Converges to epsilon-optimal
303
+ solution in finite iterations.
304
+ """
305
+ dims = cost_tensor.shape
306
+ n_dims = len(dims)
307
+
308
+ # Initialize prices (one per dimension per index)
309
+ prices = [np.zeros(dim) for dim in dims]
310
+
311
+ for iteration in range(max_iterations):
312
+ # Compute profit: cost - price penalty
313
+ profit = cost_tensor.copy()
314
+ for d in range(n_dims):
315
+ shape = [1] * n_dims
316
+ shape[d] = dims[d]
317
+ profit = profit - prices[d].reshape(shape)
318
+
319
+ # Find best assignment at current prices (greedy)
320
+ result = greedy_assignment_nd(profit)
321
+
322
+ if len(result.assignments) == 0:
323
+ break
324
+
325
+ # Update prices: increase price for "in-demand" indices
326
+ demands = [np.zeros(dim) for dim in dims]
327
+ for assignment in result.assignments:
328
+ for d, idx in enumerate(assignment):
329
+ demands[d][idx] += 1
330
+
331
+ for d in range(n_dims):
332
+ prices[d] += epsilon * (demands[d] - 1.0)
333
+
334
+ if verbose and (iteration + 1) % 10 == 0:
335
+ actual_cost = float(np.sum(cost_tensor[tuple(result.assignments.T)]))
336
+ print(f"Iter {iteration+1}: Cost={actual_cost:.4f}")
337
+
338
+ # Final solution
339
+ result = greedy_assignment_nd(cost_tensor)
340
+
341
+ return AssignmentNDResult(
342
+ assignments=result.assignments,
343
+ cost=result.cost,
344
+ converged=True,
345
+ n_iterations=iteration + 1,
346
+ gap=0.0, # Auction algorithm doesn't track gap formally
347
+ )
348
+
349
+
350
+ def detect_dimension_conflicts(
351
+ assignments: NDArray[np.intp],
352
+ dims: Tuple[int, ...],
353
+ ) -> bool:
354
+ """
355
+ Check if assignments violate dimension uniqueness.
356
+
357
+ For valid assignment, each index should appear at most once per dimension.
358
+
359
+ Parameters
360
+ ----------
361
+ assignments : ndarray
362
+ Array of shape (n_assignments, n_dimensions) with assignments.
363
+ dims : tuple
364
+ Dimensions of the cost tensor.
365
+
366
+ Returns
367
+ -------
368
+ has_conflicts : bool
369
+ True if any index appears more than once in any dimension.
370
+ """
371
+ n_dims = len(dims)
372
+
373
+ for d in range(n_dims):
374
+ indices_in_dim = assignments[:, d]
375
+ if len(indices_in_dim) != len(np.unique(indices_in_dim)):
376
+ return True
377
+
378
+ return False