A nearest-neighbor result can look rectangular and complete while still containing slots that do not identify any source row. That distinction matters immediately when a SciPy KDTree.query result crosses into a payload-enrichment step. Suppose the source has three records and a returned index is 3. SciPy documents that a missing neighbor is represented by an infinite distance together with index self.n; with three source rows, self.n == 3, so that integer is a sentinel rather than an address into positions 0, 1, or 2.
Direct NumPy indexing can therefore raise IndexError. More dangerously, changing the gather to numpy.take(..., mode="clip") can make the exception disappear by mapping an excessive index to the last element. mode="wrap" changes the addressed position by another rule. Neither operation proves that the requested neighbor existed.
The consumer boundary should instead answer a narrower question first: did this particular query and requested neighbor rank receive a valid source neighbor? The answer comes from the distance/index pair, not from the integer alone. This laboratory preserves every query and requested rank, including absence; keeps legitimate zero-distance matches; and separates faithful representation of a missing neighbor from permission to perform a downstream assignment that requires a real neighbor.
Sources were reviewed on 2026-11-28. The numerical cases below are EXPECTED / NOT EXECUTED. Package metadata was inspected, but no KDTree was constructed or queried and no NumPy numerical operation was run. Every evidence record therefore begins with executed=false and observed=null.
Define what each query and rank must preserve
The unit of qualification is a result slot:
(case_id, subpath_id, query_id, requested_rank)There must be exactly one ledger record for every slot declared by the request. The query_id is an external identity retained by the application; it is not the query array's positional offset. The requested_rank is likewise independent metadata. With k=[1, 3], SciPy's two output columns mean “first neighbor” and “third neighbor,” not “column zero means rank one, column one means rank two.” SciPy documents integer k as a count and a sequence k as the requested k-th neighbors, starting at one.
This article uses three consumer statuses:
Status | Required pair | Payload permission |
MATCHED | finite distance >= 0; integer source index 0 <= i < n; retained source binding and oracle agree | Gather that source position |
MISSING | distance is positive infinity and i == n | No source ID and no payload |
HOLD_INCONSISTENT_PAIR | anything else | No payload access |
numpy.isfinite is useful for the first branch because zero is finite while infinities and NaN are not. Finiteness is not sufficient on its own: a finite distance paired with i == n, a negative index, or an index outside the source population still fails the consumer contract.
This separation also distinguishes evidence correctness from downstream usability. A MISSING row can be completely correct evidence of what the API returned. If the business operation requires two actual neighbors, that same slot cannot authorize an enrichment assignment. “Accepted as a faithful missing record” and “eligible to supply a neighbor-dependent value” are different decisions.
Pin the local engine and source snapshot
The selected execution profile is Python 3.12.14, NumPy 2.3.5, SciPy 1.17.0, Linux, CPU float64, ordinary NumPy arrays, exact search with eps=0, Euclidean p=2, workers=1, and boxsize=None. The SciPy 1.17.0 KDTree.query signature exposes those query controls, while KDTree documents its source as an (n, m) array and exposes n and m as source cardinality and dimensionality.
The fixture is deliberately small:
SOURCE_COORDS_LITERAL = [[0.0], [4.0], [9.0]]
SOURCE_IDS_LITERAL = ["A", "B", "C"]
PAYLOADS_LITERAL = [101, 202, 303]
QUERY_COORDS_LITERAL = [[0.0], [3.0], [12.0]]
QUERY_IDS_LITERAL = ["X0", "X3", "X12"]Thus source shape is (3, 1), n=3, and m=1. X0 is an external query whose coordinate happens to equal source row A's coordinate. Nothing in this fixture asks for fitted-member removal.
For a future controlled environment:
python3.12 -m venv .venv
. .venv/bin/activate
python -m pip install "numpy==2.3.5" "scipy==1.17.0"
python kdtree_missing_neighbor_lab.py --runThe executable script below checks interpreter and package versions before constructing the tree, records module paths from the actual imports, and stops on mismatch. The broader ecosystem context belongs to the scientific Python toolkit; this qualification remains deliberately limited to the stated SciPy/NumPy interface.
SciPy documents copy_data=True as causing the tree's input data to be copied. That protects the tree's coordinate storage from subsequent source-array mutation; it does not validate that an application-maintained ID array or payload array is aligned to those positions.
Bind positions to retained source identities
Keep independent retained copies of all position-bearing inputs before any query:
source_coords = np.array(SOURCE_COORDS_LITERAL, dtype=np.float64)
source_ids = np.array(SOURCE_IDS_LITERAL, dtype=object)
payloads = np.array(PAYLOADS_LITERAL, dtype=np.int64)
query_coords = np.array(QUERY_COORDS_LITERAL, dtype=np.float64)
query_ids = np.array(QUERY_IDS_LITERAL, dtype=object)
source_coords_before = source_coords.copy()
source_ids_before = source_ids.copy()
payloads_before = payloads.copy()
query_coords_before = query_coords.copy()
query_ids_before = query_ids.copy()Admission checks require source shape (3,1), query shape (3,1), finite coordinate values, unique source IDs, unique external query IDs, and equal first-axis lengths among coordinates, IDs, and payloads. Two-dimensional query arrays are mandatory here; scalar-query shape variants are outside scope.
The source-position contract is explicit: position 0 → ("A", [0.0], 101), position 1 → ("B", [4.0], 202), position 2 → ("C", [9.0], 303). A returned source index is acceptable only if it can be reconciled against that retained binding. The copied KDTree coordinate array cannot authenticate the separate strings "A", "B", "C" or payloads 101, 202, 303; that responsibility remains at the consumer boundary.
Write an independent query-and-rank ledger
Expected results should be authored before executing the search. The manifest records source revision, query revision, the original k argument, declared requested ranks, distance_upper_bound, query IDs, expected shapes, and expected values. This is the same record-keeping principle behind efforts to preserve raw records and their grain: do not collapse distinct requested slots merely because some ultimately have no payload.
For integer k, the declared rank roster is 1..k. For a list-valued request such as [1,3], retain that list exactly. The distinction matters even when two cases happen to produce the same number of output columns.
A compact manifest constructor is:
def declared_ranks(k):
if isinstance(k, int):
if k < 1:
raise ValueError("k must be positive in this fixture")
return list(range(1, k + 1))
ranks = [int(x) for x in k]
if not ranks or any(x < 1 for x in ranks):
raise ValueError("rank list must contain positive integers")
return ranksCases K01, K02, K06, K07, K08, and K09 describe valid library queries. K03, K04, and K05 include deliberately faulty consumers. K10 injects malformed pairs directly into the decoder and makes no claim that SciPy emitted those values.
The evidence grain remains the declared (query_id, requested_rank) slot even when the API has squeezed an axis for integer k=1.
Check the literal manifest with scalar distances
The independent oracle uses ordinary Python scalar arithmetic rather than SciPy or the returned indices:
def scalar_oracle(source_values, query_value, requested_ranks, bound):
ordered = sorted(
(abs(float(query_value) - float(source_value)), source_index)
for source_index, source_value in enumerate(source_values)
)
answer = []
n = len(source_values)
for rank in requested_ranks:
if rank > n:
answer.append((float("inf"), n))
continue
distance, source_index = ordered[rank - 1]
if distance > bound:
answer.append((float("inf"), n))
else:
answer.append((float(distance), int(source_index)))
return answerThe three source coordinates are 0, 4, and 9. For X0=0, scalar distances are 0,4,9; for X3=3, they are 3,1,6; for X12=12, they are 12,8,3. These are distinct within every query, so distance-tie ordering is intentionally absent from the laboratory.
The finite cutoff is 2.5. All relevant finite distances are integers, so no distance equals the cutoff. Exact cutoff equality is therefore not qualified here.
Expected numerical distance arrays are authored as np.float64; expected index arrays use np.intp. NumPy documents intp as its native indexing integer type. The future checker records np.dtype(np.intp).itemsize * 8 as platform index width and stops if the observed result dtype differs from the selected profile.
numpy.testing.assert_array_equal(..., strict=True) can enforce exact values, shape, and dtype. NumPy also documents that corresponding NaNs can compare equal under this assertion, so the checker rejects unexpected NaNs separately before exact comparison. Exact equality is appropriate only because this fixture's expected finite distances are the supplied small integer values represented in float64; this article does not generalize that strategy to arbitrary floating-point geometry.
Establish the unbounded two-neighbor baseline
K01, unbounded_k2, queries all three external points with k=2 and distance_upper_bound=np.inf.
The literal expectations are:
K01_D = np.array(
[[0.0, 4.0],
[1.0, 3.0],
[3.0, 8.0]],
dtype=np.float64,
)
K01_I = np.array(
[[0, 1],
[1, 0],
[2, 1]],
dtype=np.intp,
)
K01_SOURCE_IDS = [
["A", "B"],
["B", "A"],
["C", "B"],
]Both numerical matrices have shape (3,2). SciPy specifies that returned indices identify rows in self.data, so those positions are reconciled back to the retained source snapshot rather than treated as anonymous column values.
For example, K01's X3/rank1 expectation is index 1, distance 1. The consumer should verify that source position 1 still binds to ID "B", coordinate [4.0], and payload 202. The same process maps X3/rank2 to position 0, ID "A", coordinate [0.0], payload 101.
Reusable capture helpers distinguish expectations from observations:
def fresh_evidence(case_id, subpath_id):
return {
"case_id": case_id,
"subpath_id": subpath_id,
"executed": False,
"observed": None,
"exception": None,
"decision": None,
}
def capture_call(record, fn):
record["executed"] = True
try:
value = fn()
except Exception as exc:
record["observed"] = None
record["exception"] = {
"type": type(exc).__name__,
"message": str(exc),
}
return None
record["observed"] = value
return valueBefore a real run, those fields remain executed=false, observed=null. No exception text is invented.
The numerical comparison helper checks NaNs, shape, dtype, and exact values independently:
def assert_exact_array(actual, expected, label):
if actual.shape != expected.shape:
raise AssertionError(
f"{label}: shape {actual.shape} != {expected.shape}"
)
if actual.dtype != expected.dtype:
raise AssertionError(
f"{label}: dtype {actual.dtype} != {expected.dtype}"
)
if np.issubdtype(actual.dtype, np.floating) and np.isnan(actual).any():
raise AssertionError(f"{label}: unexpected NaN")
np.testing.assert_array_equal(actual, expected, strict=True)K01 establishes that the retained three-row population and ordinary matched gathering path are internally coherent for this exact request. It is not an oracle for K02 or any other bound, k, population, or query set.
Retain missing slots under a finite bound
K02, bounded_k2, repeats the main queries with k=2 and distance_upper_bound=2.5.
Expected distances:
[[0, +inf],
[1, +inf],
[+inf,+inf]]Expected indices:
[[0,3],
[1,3],
[3,3]]Expected statuses:
[[MATCHED,MISSING],
[MATCHED,MISSING],
[MISSING,MISSING]]Accepted payload view:
[[101,null],
[202,null],
[null,null]]SciPy documents the paired representation directly: missing distances are infinite and missing indices are self.n. Here the source cardinality is three, so the sentinel is 3.
There are six requested slots, and all six remain represented:
Query | Rank | Distance | Index | Status | Source | Payload |
X0 | 1 | 0 | 0 | MATCHED | A | 101 |
X0 | 2 | +inf | 3 | MISSING | null | null |
X3 | 1 | 1 | 1 | MATCHED | B | 202 |
X3 | 2 | +inf | 3 | MISSING | null | null |
X12 | 1 | +inf | 3 | MISSING | null | null |
X12 | 2 | +inf | 3 | MISSING | null | null |
+inf is mathematical notation in that table, not a recommendation to emit JSON's nonstandard Infinity token. The strict serialization later stores raw_distance_token="+inf" and sets the numeric distance field to null.
The key boundary is positional: valid payload positions are 0, 1, and 2. Position 3 is not “the fourth source row”; no fourth source row exists. The sentinel communicates absence within the KDTree.query result contract. That missing slot should remain attached to X0/rank2, X3/rank2, or the relevant X12 rank rather than being dropped.
Expose unsafe gathering and permissive substitutions
K03, direct_gather, deliberately evaluates the K02 index matrix against the three-element payload array:
candidate = payloads[k02_indices]NumPy integer-array indexing uses zero-based addresses, and out-of-bounds integer indices raise IndexError for the nonempty case exercised here. Negative indices have a different documented meaning: they count from the end, which is precisely why a consumer cannot accept -1 as a missing-neighbor convention.
The expected K03 outcome is therefore an IndexError and no accepted payload matrix. A future run records the actual exception type and message. This article does not fabricate wording and does not infer transactional behavior beyond the expression being evaluated.
K04 tests two calls that can turn the out-of-range sentinel into ordinary-looking data:
np.take(payloads, k02_indices, axis=0, mode="clip")
np.take(payloads, k02_indices, axis=0, mode="wrap")NumPy documents raise, wrap, and clip as distinct out-of-bounds modes. For clip, excessive indices are replaced by the index addressing the last element. wrap wraps the index into the available range.
The expected K04 clip candidate is:
[[101,303],
[202,303],
[303,303]]The expected wrap candidate is:
[[101,101],
[202,101],
[101,101]]Each absent K02 slot has acquired a plausible integer payload even though no neighbor existed there. Both candidates are therefore REJECT, regardless of whether their NumPy calls return normally.
This is not a reason to widen distance_upper_bound, substitute the nearest source outside the approved radius, or change k. Those actions alter the request. They can be valid only under a newly approved contract and a new qualification.
Refonte Learning's separate discussion of interpolation domain versus endpoint fill addresses another API's substitution semantics. The analogy stops at the consumer principle: a library-defined fallback should not be mistaken for evidence that the original requested object existed.
Classify pairs before gathering source payloads
K05 has two subpaths: qualified_decoder and positive_distance_mask.
The qualified decoder takes the complete distance/index arrays, confirms their expected shape and roster, validates every pair, and only after the whole batch passes structural validation does it gather payloads for MATCHED positions. It explicitly performs no gather when there are no matched positions.
A reusable classifier is:
MATCHED = "MATCHED"
MISSING = "MISSING"
HOLD = "HOLD_INCONSISTENT_PAIR"
def classify_pair(distance, index, n):
index_is_integer = isinstance(index, (int, np.integer))
if not index_is_integer:
return HOLD, "index_not_integer"
index = int(index)
if np.isfinite(distance):
if distance < 0:
return HOLD, "negative_distance"
if 0 <= index < n:
return MATCHED, None
return HOLD, "finite_distance_invalid_index"
if np.isposinf(distance) and index == n:
return MISSING, None
if np.isnan(distance):
return HOLD, "nan_distance"
return HOLD, "nonfinite_pair_inconsistent"For K02, the qualified ledger contains X0/rank1 → A, distance 0, payload 101, X3/rank1 → B, distance 1, payload 202, and four explicit MISSING rows. No missing row receives a source identity or payload.
Negative indices, negative distances, NaN, finite distance paired with index n, and infinite distance paired with an ordinary source index all stop before gathering.
Keep a legitimate zero-distance match
K05's deliberately wrong positive_distance_mask is:
wrong_mask = np.isfinite(k02_distances) & (k02_distances > 0)For the supplied K02 expectation, it retains only X3/rank1 and incorrectly removes X0/rank1.
That is a consumer defect. X0 is an external query. Its coordinate equals A's coordinate, so distance zero is a legitimate match under this fixture. numpy.isfinite(0.0) is true.
Do not reinterpret that result as a rule about removing a fitted member. That separate identity problem is covered by the separate kneighbors self-exclusion contract. This article has no fitted-query mode, no classifier evaluation, and no self-removal step.
Preserve the query axis and requested-rank meaning
K06 shows why shape is part of the interface.
integer_one uses k=1 at bound 2.5. Expected distances and indices are:
np.array([0.0, 1.0, np.inf], dtype=np.float64)
np.array([0, 1, 3], dtype=np.intp)Both have shape (3,).
rank_list_one uses k=[1] with the same queries and bound:
np.array([[0.0], [1.0], [np.inf]], dtype=np.float64)
np.array([[0], [1], [3]], dtype=np.intp)Both have shape (3,1).
SciPy 1.17.0 explicitly documents that integer k=1 squeezes the final result dimension, while the example with k=[1] retains a one-column final axis.
The adapter should therefore validate the documented shape first, then normalize into a canonical ledger. One safe normalization for this restricted two-dimensional query fixture is:
def normalize_result(distances, indices, query_count, requested_ranks, k_was_int):
if k_was_int and requested_ranks == [1]:
expected_shape = (query_count,)
if distances.shape != expected_shape or indices.shape != expected_shape:
raise ValueError("unexpected squeezed k=1 shape")
return distances[:, None], indices[:, None]
expected_shape = (query_count, len(requested_ranks))
if distances.shape != expected_shape or indices.shape != expected_shape:
raise ValueError("unexpected unsqueezed result shape")
return distances, indicesBoth K06 paths then produce the same three canonical records: X0/rank1 → A, X3/rank1 → B, and X12/rank1 → MISSING.
An indiscriminate np.squeeze is intentionally absent. In a one-query situation, squeezing all singleton axes could erase the query axis as well as a neighbor axis, leaving downstream code unable to distinguish dimensions by meaning.
Preserve sparse requested ranks
K07, sparse_ranks, requests:
k=[1, 3]
distance_upper_bound=np.infExpected distances:
[[0,9],
[1,6],
[3,12]]Expected indices:
[[0,2],
[1,2],
[2,0]]Shape is (3,2), and all six slots are matched. The column metadata, however, is [1,3].
For X3, column zero is first neighbor B at distance 1; column one is third neighbor C at distance 6. Calling the second column “rank 2” would produce a semantically false ledger even though every number in the NumPy arrays remained unchanged.
This is why requested rank travels alongside output-column offset:
for qpos, query_id in enumerate(query_ids):
for column, requested_rank in enumerate([1, 3]):
distance = distances[qpos, column]
index = indices[qpos, column]Column is an implementation position; requested_rank is request meaning. They coincide only for dense requests such as integer k=2, where columns correspond to ranks one and two.
Request a rank beyond the source population
K08, excess_rank, queries only external query X3 at coordinate [[3.0]], with k=4 and an infinite upper bound.
The source contains three points. Expected results are:
K08_D = np.array([[1.0, 3.0, 6.0, np.inf]], dtype=np.float64)
K08_I = np.array([[1, 0, 2, 3]], dtype=np.intp)Shape is (1,4).
The resulting ledger is:
Query | Rank | Result |
X3 | 1 | B, distance 1 |
X3 | 2 | A, distance 3 |
X3 | 3 | C, distance 6 |
X3 | 4 | MISSING |
The fourth missing slot is not caused by the finite 2.5 radius used elsewhere; K08 has an infinite upper bound. It is a source-cardinality control demonstrating that the documented missing representation is not uniquely evidence of “too far away.” SciPy's result contract supplies infinite distance and self.n for a missing neighbor; the application's contextual reason for absence must come from the declared request and retained source population rather than from the sentinel alone.
The consumer must not transform rank four into source position 3, duplicate C, reduce k after the fact, or delete the fourth slot. The request asked for four ranks and therefore the manifest requires four records.
At the same time, two conclusions can coexist: the K08 ledger can be ACCEPTED as a faithful representation of the query, while an application requirement such as “four actual neighbors must exist” remains HOLD. Evidence fidelity does not override the downstream coverage requirement.
Preserve a completely missing batch
K09, all_missing, uses two external queries:
query_ids = ["X12", "X20"]
query_coords = np.array([[12.0], [20.0]], dtype=np.float64)with k=2 and distance_upper_bound=2.5.The expected distance matrix is:
[[+inf,+inf],
[+inf,+inf]]and the expected index matrix is:
[[3,3],
[3,3]]Both have shape (2,2).
The ledger must retain two query identities and four rank slots:
X12/rank1 -> MISSING
X12/rank2 -> MISSING
X20/rank1 -> MISSING
X20/rank2 -> MISSINGThere are zero accepted payloads and, under the guarded decoder, zero payload-gather operations. That does not mean zero query calls: in a future execution the KDTree.query call still occurs and yields evidence that is then decoded.
An all-missing result is not an empty evidence artifact. It carries four specific answers to four requested slots. If the application requires at least one or two actual neighbors, that downstream requirement remains unmet, but the numerical evidence itself need not be classified as an error merely because nothing qualified for payload access.
This resembles the record-preservation discipline in raster sampling admission and valid zeros, but no raster concepts transfer into this fixture. There is no CRS, grid, mask, reprojection, or spatial admission logic here; the only admissibility test is the stated KDTree distance/index pair contract plus retained source identity.
Reject inconsistent pairs at the consumer boundary
K10 bypasses SciPy and fault-injects four one-slot decoder inputs. They are diagnostics, not claimed KDTree outputs.
The mandatory subpaths are:
Subpath | Distance | Index | Expected status |
finite_n | 1.0 | 3 | HOLD_INCONSISTENT_PAIR |
inf_valid | +inf | 0 | HOLD_INCONSISTENT_PAIR |
negative_index | 1.0 | -1 | HOLD_INCONSISTENT_PAIR |
nan_n | NaN | 3 | HOLD_INCONSISTENT_PAIR |
finite_n is internally contradictory under this consumer contract because a finite match cannot point at the missing sentinel. inf_valid combines the missing-distance side with an ordinary source index. negative_index is particularly important because NumPy gives negative integer indices a valid from-the-end interpretation; application validation must reject the value before NumPy receives it. nan_n is not a documented ordinary missing representation and is held independently; np.isfinite distinguishes NaN from finite values but does not by itself identify a valid missing pair.
The required aggregate is four decoder attempts and zero gathers.
Diagnostic evidence retains the malformed values rather than normalizing them into something usable:
{
"case_id": "K10",
"subpath_id": "finite_n",
"raw_distance_token": "1.0",
"distance": 1.0,
"raw_index": 3,
"status": "HOLD_INCONSISTENT_PAIR",
"source_id": null,
"payload": null
}For nan_n, the numeric JSON distance becomes null and a diagnostic token records "NaN".
Prove that the guard precedes the gather
Do not infer “no gather happened” merely because the final output contains no payloads. Instrument payload access:
class PayloadAccessProbe:
def init(self, payloads):
self.payloads = payloads
self.gather_calls = 0
def gather(self, indices):
self.gather_calls += 1
return np.take(self.payloads, indices, axis=0, mode="raise")The guarded decoder first classifies the entire supplied pair matrix. Any inconsistent slot aborts payload access for that decoder attempt:
def decode_guarded(distances, indices, *, n, probe):
statuses = []
reasons = []
for distance, index in zip(distances.flat, indices.flat):
status, reason = classify_pair(distance, index, n)
statuses.append(status)
reasons.append(reason)
if HOLD in statuses:
return {
"statuses": statuses,
"reasons": reasons,
"gathered": None,
}
matched_indices = [
int(index)
for index, status in zip(indices.flat, statuses)
if status == MATCHED
]
gathered = None
if matched_indices:
gathered = probe.gather(
np.asarray(matched_indices, dtype=np.intp)
)
return {
"statuses": statuses,
"reasons": reasons,
"gathered": gathered,
}This ordering prevents a valid-looking prefix from being gathered before a malformed suffix is discovered. The guard is application policy: it demonstrates how the consumer refuses contradictory evidence; it is not an assertion that SciPy produces corrupt pairs.
Reconcile all cases and serialize absence explicitly
The mandatory evidence roster contains ten case IDs and sixteen named subpaths:
Case | Subpaths |
K01 | unbounded_k2 |
K02 | bounded_k2 |
K03 | direct_gather |
K04 | clip, wrap |
K05 | qualified_decoder, positive_distance_mask |
K06 | integer_one, rank_list_one |
K07 | sparse_ranks |
K08 | excess_rank |
K09 | all_missing |
K10 | finite_n, inf_valid, negative_index, nan_n |
A checker rejects omitted or duplicated (case_id, subpath_id) evidence. For paths that represent a query result, it also reconciles the complete query/rank roster. An exception path such as K03 does not receive fabricated accepted-payload rows, and a K10 diagnostic that correctly reaches the expected hold still does not make its malformed candidate acceptable.
The following script is the complete runnable laboratory. It has not been executed for this article. Without --run, it writes only an expected/not-executed manifest; with --run, it checks the selected environment, constructs KDTree, captures raw results, performs the deliberate bad-consumer paths, checks all expectations, and writes strict JSON evidence.
#!/usr/bin/env python3
import argparse
import importlib.metadata
import json
import platform
import sys
from copy import deepcopy
from pathlib import Path
EXPECTED_PYTHON = "3.12.14"
EXPECTED_NUMPY = "2.3.5"
EXPECTED_SCIPY = "1.17.0"
SOURCE_REVISION = "source-v1-2026-11-28"
QUERY_REVISION = "query-v1-2026-11-28"
SOURCE_COORDS_LITERAL = [[0.0], [4.0], [9.0]]
SOURCE_IDS_LITERAL = ["A", "B", "C"]
PAYLOADS_LITERAL = [101, 202, 303]
MAIN_QUERY_COORDS_LITERAL = [[0.0], [3.0], [12.0]]
MAIN_QUERY_IDS_LITERAL = ["X0", "X3", "X12"]
MATCHED = "MATCHED"
MISSING = "MISSING"
HOLD = "HOLD_INCONSISTENT_PAIR"
MANDATORY_ROSTER = [
("K01", "unbounded_k2"),
("K02", "bounded_k2"),
("K03", "direct_gather"),
("K04", "clip"),
("K04", "wrap"),
("K05", "qualified_decoder"),
("K05", "positive_distance_mask"),
("K06", "integer_one"),
("K06", "rank_list_one"),
("K07", "sparse_ranks"),
("K08", "excess_rank"),
("K09", "all_missing"),
("K10", "finite_n"),
("K10", "inf_valid"),
("K10", "negative_index"),
("K10", "nan_n"),
]
def base_record(case_id, subpath_id):
return {
"case_id": case_id,
"subpath_id": subpath_id,
"source_revision": SOURCE_REVISION,
"query_revision": QUERY_REVISION,
"executed": False,
"observed": None,
"exception": None,
"decision": None,
}
def expected_only_evidence():
return [base_record(c, s) for c, s in MANDATORY_ROSTER]
def strict_dump(obj, path):
text = json.dumps(
obj,
indent=2,
sort_keys=True,
allow_nan=False,
)
Path(path).write_text(text + "\n", encoding="utf-8")
def check_roster(records):
got = [(x["case_id"], x["subpath_id"]) for x in records]
if len(got) != len(set(got)):
raise AssertionError("duplicate evidence subpath")
if got != MANDATORY_ROSTER:
raise AssertionError(
f"evidence roster mismatch:\nexpected={MANDATORY_ROSTER}\ngot={got}"
)
def scalar_oracle(source_values, query_value, requested_ranks, bound):
ordered = sorted(
(abs(float(query_value) - float(source_value)), source_index)
for source_index, source_value in enumerate(source_values)
)
n = len(source_values)
answer = []
for rank in requested_ranks:
if rank > n:
answer.append((float("inf"), n))
continue
distance, source_index = ordered[rank - 1]
if distance > bound:
answer.append((float("inf"), n))
else:
answer.append((float(distance), int(source_index)))
return answer
def declared_ranks(k):
if isinstance(k, int):
if k < 1:
raise ValueError("k must be >= 1")
return list(range(1, k + 1))
ranks = [int(x) for x in k]
if not ranks or any(x < 1 for x in ranks):
raise ValueError("rank list must contain positive integers")
return ranks
def classify_pair(np, distance, index, n):
if not isinstance(index, (int, np.integer)):
return HOLD, "index_not_integer"
index = int(index)
if np.isfinite(distance):
if distance < 0:
return HOLD, "negative_distance"
if 0 <= index < n:
return MATCHED, None
return HOLD, "finite_distance_invalid_index"
if np.isposinf(distance) and index == n:
return MISSING, None
if np.isnan(distance):
return HOLD, "nan_distance"
return HOLD, "nonfinite_pair_inconsistent"
class PayloadAccessProbe:
def init(self, np, payloads):
self.np = np
self.payloads = payloads
self.gather_calls = 0
def gather(self, indices):
self.gather_calls += 1
return self.np.take(
self.payloads,
indices,
axis=0,
mode="raise",
)
def strict_array_equal(np, actual, expected, label):
if actual.shape != expected.shape:
raise AssertionError(
f"{label}: shape {actual.shape} != {expected.shape}"
)
if actual.dtype != expected.dtype:
raise AssertionError(
f"{label}: dtype {actual.dtype} != {expected.dtype}"
)
if (
np.issubdtype(actual.dtype, np.floating)
and np.isnan(actual).any()
):
raise AssertionError(f"{label}: unexpected NaN")
np.testing.assert_array_equal(actual, expected, strict=True)
def normalize_result(
distances,
indices,
query_count,
ranks,
k_was_int,
):
if k_was_int and ranks == [1]:
expected = (query_count,)
if distances.shape != expected or indices.shape != expected:
raise AssertionError("unexpected squeezed k=1 shape")
return distances[:, None], indices[:, None]
expected = (query_count, len(ranks))
if distances.shape != expected or indices.shape != expected:
raise AssertionError(
f"unexpected query result shape: "
f"{distances.shape}, {indices.shape}, expected {expected}"
)
return distances, indices
def raw_distance_token(np, value):
if np.isnan(value):
return "NaN"
if np.isposinf(value):
return "+inf"
if np.isneginf(value):
return "-inf"
return repr(float(value))
def ledger_row(
np,
query_id,
rank,
distance,
index,
status,
source_ids,
payloads,
):
if status == MATCHED:
return {
"query_id": query_id,
"requested_rank": rank,
"raw_distance_token": raw_distance_token(np, distance),
"distance": float(distance),
"raw_index": int(index),
"status": MATCHED,
"source_id": str(source_ids[int(index)]),
"payload": int(payloads[int(index)]),
}
return {
"query_id": query_id,
"requested_rank": rank,
"raw_distance_token": raw_distance_token(np, distance),
"distance": None,
"raw_index": int(index),
"status": status,
"source_id": None,
"payload": None,
}
def decode_complete(
np,
distances,
indices,
query_ids,
ranks,
source_ids,
payloads,
probe,
):
n = len(source_ids)
pair_info = []
for qpos, query_id in enumerate(query_ids):
for col, rank in enumerate(ranks):
distance = distances[qpos, col]
index = indices[qpos, col]
status, reason = classify_pair(np, distance, index, n)
pair_info.append(
(qpos, col, query_id, rank, distance, index, status, reason)
)
holds = [x for x in pair_info if x[6] == HOLD]
if holds:
return {
"ledger": [
{
"query_id": x[2],
"requested_rank": x[3],
"raw_distance_token": raw_distance_token(np, x[4]),
"distance": None
if not np.isfinite(x[4])
else float(x[4]),
"raw_index": int(x[5]),
"status": HOLD,
"reason": x[7],
"source_id": None,
"payload": None,
}
for x in pair_info
],
"gathered": None,
}
matched_indices = np.array(
[int(x[5]) for x in pair_info if x[6] == MATCHED],
dtype=np.intp,
)
gathered = None
if matched_indices.size:
gathered = probe.gather(matched_indices)
ledger = [
ledger_row(
np,
x[2],
x[3],
x[4],
x[5],
x[6],
source_ids,
payloads,
)
for x in pair_info
]
return {
"ledger": ledger,
"gathered": None if gathered is None else gathered.tolist(),
}
def oracle_matrix(np, source_coords, query_coords, ranks, bound):
ds = []
ii = []
source_1d = [float(row[0]) for row in source_coords]
for row in query_coords:
pairs = scalar_oracle(
source_1d,
float(row[0]),
ranks,
bound,
)
ds.append([p[0] for p in pairs])
ii.append([p[1] for p in pairs])
return (
np.array(ds, dtype=np.float64),
np.array(ii, dtype=np.intp),
)
def query_case(tree, np, q, k, bound):
return tree.query(
q,
k=k,
eps=0,
p=2,
distance_upper_bound=bound,
workers=1,
)
def environment(np, scipy):
return {
"python": platform.python_version(),
"numpy_metadata": importlib.metadata.version("numpy"),
"scipy_metadata": importlib.metadata.version("scipy"),
"numpy_import_version": np.__version__,
"scipy_import_version": scipy.__version__,
"numpy_module_path": str(np.__file__),
"scipy_module_path": str(scipy.__file__),
"platform": platform.platform(),
"machine": platform.machine(),
"python_executable": sys.executable,
"np_intp_bits": np.dtype(np.intp).itemsize * 8,
}
def enforce_environment(env):
if env["python"] != EXPECTED_PYTHON:
raise RuntimeError(f"Python mismatch: {env['python']}")
if env["numpy_metadata"] != EXPECTED_NUMPY:
raise RuntimeError(f"NumPy metadata mismatch: {env['numpy_metadata']}")
if env["scipy_metadata"] != EXPECTED_SCIPY:
raise RuntimeError(f"SciPy metadata mismatch: {env['scipy_metadata']}")
if env["numpy_import_version"] != EXPECTED_NUMPY:
raise RuntimeError("NumPy import version mismatch")
if env["scipy_import_version"] != EXPECTED_SCIPY:
raise RuntimeError("SciPy import version mismatch")
def run():
import numpy as np
import scipy
from scipy.spatial import KDTree
env = environment(np, scipy)
enforce_environment(env)
source_coords = np.array(SOURCE_COORDS_LITERAL, dtype=np.float64)
source_ids = np.array(SOURCE_IDS_LITERAL, dtype=object)
payloads = np.array(PAYLOADS_LITERAL, dtype=np.int64)
main_q = np.array(MAIN_QUERY_COORDS_LITERAL, dtype=np.float64)
main_ids = np.array(MAIN_QUERY_IDS_LITERAL, dtype=object)
source_before = source_coords.copy()
ids_before = source_ids.copy()
payload_before = payloads.copy()
q_before = main_q.copy()
qids_before = main_ids.copy()
if source_coords.shape != (3, 1):
raise AssertionError("source shape")
if main_q.shape != (3, 1):
raise AssertionError("query shape")
if not np.isfinite(source_coords).all():
raise AssertionError("nonfinite source coordinate")
if not np.isfinite(main_q).all():
raise AssertionError("nonfinite query coordinate")
if len(set(source_ids.tolist())) != len(source_ids):
raise AssertionError("duplicate source ID")
if len(set(main_ids.tolist())) != len(main_ids):
raise AssertionError("duplicate query ID")
if len(source_ids) != len(source_coords) or len(payloads) != len(source_coords):
raise AssertionError("source binding length mismatch")
tree = KDTree(
source_coords,
copy_data=True,
boxsize=None,
)
if tree.n != 3 or tree.m != 1:
raise AssertionError("unexpected tree population/dimension")
records = []
def rec(case, subpath):
r = base_record(case, subpath)
r["executed"] = True
records.append(r)
return r
# Literal expectations.
K01_D = np.array([[0, 4], [1, 3], [3, 8]], dtype=np.float64)
K01_I = np.array([[0, 1], [1, 0], [2, 1]], dtype=np.intp)
K02_D = np.array(
[[0, np.inf], [1, np.inf], [np.inf, np.inf]],
dtype=np.float64,
)
K02_I = np.array([[0, 3], [1, 3], [3, 3]], dtype=np.intp)
# Independent oracle checks literals before SciPy comparison.
o1d, o1i = oracle_matrix(np, source_coords, main_q, [1, 2], np.inf)
strict_array_equal(np, K01_D, o1d, "K01 literal/oracle distance")
strict_array_equal(np, K01_I, o1i, "K01 literal/oracle index")
o2d, o2i = oracle_matrix(np, source_coords, main_q, [1, 2], 2.5)
strict_array_equal(np, K02_D, o2d, "K02 literal/oracle distance")
strict_array_equal(np, K02_I, o2i, "K02 literal/oracle index")
# K01
r = rec("K01", "unbounded_k2")
d1, i1 = query_case(tree, np, main_q, 2, np.inf)
strict_array_equal(np, d1, K01_D, "K01 distances")
strict_array_equal(np, i1, K01_I, "K01 indices")
r["observed"] = {"distances": d1.tolist(), "indices": i1.tolist()}
r["decision"] = "ACCEPT"
# K02
r = rec("K02", "bounded_k2")
d2, i2 = query_case(tree, np, main_q, 2, 2.5)
strict_array_equal(np, d2, K02_D, "K02 distances")
strict_array_equal(np, i2, K02_I, "K02 indices")
r["observed"] = {
"distances_tokens": [
[raw_distance_token(np, x) for x in row] for row in d2
],
"indices": i2.tolist(),
}
r["decision"] = "ACCEPT"
# K03 direct gather.
r = rec("K03", "direct_gather")
try:
candidate = payloads[i2]
except Exception as exc:
r["exception"] = {
"type": type(exc).__name__,
"message": str(exc),
}
if not isinstance(exc, IndexError):
raise
r["decision"] = "REJECT"
else:
r["observed"] = candidate.tolist()
raise AssertionError("K03 unexpectedly returned")
# K04 clip.
r = rec("K04", "clip")
clip_candidate = np.take(payloads, i2, axis=0, mode="clip")
clip_expected = np.array(
[[101, 303], [202, 303], [303, 303]],
dtype=payloads.dtype,
)
strict_array_equal(np, clip_candidate, clip_expected, "K04 clip")
r["observed"] = clip_candidate.tolist()
r["decision"] = "REJECT"
# K04 wrap.
r = rec("K04", "wrap")
wrap_candidate = np.take(payloads, i2, axis=0, mode="wrap")
wrap_expected = np.array(
[[101, 101], [202, 101], [101, 101]],
dtype=payloads.dtype,
)
strict_array_equal(np, wrap_candidate, wrap_expected, "K04 wrap")
r["observed"] = wrap_candidate.tolist()
r["decision"] = "REJECT"
# K05 guarded decoder.
r = rec("K05", "qualified_decoder")
probe = PayloadAccessProbe(np, payloads)
decoded = decode_complete(
np, d2, i2, main_ids.tolist(), [1, 2], source_ids, payloads, probe
)
if probe.gather_calls != 1:
raise AssertionError("K05 qualified expected one matched batch gather")
r["observed"] = {
"ledger": decoded["ledger"],
"gather_calls": probe.gather_calls,
}
r["decision"] = "ACCEPT"
# K05 wrong positive-distance mask.
r = rec("K05", "positive_distance_mask")
wrong_mask = np.isfinite(d2) & (d2 > 0)
expected_wrong = np.array(
[[False, False], [True, False], [False, False]],
dtype=bool,
)
strict_array_equal(np, wrong_mask, expected_wrong, "K05 wrong mask")
r["observed"] = wrong_mask.tolist()
r["decision"] = "REJECT"
# K06 integer k=1.
r = rec("K06", "integer_one")
d6a, i6a = query_case(tree, np, main_q, 1, 2.5)
e6ad = np.array([0, 1, np.inf], dtype=np.float64)
e6ai = np.array([0, 1, 3], dtype=np.intp)
strict_array_equal(np, d6a, e6ad, "K06 integer distances")
strict_array_equal(np, i6a, e6ai, "K06 integer indices")
n6ad, n6ai = normalize_result(d6a, i6a, 3, [1], True)
r["observed"] = {
"raw_shape": list(d6a.shape),
"normalized_shape": list(n6ad.shape),
}
r["decision"] = "ACCEPT"
# K06 k=[1].
r = rec("K06", "rank_list_one")
d6b, i6b = query_case(tree, np, main_q, [1], 2.5)
e6bd = np.array([[0], [1], [np.inf]], dtype=np.float64)
e6bi = np.array([[0], [1], [3]], dtype=np.intp)
strict_array_equal(np, d6b, e6bd, "K06 list distances")
strict_array_equal(np, i6b, e6bi, "K06 list indices")
n6bd, n6bi = normalize_result(d6b, i6b, 3, [1], False)
strict_array_equal(np, n6ad, n6bd, "K06 normalized distances")
strict_array_equal(np, n6ai, n6bi, "K06 normalized indices")
r["observed"] = {"raw_shape": list(d6b.shape)}
r["decision"] = "ACCEPT"
# K07 sparse ranks.
r = rec("K07", "sparse_ranks")
d7, i7 = query_case(tree, np, main_q, [1, 3], np.inf)
e7d = np.array([[0, 9], [1, 6], [3, 12]], dtype=np.float64)
e7i = np.array([[0, 2], [1, 2], [2, 0]], dtype=np.intp)
strict_array_equal(np, d7, e7d, "K07 distances")
strict_array_equal(np, i7, e7i, "K07 indices")
r["observed"] = {
"requested_ranks": [1, 3],
"distances": d7.tolist(),
"indices": i7.tolist(),
}
r["decision"] = "ACCEPT"
# K08 rank beyond source population.
r = rec("K08", "excess_rank")
q8 = np.array([[3.0]], dtype=np.float64)
d8, i8 = query_case(tree, np, q8, 4, np.inf)
e8d = np.array([[1, 3, 6, np.inf]], dtype=np.float64)
e8i = np.array([[1, 0, 2, 3]], dtype=np.intp)
strict_array_equal(np, d8, e8d, "K08 distances")
strict_array_equal(np, i8, e8i, "K08 indices")
r["observed"] = {
"distances_tokens": [
[raw_distance_token(np, x) for x in row] for row in d8
],
"indices": i8.tolist(),
}
r["decision"] = "ACCEPT"
# K09 all missing.
r = rec("K09", "all_missing")
q9 = np.array([[12.0], [20.0]], dtype=np.float64)
ids9 = ["X12", "X20"]
d9, i9 = query_case(tree, np, q9, 2, 2.5)
e9d = np.array(
[[np.inf, np.inf], [np.inf, np.inf]],
dtype=np.float64,
)
e9i = np.array([[3, 3], [3, 3]], dtype=np.intp)
strict_array_equal(np, d9, e9d, "K09 distances")
strict_array_equal(np, i9, e9i, "K09 indices")
probe9 = PayloadAccessProbe(np, payloads)
dec9 = decode_complete(
np, d9, i9, ids9, [1, 2], source_ids, payloads, probe9
)
if probe9.gather_calls != 0:
raise AssertionError("K09 must perform zero gathers")
r["observed"] = {
"ledger": dec9["ledger"],
"gather_calls": probe9.gather_calls,
}
r["decision"] = "ACCEPT"
# K10 synthetic faults.
faults = [
("finite_n", 1.0, 3),
("inf_valid", np.inf, 0),
("negative_index", 1.0, -1),
("nan_n", np.nan, 3),
]
k10_total_gathers = 0
for subpath, distance, index in faults:
r = rec("K10", subpath)
fd = np.array([[distance]], dtype=np.float64)
fi = np.array([[index]], dtype=np.intp)
probe10 = PayloadAccessProbe(np, payloads)
dec10 = decode_complete(
np,
fd,
fi,
[f"DIAG_{subpath}"],
[1],
source_ids,
payloads,
probe10,
)
k10_total_gathers += probe10.gather_calls
status = dec10["ledger"][0]["status"]
if status != HOLD:
raise AssertionError(f"K10 {subpath} did not HOLD")
r["observed"] = {
"ledger": dec10["ledger"],
"gather_calls": probe10.gather_calls,
}
r["decision"] = "HOLD"
if k10_total_gathers != 0:
raise AssertionError("K10 requires zero gathers across faults")
# Prove retained inputs unchanged.
strict_array_equal(np, source_coords, source_before, "source unchanged")
np.testing.assert_array_equal(source_ids, ids_before, strict=True)
strict_array_equal(np, payloads, payload_before, "payload unchanged")
strict_array_equal(np, main_q, q_before, "query unchanged")
np.testing.assert_array_equal(main_ids, qids_before, strict=True)
check_roster(records)
return {
"batch_date": "2026-11-28",
"status": "EXECUTED",
"environment": env,
"source": {
"revision": SOURCE_REVISION,
"coordinates": SOURCE_COORDS_LITERAL,
"ids": SOURCE_IDS_LITERAL,
"payloads": PAYLOADS_LITERAL,
},
"evidence": records,
}
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--run", action="store_true")
parser.add_argument(
"--output",
default="kdtree_missing_neighbor_evidence.json",
)
args = parser.parse_args()
if not args.run:
document = {
"batch_date": "2026-11-28",
"status": "EXPECTED_NOT_EXECUTED",
"executed": False,
"observed": None,
"selected_versions": {
"python": EXPECTED_PYTHON,
"numpy": EXPECTED_NUMPY,
"scipy": EXPECTED_SCIPY,
},
"source_revision": SOURCE_REVISION,
"query_revision": QUERY_REVISION,
"evidence": expected_only_evidence(),
}
check_roster(document["evidence"])
strict_dump(document, args.output)
return
result = run()
strict_dump(result, args.output)
if name == "__main__":
main()Keep infinity meaningful in strict JSON
Python's JSON documentation notes that the default encoder may emit NaN, Infinity, and -Infinity, even though those numeric literals are outside the JSON specification; allow_nan=False instead raises if such floating values reach the encoder.
The evidence representation therefore converts a missing pair before serialization:
{
"query_id": "X0",
"requested_rank": 2,
"raw_distance_token": "+inf",
"distance": null,
"raw_index": 3,
"status": "MISSING",
"source_id": null,
"payload": null
}Finite distances remain ordinary JSON numbers. A synthetic NaN from K10 is represented with raw_distance_token="NaN" and distance=null; it is never serialized as a JSON numeric NaN.
The pre-execution evidence state is deliberately different:
{
"case_id": "K02",
"subpath_id": "bounded_k2",
"executed": false,
"observed": null,
"exception": null,
"decision": null
}That is the status of this article's laboratory. The supplied matrices and ledgers are EXPECTED / NOT EXECUTED. Metadata inspection on 2026-11-28 reported Python 3.12.14, NumPy 2.3.5, and SciPy 1.17.0, but no numerical run was performed; the Python documentation page consulted for json currently identifies the 3.12 branch separately from that selected runtime.
A real qualification run should retain its actual command, imports, module paths, versions, platform, raw query results, literal expectations, source/query revisions, warnings and exceptions, and checker decisions. Hashes should be recorded only when the corresponding artifacts were actually retained and hashed; no hashes, timing measurements, warning counts, or PASS totals are fabricated here.
Repair the consumer from retained source evidence
Recovery begins from the original source snapshot and query contract, not from a payload array that may already contain substitutions.
Decision | Apply when | Required action |
ACCEPT | Complete declared query/rank roster is present; every pair is correctly classified; matched rows reconcile to retained source identity; missing rows remain missing | Approve that bounded evidence for the stated contract |
REPAIR | Gather logic, shape normalization, rank labeling, or zero-distance filtering is wrong while retained source/query evidence remains sufficient | Correct the consumer and rebuild a separate result |
HOLD | Pair is inconsistent, provenance is incomplete, or required actual-neighbor coverage is unmet | Prevent the affected downstream assignment or publication |
RERUN | Engine/version, source population, bound, norm, rank request, query set, or consumer revision changes | Execute a new qualification against the new contract |
For K03 and K04, the original K02 distance/index evidence is more valuable than the failed or substituted payload candidates. Preserve those candidates as rejected evidence, correct the gather boundary, and regenerate payload assignments only from slots already classified MATCHED.
For a shape bug in K06, repair the adapter while retaining the original k form. For a rank-label bug in K07, restore the metadata [1,3]; do not relabel the numerical second column as rank two. For the K05 positive-distance rule, restore zero as a valid finite distance. For a K10 inconsistent pair, HOLD rather than guessing which side of the pair was intended.
A useful recovery sequence is:
Freeze the retained source coordinates, source IDs, payloads, external query IDs, query coordinates, requested ranks, bound, norm, and engine revision.
Preserve the rejected consumer artifact and its decision; do not overwrite it with a repaired result.
Identify whether the defect is gathering, shape adaptation, requested-rank metadata, pair qualification, or a downstream minimum-neighbor rule.
Correct only that consumer layer. Do not manufacture a payload for a MISSING slot and do not silently widen 2.5 or change k.
Rebuild a new result from the retained source evidence, then reconcile all declared query/rank slots again.
If the scientific request itself changes (new radius, new rank count, new norm, changed population, changed engine, or other excluded behavior), treat it as a new contract and RERUN.
Responsibility should also stay explicit. The scientific or data owner specifies the metric, bound, ranks, and required-neighbor coverage. The implementer owns source binding, shape adaptation, pair decoding, and guarded payload access. An independent reviewer reconciles the manifest against the scalar oracle and checks complete slot coverage.
Correcting code does not undo downstream artifacts that may already have consumed a clipped or wrapped candidate. Those artifacts require their own impact review. This laboratory itself has no external side effects beyond a future run's local evidence file.
The qualification boundary is intentionally narrow. Exact cutoff equality is untested; ties are excluded; approximate eps search is excluded; only p=2, one-dimensional finite float64 coordinates, ordinary arrays, workers=1, and boxsize=None are admitted. There is no basis here for extrapolating the exact-equality checker to arbitrary numerical precision, another norm, high-dimensional behavior, periodic geometry, concurrency, or source mutation.
Build numerical foundations with Refonte Learning Data Science & AI
This KDTree example is specialized, but the engineering habit behind it is broader: numerical APIs are safest when assumptions, source identity, array shape, missingness, and evidence grain are made explicit before downstream data movement.
Refonte Learning's Data Science & AI program page lists a three-month program with a stated 12–14 hours/week and competencies including Python Data Science, Statistical Modelling, EDA, Machine Learning and Predictive Modelling, and Model Optimization & Problem-Solving Techniques. Its FAQ names Python, Jupyter Notebook, Pandas, NumPy, Matplotlib, scikit-learn, and TensorFlow; the page also names Dr. John Anderson as an educational mentor and describes Training and Internship certificates upon successful completion.
The page is not fully internally uniform: its program-specific admission language refers to degree study while the FAQ says there are no strict prerequisites; the main section says three months while the FAQ describes variable duration; explicit certificate language sits alongside more conditional FAQ wording. Confirm the applicable eligibility requirements and terms directly with Refonte Learning. SciPy/KDTree instruction, this laboratory, taught package versions, individual mentoring frequency, and internship allocation also require confirmation and should not be treated as verified benefits.
For structured foundations in numerical Python, statistics, and analytical modeling, review the Data Science & AI program.
