Introduce knn-engine and further refactors in aoa and trainDI#167
Open
goergen95 wants to merge 51 commits intoHannaMeyer:masterfrom
Open
Introduce knn-engine and further refactors in aoa and trainDI#167goergen95 wants to merge 51 commits intoHannaMeyer:masterfrom
goergen95 wants to merge 51 commits intoHannaMeyer:masterfrom
Conversation
small cleans
Integrates new knn-engine in knndm and nndm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
KNN-Engine and Refactors
@HannaMeyer, @Nowosad, @JanLinnenbrink:
The below summary of the PR was produced by the Claude Haiku 4.5 model inspecting
the previous PR description and analysing the diff. I reviewed all content
and edited/deleted obviously wrong content (though I am less confident for
the analysis of the changes in nndm.R/knndm.R).
Summary
This PR introduces a centralized k-nearest neighbor (KNN) distance calculation
engine (
knn-engine.R) and extensive refactoring of distancecalculations across the CAST package. The refactor replaces fragmented distance
computation logic with a unified, modular architecture while maintaining backward
compatibility through deprecation warnings. This represents a significant
architectural improvement that simplifies dependency management, improves code
maintainability, and sets the foundation for future parallelization.
1. KNN-Engine Architecture (
knn-engine.R)1.1 Core Design Principles
The new KNN engine is built on a preprocessor-calculator pattern that
separates distance metric preprocessing from pairwise distance computation:
1.2 Key Functions
.distance(reference, query, dist_fun)Purpose: Compute pairwise distance matrix between reference and query observations
Preprocessing Routing:
"euclidean"→ default normalization only"mahalanobis"→ covariance pseudo-inversion + linear transformation"gower"→ reference-based min/max scaling + factor encodingKey Assumptions:
.knndist(reference, query, k, dist_fun, offset)1.3 Known Caveats
gower::gower()applied global min-max normalization. New implementation uses reference-only normalization → test expectations changed2. Helper Functions & Data Preparation
2.1 Categorical Variable Handling (
aoa-helpers.R).prepare_categorical_variables()caret::dummyVars2.2 Weight Management
.prepare_weights(weight, model, variables, useWeight)sweep()- multiplies each column by corresponding weight2.3 Input Validation
.validate_LPD(maxLPD, n_samples).prepare_folds(model, CVtrain, CVtest, useCV)3. Distance Computation Refactors
3.1
trainDI.R- Training Data DissimilarityPrevious Approach:
.knndistfun()New Approach:
.calc_dist()and.calc_lpd()handle specific metricsKey Function:
.chunked_apply()calc_fun(e.g.,.calc_dist,.calc_lpd) to each chunkCV Fold Masking via
.mask_dist_mat():3.2
aoa.R- Area of ApplicabilitySignature Change:
Key Refactors:
method→dist_fun(matchesgeodist,knndm,nndm).process_row()and cluster logic deleted.convert_factors_to_dummy()from helpers.knndist()call with maxLPD parameter4. Cross-Package Refactors
4.1
knndm.R- k-NN Distance MatchingChanges:
FNN::knn.dist,FNN::knnx.dist).knndist()and.distance()from knn-engineknndm_feature()andknndm_geo()Removed Helper:
distclust_distmat()replaced bycv_distances()using.knndist()4.2
nndm.R- Nearest Neighbor Distance MatchingChanges:
space→dist_space(consistency with other functions)dist_fun="euclidean",scale_vars=TRUE.distance())4.3
geodist.R- Geographical DistanceChanges:
algorithmparameter (now in knn-engine)dist_fundetection for geographical coordinates.knndist()5. Dependency Changes
5.1 Removed Dependencies
FNN- Fast Nearest Neighbor library (for euclidean only)parallel- Fork cluster approach5.2 New Dependencies
philentropy- Unified distance computation backend (likely viadist_many_many())5.3 Implications
6. Further Refactors in PR
6.1
aoa-helpers.R(NEW FILE - 243 lines)Purpose: Consolidate repetitive validation and preprocessing logic
Components:
.validate_LPD().get_categorical_variables().drop_unknown_levels().create_dummy_variables().convert_factors_to_dummy().prepare_categorical_variables().prepare_weights().check_weights().apply_weights().prepare_folds().prepare_variables().di_threshold()Extraction Rationale: These 10 helper functions were previously embedded in
aoa.R(lines 25-550) andtrainDI.R. Extraction improves:6.2
caret-helpers.R(NEW FILE - 48 lines)Purpose: Centralize caret model introspection
.caret_get_data().caret_get_variables().caret_get_folds().caret_get_weights()Why new file?: Previously scattered across
trainDI.Rasaoa_get_*()functions. Unified naming and extracted to separate module signals these are infrastructure functions, not domain-specific.6.3
trainDI.R- Major Refactor (600 → 400 lines)Structural Changes:
.chunked_apply()with.calc_dist()and.calc_lpd()callbacksaoa_*functions moved toaoa-helpers.Randcaret-helpers.RBefore (trainDI main loop):
After (trainDI refactored):
Benefits:
.mask_dist_mat(), calculation in.calc_dist()/.calc_lpd()7. Impact on Package Architecture
7.1 Before: Fragmented Distance Logic
7.2 After: Centralized KNN Engine
8. Backward Compatibility & Deprecations
8.1 Deprecated Parameters
All functions show warnings (not errors) for old parameters:
8.2 Signature Mapping
method="L2"dist_fun="euclidean"method="MD"dist_fun="mahalanobis"parallel=TRUE/FALSEcores=Nparalleldeprecationalgorithm="brute"8.3 Test Expectations Updates
Tests that verify numerical results changed for:
9. Future Development & Maintenance Implications
9.1 Parallelization Strategy (Deferred)
Current Design:
.chunked_apply()ready for parallelizationRecommended Approach:
Benefits of chunking vs old fork approach:
futureframework (supports multiple backends)9.2 Numerical Precision
Known Issues:
9.3 Testing Infrastructure
New Test Files:
test-knn-engine.R(117 lines): Distance metric correctnesstest-aoa-helpers.R(170 lines): Validation and preprocessingtest-caret-helpers.R(32 lines): Model introspectiondata-fixture.R(29 lines): Shared test setuptest-aoa.R,test-geodist.R,test-knndm.R,test-nndm.RTest Coverage Strategy:
Conclusion
This PR represents a major architectural improvement to CAST. By centralizing
k-nearest neighbor distance computation, eliminating 200+ lines of duplicated logic,
and establishing a clean separation between distance metrics and spatial/feature applications,
the package becomes: