opforch 2.0.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.
Files changed (37) hide show
  1. opforch-2.0.0/LICENSE +177 -0
  2. opforch-2.0.0/PKG-INFO +229 -0
  3. opforch-2.0.0/README.md +189 -0
  4. opforch-2.0.0/opforch/__init__.py +7 -0
  5. opforch-2.0.0/opforch/core/__init__.py +5 -0
  6. opforch-2.0.0/opforch/core/heap.py +200 -0
  7. opforch-2.0.0/opforch/core/opf.py +213 -0
  8. opforch-2.0.0/opforch/core/subgraph.py +238 -0
  9. opforch-2.0.0/opforch/math/__init__.py +1 -0
  10. opforch-2.0.0/opforch/math/distance.py +501 -0
  11. opforch-2.0.0/opforch/math/general.py +179 -0
  12. opforch-2.0.0/opforch/math/random.py +49 -0
  13. opforch-2.0.0/opforch/models/__init__.py +6 -0
  14. opforch-2.0.0/opforch/models/knn_supervised.py +278 -0
  15. opforch-2.0.0/opforch/models/semi_supervised.py +157 -0
  16. opforch-2.0.0/opforch/models/supervised.py +403 -0
  17. opforch-2.0.0/opforch/models/unsupervised.py +336 -0
  18. opforch-2.0.0/opforch/stream/__init__.py +3 -0
  19. opforch-2.0.0/opforch/stream/loader.py +107 -0
  20. opforch-2.0.0/opforch/stream/parser.py +53 -0
  21. opforch-2.0.0/opforch/stream/splitter.py +128 -0
  22. opforch-2.0.0/opforch/subgraphs/__init__.py +3 -0
  23. opforch-2.0.0/opforch/subgraphs/knn.py +280 -0
  24. opforch-2.0.0/opforch/utils/__init__.py +1 -0
  25. opforch-2.0.0/opforch/utils/constants.py +31 -0
  26. opforch-2.0.0/opforch/utils/converter.py +130 -0
  27. opforch-2.0.0/opforch/utils/device.py +90 -0
  28. opforch-2.0.0/opforch/utils/exception.py +61 -0
  29. opforch-2.0.0/opforch/utils/logging.py +65 -0
  30. opforch-2.0.0/opforch.egg-info/PKG-INFO +229 -0
  31. opforch-2.0.0/opforch.egg-info/SOURCES.txt +36 -0
  32. opforch-2.0.0/opforch.egg-info/dependency_links.txt +1 -0
  33. opforch-2.0.0/opforch.egg-info/requires.txt +7 -0
  34. opforch-2.0.0/opforch.egg-info/top_level.txt +1 -0
  35. opforch-2.0.0/pyproject.toml +2 -0
  36. opforch-2.0.0/setup.cfg +14 -0
  37. opforch-2.0.0/setup.py +42 -0
opforch-2.0.0/LICENSE ADDED
@@ -0,0 +1,177 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ https://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
opforch-2.0.0/PKG-INFO ADDED
@@ -0,0 +1,229 @@
1
+ Metadata-Version: 2.4
2
+ Name: opforch
3
+ Version: 2.0.0
4
+ Summary: PyTorch-Inspired Optimum-Path Forest Classifier
5
+ Home-page: https://github.com/gugarosa/opforch
6
+ Author: Gustavo de Rosa
7
+ Author-email: gustavo.rosa@unesp.br
8
+ License: Apache 2.0
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Intended Audience :: Education
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3.8
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Software Development :: Libraries
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: numpy>=1.19.5
24
+ Requires-Dist: torch>=2.0.0
25
+ Provides-Extra: tests
26
+ Requires-Dist: coverage; extra == "tests"
27
+ Requires-Dist: pytest; extra == "tests"
28
+ Requires-Dist: pytest-pep8; extra == "tests"
29
+ Dynamic: author
30
+ Dynamic: author-email
31
+ Dynamic: classifier
32
+ Dynamic: description
33
+ Dynamic: description-content-type
34
+ Dynamic: home-page
35
+ Dynamic: license
36
+ Dynamic: license-file
37
+ Dynamic: provides-extra
38
+ Dynamic: requires-dist
39
+ Dynamic: summary
40
+
41
+ # OPForch: A PyTorch-Powered Optimum-Path Forest Classifier
42
+
43
+ [![Latest release](https://img.shields.io/github/release/gugarosa/opforch.svg)](https://github.com/gugarosa/opforch/releases)
44
+ [![Open issues](https://img.shields.io/github/issues/gugarosa/opforch.svg)](https://github.com/gugarosa/opforch/issues)
45
+ [![License](https://img.shields.io/github/license/gugarosa/opforch.svg)](https://github.com/gugarosa/opforch/blob/master/LICENSE)
46
+
47
+ ## Welcome to OPForch.
48
+
49
+ *Note that this implementation relies purely on the standard [LibOPF](https://github.com/jppbsi/LibOPF). Therefore, if one uses our package, please also cite the original LibOPF [authors](https://github.com/jppbsi/LibOPF/wiki/Additional-information).*
50
+
51
+ OPForch is a **PyTorch-based** implementation of the Optimum-Path Forest (OPF) classifier, migrated from the original [OPFython](https://github.com/gugarosa/opfython) package. By replacing per-node Python objects with dense tensors and scalar Numba loops with batched tensor operations, OPForch delivers **massive speedups** while maintaining **zero prediction mismatches** against the reference implementation.
52
+
53
+ ### Key Highlights
54
+
55
+ | Metric | Result |
56
+ |--------|--------|
57
+ | **Accuracy Parity** | 0 prediction mismatches across all 4 classifiers |
58
+ | **Predict Speedup** | Up to **484×** faster at N=10,000 |
59
+ | **Fit Speedup** | Up to **19×** faster at N=10,000 |
60
+ | **Distance Matrix** | Up to **413×** faster (batched tensor vs N² scalar loop) |
61
+ | **GPU Acceleration** | **12.7×** additional speedup on RTX 4070 for distance computation |
62
+ | **Device Support** | CPU, CUDA, and Multi-GPU via `DeviceManager` |
63
+
64
+ ### Use OPForch if you need:
65
+
66
+ * Graph-based classification without hyperparameter tuning
67
+ * Deterministic training with competitive accuracy
68
+ * GPU-accelerated distance computation and prediction
69
+ * A drop-in replacement for OPFython with orders-of-magnitude speedups
70
+
71
+ OPForch is compatible with: **Python 3.8+** and **PyTorch 2.0+**.
72
+
73
+ ---
74
+
75
+ ## Package Structure
76
+
77
+ ```
78
+ opforch/
79
+ ├── core/
80
+ │ ├── heap.py # Tensor-backed binary heap
81
+ │ ├── subgraph.py # Dense tensor columns (13 state tensors)
82
+ │ └── opf.py # Abstract base (torch.save/load, device)
83
+ ├── math/
84
+ │ ├── distance.py # 47 batched (N,D)×(M,D)→(N,M) distance metrics
85
+ │ ├── general.py # Accuracy, confusion matrix, normalize, purity
86
+ │ └── random.py # Tensor-based random generators
87
+ ├── models/
88
+ │ ├── supervised.py # MST + competition + batched predict
89
+ │ ├── knn_supervised.py # KNN density clustering + k-selection
90
+ │ ├── semi_supervised.py # Labeled + unlabeled propagation
91
+ │ └── unsupervised.py # Density clustering + normalized cut
92
+ ├── stream/
93
+ │ ├── loader.py # CSV/TXT/JSON → torch.Tensor
94
+ │ ├── parser.py # Extract features + labels
95
+ │ └── splitter.py # Train/test split
96
+ ├── subgraphs/
97
+ │ └── knn.py # KNNSubgraph (torch.topk, vectorized PDF)
98
+ ├── utils/
99
+ │ ├── constants.py # EPSILON, FLOAT_MAX, status codes
100
+ │ ├── converter.py # Binary OPF format converters
101
+ │ ├── device.py # DeviceManager (CPU/GPU/multi-GPU)
102
+ │ ├── exception.py # Custom exception hierarchy
103
+ │ └── logging.py # Timed rotating file logger
104
+ ├── report/ # Migration report, benchmarks, and plots
105
+ ├── examples/ # Usage scripts for all 4 classifiers
106
+ ```
107
+
108
+ ---
109
+
110
+ ## Installation
111
+
112
+ Install from source:
113
+
114
+ ```bash
115
+ git clone https://github.com/gugarosa/opforch.git
116
+ cd opforch
117
+ pip install -e .
118
+ ```
119
+
120
+ For GPU support, install PyTorch with CUDA:
121
+
122
+ ```bash
123
+ pip install torch --index-url https://download.pytorch.org/whl/cu124
124
+ ```
125
+
126
+ ---
127
+
128
+ ## Quick Start
129
+
130
+ ### Supervised Classification
131
+
132
+ ```python
133
+ import torch
134
+ from opforch.models import SupervisedOPF
135
+ from opforch.stream import loader, parser, splitter
136
+
137
+ # Load data
138
+ data = loader.load_txt("data/boat.txt")
139
+ X, Y = parser.parse_loader(data)
140
+ X_train, X_test, Y_train, Y_test = splitter.split(X, Y, percentage=0.5)
141
+
142
+ # Train and predict (CPU)
143
+ opf = SupervisedOPF(distance="log_squared_euclidean")
144
+ opf.fit(X_train, Y_train)
145
+ predictions = opf.predict(X_test)
146
+
147
+ # GPU — just change the device
148
+ opf_gpu = SupervisedOPF(distance="euclidean", device="cuda:0")
149
+ opf_gpu.fit(X_train.cuda(), Y_train.cuda())
150
+ predictions = opf_gpu.predict(X_test.cuda())
151
+ ```
152
+
153
+ ### Available Classifiers
154
+
155
+ | Classifier | Description |
156
+ |-----------|-------------|
157
+ | `SupervisedOPF` | MST-based prototype detection + cost competition |
158
+ | `KNNSupervisedOPF` | k-NN density clustering with validation-driven k |
159
+ | `SemiSupervisedOPF` | Extends supervised with unlabeled data propagation |
160
+ | `UnsupervisedOPF` | Density-based clustering with normalized cut |
161
+
162
+ All classifiers support `fit()`, `predict()`, `save()`, and `load()`, and accept a `device` parameter for CPU/GPU execution.
163
+
164
+ ---
165
+
166
+ ## Benchmarks
167
+
168
+ Run the benchmark suite to compare performance on your hardware:
169
+
170
+ ```bash
171
+ # Baseline benchmarks (47 metrics, 4 models, scaling)
172
+ python report/benchmark.py
173
+
174
+ # Extended benchmarks (up to N=10K, GPU, dimensionality)
175
+ python report/benchmark_extended.py
176
+
177
+ # Generate plots
178
+ python report/plot_benchmarks.py
179
+ python report/plot_extended.py
180
+ ```
181
+
182
+ For the full migration report with detailed analysis, see [`report/REPORT.md`](report/REPORT.md).
183
+
184
+ ---
185
+
186
+ ## Architecture
187
+
188
+ The key architectural change from OPFython is the elimination of per-node Python objects in favor of dense tensor columns:
189
+
190
+ ```
191
+ OPFython: subgraph.nodes[i].cost = 5.0 # Python object attribute
192
+ OPForch: subgraph.costs[i] = 5.0 # Tensor element (GPU-ready)
193
+ ```
194
+
195
+ Prediction is fully batched — a single tensor operation replaces the O(N×M) Python loop:
196
+
197
+ ```python
198
+ dist_matrix = distance_fn(train_features, test_features) # (N, M)
199
+ path_costs = torch.maximum(train_costs[:, None], dist_matrix) # (N, M)
200
+ predictions = train_labels[path_costs.argmin(dim=0)] # (M,)
201
+ ```
202
+
203
+ For the complete architecture documentation, see [`ARCHITECTURE.md`](ARCHITECTURE.md).
204
+
205
+ ---
206
+
207
+ ## Citation
208
+
209
+ If you use OPForch to fulfill any of your needs, please cite us:
210
+
211
+ ```
212
+ J. P. Papa, A. X. Falcão and C. T. N. Suzuki.
213
+ Supervised Pattern Classification based on Optimum-Path Forest.
214
+ International Journal of Imaging Systems and Technology (2009).
215
+ ```
216
+
217
+ ---
218
+
219
+ ## Datasets
220
+
221
+ Looking for datasets? We have some pre-loaded into OPF file format in the `data/` directory. More are available at [recogna.tech](http://recogna.tech).
222
+
223
+ ---
224
+
225
+ ## Support
226
+
227
+ If you ever need to report a bug, talk to us, or suggest improvements, please open an issue. We will do our best to help.
228
+
229
+ ---
@@ -0,0 +1,189 @@
1
+ # OPForch: A PyTorch-Powered Optimum-Path Forest Classifier
2
+
3
+ [![Latest release](https://img.shields.io/github/release/gugarosa/opforch.svg)](https://github.com/gugarosa/opforch/releases)
4
+ [![Open issues](https://img.shields.io/github/issues/gugarosa/opforch.svg)](https://github.com/gugarosa/opforch/issues)
5
+ [![License](https://img.shields.io/github/license/gugarosa/opforch.svg)](https://github.com/gugarosa/opforch/blob/master/LICENSE)
6
+
7
+ ## Welcome to OPForch.
8
+
9
+ *Note that this implementation relies purely on the standard [LibOPF](https://github.com/jppbsi/LibOPF). Therefore, if one uses our package, please also cite the original LibOPF [authors](https://github.com/jppbsi/LibOPF/wiki/Additional-information).*
10
+
11
+ OPForch is a **PyTorch-based** implementation of the Optimum-Path Forest (OPF) classifier, migrated from the original [OPFython](https://github.com/gugarosa/opfython) package. By replacing per-node Python objects with dense tensors and scalar Numba loops with batched tensor operations, OPForch delivers **massive speedups** while maintaining **zero prediction mismatches** against the reference implementation.
12
+
13
+ ### Key Highlights
14
+
15
+ | Metric | Result |
16
+ |--------|--------|
17
+ | **Accuracy Parity** | 0 prediction mismatches across all 4 classifiers |
18
+ | **Predict Speedup** | Up to **484×** faster at N=10,000 |
19
+ | **Fit Speedup** | Up to **19×** faster at N=10,000 |
20
+ | **Distance Matrix** | Up to **413×** faster (batched tensor vs N² scalar loop) |
21
+ | **GPU Acceleration** | **12.7×** additional speedup on RTX 4070 for distance computation |
22
+ | **Device Support** | CPU, CUDA, and Multi-GPU via `DeviceManager` |
23
+
24
+ ### Use OPForch if you need:
25
+
26
+ * Graph-based classification without hyperparameter tuning
27
+ * Deterministic training with competitive accuracy
28
+ * GPU-accelerated distance computation and prediction
29
+ * A drop-in replacement for OPFython with orders-of-magnitude speedups
30
+
31
+ OPForch is compatible with: **Python 3.8+** and **PyTorch 2.0+**.
32
+
33
+ ---
34
+
35
+ ## Package Structure
36
+
37
+ ```
38
+ opforch/
39
+ ├── core/
40
+ │ ├── heap.py # Tensor-backed binary heap
41
+ │ ├── subgraph.py # Dense tensor columns (13 state tensors)
42
+ │ └── opf.py # Abstract base (torch.save/load, device)
43
+ ├── math/
44
+ │ ├── distance.py # 47 batched (N,D)×(M,D)→(N,M) distance metrics
45
+ │ ├── general.py # Accuracy, confusion matrix, normalize, purity
46
+ │ └── random.py # Tensor-based random generators
47
+ ├── models/
48
+ │ ├── supervised.py # MST + competition + batched predict
49
+ │ ├── knn_supervised.py # KNN density clustering + k-selection
50
+ │ ├── semi_supervised.py # Labeled + unlabeled propagation
51
+ │ └── unsupervised.py # Density clustering + normalized cut
52
+ ├── stream/
53
+ │ ├── loader.py # CSV/TXT/JSON → torch.Tensor
54
+ │ ├── parser.py # Extract features + labels
55
+ │ └── splitter.py # Train/test split
56
+ ├── subgraphs/
57
+ │ └── knn.py # KNNSubgraph (torch.topk, vectorized PDF)
58
+ ├── utils/
59
+ │ ├── constants.py # EPSILON, FLOAT_MAX, status codes
60
+ │ ├── converter.py # Binary OPF format converters
61
+ │ ├── device.py # DeviceManager (CPU/GPU/multi-GPU)
62
+ │ ├── exception.py # Custom exception hierarchy
63
+ │ └── logging.py # Timed rotating file logger
64
+ ├── report/ # Migration report, benchmarks, and plots
65
+ ├── examples/ # Usage scripts for all 4 classifiers
66
+ ```
67
+
68
+ ---
69
+
70
+ ## Installation
71
+
72
+ Install from source:
73
+
74
+ ```bash
75
+ git clone https://github.com/gugarosa/opforch.git
76
+ cd opforch
77
+ pip install -e .
78
+ ```
79
+
80
+ For GPU support, install PyTorch with CUDA:
81
+
82
+ ```bash
83
+ pip install torch --index-url https://download.pytorch.org/whl/cu124
84
+ ```
85
+
86
+ ---
87
+
88
+ ## Quick Start
89
+
90
+ ### Supervised Classification
91
+
92
+ ```python
93
+ import torch
94
+ from opforch.models import SupervisedOPF
95
+ from opforch.stream import loader, parser, splitter
96
+
97
+ # Load data
98
+ data = loader.load_txt("data/boat.txt")
99
+ X, Y = parser.parse_loader(data)
100
+ X_train, X_test, Y_train, Y_test = splitter.split(X, Y, percentage=0.5)
101
+
102
+ # Train and predict (CPU)
103
+ opf = SupervisedOPF(distance="log_squared_euclidean")
104
+ opf.fit(X_train, Y_train)
105
+ predictions = opf.predict(X_test)
106
+
107
+ # GPU — just change the device
108
+ opf_gpu = SupervisedOPF(distance="euclidean", device="cuda:0")
109
+ opf_gpu.fit(X_train.cuda(), Y_train.cuda())
110
+ predictions = opf_gpu.predict(X_test.cuda())
111
+ ```
112
+
113
+ ### Available Classifiers
114
+
115
+ | Classifier | Description |
116
+ |-----------|-------------|
117
+ | `SupervisedOPF` | MST-based prototype detection + cost competition |
118
+ | `KNNSupervisedOPF` | k-NN density clustering with validation-driven k |
119
+ | `SemiSupervisedOPF` | Extends supervised with unlabeled data propagation |
120
+ | `UnsupervisedOPF` | Density-based clustering with normalized cut |
121
+
122
+ All classifiers support `fit()`, `predict()`, `save()`, and `load()`, and accept a `device` parameter for CPU/GPU execution.
123
+
124
+ ---
125
+
126
+ ## Benchmarks
127
+
128
+ Run the benchmark suite to compare performance on your hardware:
129
+
130
+ ```bash
131
+ # Baseline benchmarks (47 metrics, 4 models, scaling)
132
+ python report/benchmark.py
133
+
134
+ # Extended benchmarks (up to N=10K, GPU, dimensionality)
135
+ python report/benchmark_extended.py
136
+
137
+ # Generate plots
138
+ python report/plot_benchmarks.py
139
+ python report/plot_extended.py
140
+ ```
141
+
142
+ For the full migration report with detailed analysis, see [`report/REPORT.md`](report/REPORT.md).
143
+
144
+ ---
145
+
146
+ ## Architecture
147
+
148
+ The key architectural change from OPFython is the elimination of per-node Python objects in favor of dense tensor columns:
149
+
150
+ ```
151
+ OPFython: subgraph.nodes[i].cost = 5.0 # Python object attribute
152
+ OPForch: subgraph.costs[i] = 5.0 # Tensor element (GPU-ready)
153
+ ```
154
+
155
+ Prediction is fully batched — a single tensor operation replaces the O(N×M) Python loop:
156
+
157
+ ```python
158
+ dist_matrix = distance_fn(train_features, test_features) # (N, M)
159
+ path_costs = torch.maximum(train_costs[:, None], dist_matrix) # (N, M)
160
+ predictions = train_labels[path_costs.argmin(dim=0)] # (M,)
161
+ ```
162
+
163
+ For the complete architecture documentation, see [`ARCHITECTURE.md`](ARCHITECTURE.md).
164
+
165
+ ---
166
+
167
+ ## Citation
168
+
169
+ If you use OPForch to fulfill any of your needs, please cite us:
170
+
171
+ ```
172
+ J. P. Papa, A. X. Falcão and C. T. N. Suzuki.
173
+ Supervised Pattern Classification based on Optimum-Path Forest.
174
+ International Journal of Imaging Systems and Technology (2009).
175
+ ```
176
+
177
+ ---
178
+
179
+ ## Datasets
180
+
181
+ Looking for datasets? We have some pre-loaded into OPF file format in the `data/` directory. More are available at [recogna.tech](http://recogna.tech).
182
+
183
+ ---
184
+
185
+ ## Support
186
+
187
+ If you ever need to report a bug, talk to us, or suggest improvements, please open an issue. We will do our best to help.
188
+
189
+ ---
@@ -0,0 +1,7 @@
1
+ """OPForch: PyTorch-Inspired Optimum-Path Forest Classifier.
2
+
3
+ This library provides GPU-accelerated OPF classifiers
4
+ using PyTorch tensors as the universal data representation.
5
+ """
6
+
7
+ __version__ = "2.0.0"
@@ -0,0 +1,5 @@
1
+ """Core structures for OPForch implementations."""
2
+
3
+ from opforch.core.heap import Heap
4
+ from opforch.core.subgraph import Subgraph
5
+ from opforch.core.opf import OPF