Skip to content

API Reference

The public API consists of two classes: VQFitter, which fits prototypes, and VQRecaller, which computes recall products.

VQFitter

vqlp.VQFitter

VQFitter(
    M, p=2, max_bmu=2, random_state=None, verbose=True
)

Vector Quantizer Fitter using arbitrary Lp distance metrics.

Supports multiple fitting algorithms including random sampling, IRLS (Iteratively Reweighted Least Squares), gradient descent (GD), PAM (Partitioning Around Medoids), and FAISS k-means (p=2 only).

Typical workflow
  1. Instantiate with the desired number of prototypes M and Lp order p::

    fitter = VQFitter(M=20, p=2, random_state=42)

  2. Fit prototypes to a data matrix X of shape (N, d)::

    fitter.fit(X) # defaults to k-means for p=2, IRLS otherwise

  3. Run recall analysis to compute BMU assignments, receptive fields, connectivity, etc. Call with no arguments to analyze the training data, or pass new X to analyze held-out data::

    fitter.recall() # training data fitter.recall(X_test) # new data

  4. Inspect results via the embedded VQRecaller object::

    recaller = fitter.recaller print(recaller.BMU) # shape (N, max_bmu) print(recaller.QE) # quantization errors print(recaller.RFSize) # receptive field sizes print(recaller.CONN) # sparse connectivity matrix

  5. Optionally reconstruct data::

    X_hard = recaller.reconstruct(fitter.W, X, method='hard') X_soft = recaller.reconstruct(fitter.W, X, method='soft')

See VQRecaller for definitions of BMU, QE, RF, CADJ, and CONN.

Initialize the VQ Fitter.

Parameters:

Name Type Description Default
M int

Number of prototypes to create

required
p float

Order of the Lp distance metric (e.g., 1 for Manhattan, 2 for Euclidean)

2
max_bmu int

Number of Best Matching Units (closest prototypes) to track

2
random_state int or None

Seed for the instance-local random number generator. Reproducible results are guaranteed without touching the global NumPy random state, so multiple VQFitter instances with different seeds can coexist safely.

None
verbose bool

If True, print progress messages during fitting and recall. Set to False to suppress all terminal output.

True
Source code in src/vqlp/vq.py
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
def __init__(self, M, p=2, max_bmu=2, random_state=None, verbose=True):
    """
    Initialize the VQ Fitter.

    Parameters
    ----------
    M : int
        Number of prototypes to create
    p : float, default=2
        Order of the Lp distance metric (e.g., 1 for Manhattan, 2 for Euclidean)
    max_bmu : int, default=2
        Number of Best Matching Units (closest prototypes) to track
    random_state : int or None, optional
        Seed for the instance-local random number generator. Reproducible
        results are guaranteed without touching the global NumPy random
        state, so multiple VQFitter instances with different seeds can
        coexist safely.
    verbose : bool, default=True
        If True, print progress messages during fitting and recall.
        Set to False to suppress all terminal output.
    """
    self.M = int(M)
    self.p = p
    self.max_bmu = max_bmu
    self.random_state = random_state
    self.verbose = verbose
    self.W = None  # Prototype matrix (M, d)

    # Use an instance-local Generator rather than np.random.seed(), which
    # would mutate the global NumPy random state and interfere with other
    # code (other VQFitter instances, user code, etc.).
    self._rng = np.random.default_rng(self.random_state)

    # VQRecaller instance for BMU tracking during fitting
    self.recaller = VQRecaller(p=self.p, max_bmu=self.max_bmu, verbose=self.verbose)

fit

fit(X, method=None, distX=None, **kwargs)

Fit the vector quantizer using the specified method.

Defaults to "kmeans" when p=2, and "IRLS" otherwise.

Parameters:

Name Type Description Default
X (array - like, shape(N, d))

Training data matrix

required
method str

Fitting method. One of: ["random", "IRLS", "GD", "PAM", "kmeans"]. Defaults to "kmeans" if p=2, "IRLS" otherwise.

None
distX (array, shape(N, N))

Precomputed distance matrix. If provided, internal distance calculation is skipped (PAM only).

None
**kwargs additional arguments

Method-specific parameters (see individual fit* methods).

{}

Returns:

Name Type Description
self VQFitter

Returns self for method chaining

Source code in src/vqlp/vq.py
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
def fit(self, X, method=None, distX=None, **kwargs):
    """
    Fit the vector quantizer using the specified method.

    Defaults to "kmeans" when p=2, and "IRLS" otherwise.

    Parameters
    ----------
    X : array-like, shape (N, d)
        Training data matrix
    method : str, optional
        Fitting method. One of: ["random", "IRLS", "GD", "PAM", "kmeans"].
        Defaults to "kmeans" if p=2, "IRLS" otherwise.
    distX : array, shape (N, N), optional
        Precomputed distance matrix. If provided, internal distance
        calculation is skipped (PAM only).
    **kwargs : additional arguments
        Method-specific parameters (see individual _fit_* methods).

    Returns
    -------
    self : VQFitter
        Returns self for method chaining
    """
    X = np.array(X)
    N, d = X.shape

    if self.M > N:
        raise ValueError(f"Cannot create {self.M} prototypes from only {N} observations")

    # Choose default method based on p
    if method is None:
        method = "kmeans" if self.p == 2 else "IRLS"

    if method not in self.AVAILABLE_METHODS:
        raise ValueError(f"Unknown fitting method '{method}'. Available methods: {self.AVAILABLE_METHODS}")

    if method == "kmeans" and self.p != 2:
        raise ValueError(f"kmeans only supports p=2 (Euclidean distance), got p={self.p}")

    if method == "random":
        self._fit_random(X)
    elif method == "IRLS":
        self._fit_IRLS(X, **kwargs)
    elif method == "GD":
        self._fit_GD(X, **kwargs)
    elif method == "PAM":
        self._fit_PAM(X, distX=distX, **kwargs)
    elif method == "kmeans":
        self._fit_kmeans(X, **kwargs)

    if self.verbose:
        print(f"Fitting complete using {method} method.")
    return self

set_prototypes

set_prototypes(W, X)

Set the prototype matrix W directly, bypassing fitting.

Useful when prototypes are known in advance (e.g. from a previous run, an external algorithm, or domain-specific initialization) and you want to use the VQFitter machinery for recall analysis or as a warm start for further fitting.

BMU and QE are computed immediately from X, keeping the object in a consistent state — the same guarantee provided by all fit* methods.

Parameters:

Name Type Description Default
W (array - like, shape(M, d))

Prototype matrix. Must have exactly self.M rows. If the data dimensionality d is already known (from a prior fit or recall), W must match it; otherwise d is inferred from W.

required
X (array - like, shape(N, d))

Data matrix used to compute BMU and QE.

required

Returns:

Name Type Description
self VQFitter

Returns self for method chaining

Source code in src/vqlp/vq.py
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
def set_prototypes(self, W, X):
    """
    Set the prototype matrix W directly, bypassing fitting.

    Useful when prototypes are known in advance (e.g. from a previous run,
    an external algorithm, or domain-specific initialization) and you want
    to use the VQFitter machinery for recall analysis or as a warm start
    for further fitting.

    BMU and QE are computed immediately from X, keeping the object in a
    consistent state — the same guarantee provided by all _fit_* methods.

    Parameters
    ----------
    W : array-like, shape (M, d)
        Prototype matrix. Must have exactly self.M rows. If the data
        dimensionality d is already known (from a prior fit or recall),
        W must match it; otherwise d is inferred from W.
    X : array-like, shape (N, d)
        Data matrix used to compute BMU and QE.

    Returns
    -------
    self : VQFitter
        Returns self for method chaining
    """
    W = np.array(W)
    X = np.array(X)

    if W.shape[0] != self.M:
        raise ValueError(
            f"W has {W.shape[0]} prototypes but this fitter expects M={self.M}"
        )

    # Validate d if already known, otherwise infer from W
    known_d = self.W.shape[1] if self.W is not None else None
    if known_d is not None and W.shape[1] != known_d:
        raise ValueError(
            f"W has {W.shape[1]} features but prior data had d={known_d}"
        )
    if X.shape[1] != W.shape[1]:
        raise ValueError(
            f"X has {X.shape[1]} features but W has {W.shape[1]} features"
        )

    self.W = W.copy()
    self.recaller.update_BMU(X, self.W)
    if self.verbose:
        print(f"Prototypes set externally. MQE: {np.mean(self.recaller.QE[:, 0]):.6f}")
    return self

recall

recall(X=None, labels=None)

Perform recall analysis using the fitted prototypes.

This is a convenience wrapper around VQRecaller.recall(). The key difference from calling self.recaller.recall() directly is that W is always taken from self.W (the fitted prototypes), so you never need to pass it explicitly here.

If X is provided, performs recall analysis on new (e.g. held-out) data. If X is None, finalizes recall analysis on the training data (BMU was already updated incrementally during fitting).

Parameters:

Name Type Description Default
X (array - like, shape(N, d))

Data matrix for recall analysis. If None, finalizes training recall.

None
labels (array - like, shape(N))

Observation labels. Any hashable type is accepted (int, str, float, etc.). If provided, recall_labels() is called automatically after the main recall pipeline to compute WL, WL_Dist, and WL_Purity.

None

Returns:

Name Type Description
self VQFitter

Returns self for method chaining.

See Also

VQRecaller.recall : The underlying recall method, which also accepts explicit W and p arguments for use outside of VQFitter.

Source code in src/vqlp/vq.py
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
def recall(self, X=None, labels=None):
    """
    Perform recall analysis using the fitted prototypes.

    This is a convenience wrapper around VQRecaller.recall().
    The key difference from calling self.recaller.recall() directly is
    that W is always taken from self.W (the fitted prototypes), so you
    never need to pass it explicitly here.

    If X is provided, performs recall analysis on new (e.g. held-out) data.
    If X is None, finalizes recall analysis on the training data (BMU was
    already updated incrementally during fitting).

    Parameters
    ----------
    X : array-like, shape (N, d), optional
        Data matrix for recall analysis. If None, finalizes training recall.
    labels : array-like, shape (N,), optional
        Observation labels. Any hashable type is accepted (int, str, float,
        etc.). If provided, recall_labels() is called automatically after
        the main recall pipeline to compute WL, WL_Dist, and WL_Purity.

    Returns
    -------
    self : VQFitter
        Returns self for method chaining.

    See Also
    --------
    VQRecaller.recall : The underlying recall method, which also accepts
        explicit W and p arguments for use outside of VQFitter.
    """
    if self.W is None:
        raise RuntimeError("Model not fitted. Call fit() first.")

    if X is not None:
        X = np.array(X)
        self.recaller.recall(X, self.W, labels=labels)
    else:
        self.recaller.recall(labels=labels)

    return self

save

save(path)

Save the VQFitter (and its embedded VQRecaller) to an HDF5 file.

Parameters:

Name Type Description Default
path str

Destination file path. Created or overwritten.

required
See Also

VQFitter.load : Reconstruct a VQFitter from a saved file. VQRecaller.save : Save a standalone VQRecaller.

Examples:

>>> fitter.save("fitter.h5")
>>> fitter2 = VQFitter.load("fitter.h5")
Source code in src/vqlp/vq.py
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
def save(self, path):
    """
    Save the VQFitter (and its embedded VQRecaller) to an HDF5 file.

    Parameters
    ----------
    path : str
        Destination file path.  Created or overwritten.

    See Also
    --------
    VQFitter.load   : Reconstruct a VQFitter from a saved file.
    VQRecaller.save : Save a standalone VQRecaller.

    Examples
    --------
    >>> fitter.save("fitter.h5")
    >>> fitter2 = VQFitter.load("fitter.h5")
    """
    from .io import VQFitterIO
    VQFitterIO(self).save(path)

load classmethod

load(path)

Load a VQFitter (and its embedded VQRecaller) from an HDF5 file created by :meth:save.

Parameters:

Name Type Description Default
path str

Path to the HDF5 file.

required

Returns:

Type Description
VQFitter

Examples:

>>> fitter = VQFitter.load("fitter.h5")
>>> fitter.W              # prototype matrix
>>> fitter.recaller.BMU   # recall products, if recall() was called before saving
Source code in src/vqlp/vq.py
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
@classmethod
def load(cls, path):
    """
    Load a VQFitter (and its embedded VQRecaller) from an HDF5 file
    created by :meth:`save`.

    Parameters
    ----------
    path : str
        Path to the HDF5 file.

    Returns
    -------
    VQFitter

    Examples
    --------
    >>> fitter = VQFitter.load("fitter.h5")
    >>> fitter.W              # prototype matrix
    >>> fitter.recaller.BMU   # recall products, if recall() was called before saving
    """
    from .io import VQFitterIO
    return VQFitterIO.load(path)

to_dict

to_dict()

Return a plain dict representation of this VQFitter.

Only hyperparameters and the prototype matrix W are included. The embedded recaller is serialized separately by VQFitterIO. The RNG (_rng) is not stored; on load it is re-initialized from random_state.

Returns:

Type Description
dict with keys: M, p, max_bmu, verbose, random_state, W
Source code in src/vqlp/vq.py
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
def to_dict(self):
    """
    Return a plain dict representation of this VQFitter.

    Only hyperparameters and the prototype matrix W are included.
    The embedded recaller is serialized separately by VQFitterIO.
    The RNG (``_rng``) is not stored; on load it is re-initialized
    from ``random_state``.

    Returns
    -------
    dict with keys: M, p, max_bmu, verbose, random_state, W
    """
    return {
        "M":            self.M,
        "p":            self.p,
        "max_bmu":      self.max_bmu,
        "verbose":      self.verbose,
        "random_state": self.random_state,
        "W":            self.W,
    }

from_dict classmethod

from_dict(d)

Reconstruct a VQFitter from a dict produced by :meth:to_dict.

Bypasses __init__ so that hyperparameters are restored directly. The RNG is re-initialized from random_state.

Note: recaller is set to None by this method. :meth:VQFitterIO.load attaches the reconstructed VQRecaller after calling from_dict. If you call from_dict directly, you are responsible for setting obj.recaller before calling any method that depends on it.

Parameters:

Name Type Description Default
d dict

As returned by :meth:to_dict.

required

Returns:

Type Description
VQFitter
Source code in src/vqlp/vq.py
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
@classmethod
def from_dict(cls, d):
    """
    Reconstruct a VQFitter from a dict produced by :meth:`to_dict`.

    Bypasses ``__init__`` so that hyperparameters are restored directly.
    The RNG is re-initialized from ``random_state``.

    Note: ``recaller`` is set to ``None`` by this method.
    :meth:`VQFitterIO.load` attaches the reconstructed VQRecaller after
    calling ``from_dict``.  If you call ``from_dict`` directly, you are
    responsible for setting ``obj.recaller`` before calling any method
    that depends on it.

    Parameters
    ----------
    d : dict
        As returned by :meth:`to_dict`.

    Returns
    -------
    VQFitter
    """
    obj              = cls.__new__(cls)
    obj.M            = int(d["M"])
    obj.p            = float(d["p"])
    obj.max_bmu      = int(d["max_bmu"])
    obj.verbose      = bool(d["verbose"])
    obj.random_state = d.get("random_state")
    obj.W            = d.get("W")
    obj._rng         = np.random.default_rng(obj.random_state)
    obj.recaller     = None   # attached by VQFitterIO.load()
    return obj

get_summary

get_summary()

Get a summary of the fitted model and recall analysis.

Returns:

Type Description
dict

Summary statistics. Keys always present: - "fitted" : bool — whether prototypes have been computed - "M" : int — number of prototypes - "d" : int or None — feature dimensionality (None if not yet fitted) - "p_norm" : float — Lp order - "max_bmu" : int — number of BMUs tracked - "random_state" : int or None — seed used

If recall() has been called, all keys from VQRecaller.get_summary() are also included (MQE, RF sizes, connectivity stats, etc.).

Source code in src/vqlp/vq.py
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
def get_summary(self):
    """
    Get a summary of the fitted model and recall analysis.

    Returns
    -------
    dict
        Summary statistics.  Keys always present:
          - ``"fitted"`` : bool — whether prototypes have been computed
          - ``"M"`` : int — number of prototypes
          - ``"d"`` : int or None — feature dimensionality (None if not yet fitted)
          - ``"p_norm"`` : float — Lp order
          - ``"max_bmu"`` : int — number of BMUs tracked
          - ``"random_state"`` : int or None — seed used

        If recall() has been called, all keys from VQRecaller.get_summary()
        are also included (MQE, RF sizes, connectivity stats, etc.).
    """
    summary = {
        "fitted": self.W is not None,
        "M": self.M,
        "d": self.W.shape[1] if self.W is not None else None,
        "p_norm": self.p,
        "max_bmu": self.max_bmu,
        "random_state": self.random_state
    }

    if self.recaller.BMU is not None:
        recall_summary = self.recaller.get_summary()
        summary.update(recall_summary)

    return summary

VQRecaller

vqlp.VQRecaller

VQRecaller(
    p=2,
    max_bmu=2,
    index_type="flat",
    nlist=None,
    nprobe=None,
    verbose=True,
)

Recall analysis for Vector Quantizer results.

Computes and stores analysis products from applying a set of prototypes to data, including Best Matching Units, connectivity matrices, receptive fields, and reconstruction capabilities.

Nearest-prototype search is performed via FAISS, which supports arbitrary Lp metrics. Both exact (flat) and approximate (IVF) search are available via the index_type parameter.

Note: FAISS operates in float32 internally. Input data is cast to float32 for the search step regardless of input dtype.

Terminology

Prototype (W[m]) : One of M representative vectors in feature space, also called a codebook vector or neuron. Shape (d,). BMU (Best Matching Unit) : The prototype closest to a given observation under the chosen Lp metric. A 2nd BMU, 3rd BMU, etc. are the next closest prototypes. Controlled by max_bmu. QE (Quantization Error) : The Lp distance from an observation to its assigned BMU. Lower is better; zero means the observation sits exactly on a prototype. RF (Receptive Field) : The set of observations for which a given prototype is the 1st BMU. Analogous to a Voronoi cell. RFSize : The number of observations in each prototype's receptive field. A prototype with RFSize == 0 is "dead" (no data point maps to it). CADJ (Co-Adjacency matrix) : An M×M integer matrix where CADJ[i, j] counts the number of observations whose 1st BMU is prototype i and whose 2nd BMU is prototype j. Asymmetric by construction. Encodes the directed manifold neighborhood of the codebook. CONN (Connectivity matrix) : The symmetric version of CADJ: CONN = CADJ + CADJ^T. Used for undirected neighborhood queries. CONN[i, j] > 0 means prototypes i and j are topological neighbors.

Initialize VQRecaller.

Parameters:

Name Type Description Default
p float

Order of the Lp distance metric. Any positive value is supported for exact search (index_type="flat"). Approximate search (index_type="ivf") is restricted to p in {1, 2}.

2
max_bmu int

Number of Best Matching Units to track for each observation

2
index_type str

FAISS index type for nearest-neighbor search: - "flat": Exact brute-force search via IndexFlat. Correct for any p and recommended for codebooks up to a few thousand prototypes, and for any iterative fitting loop. - "ivf": Approximate search via IndexIVFFlat. Useful for very large codebooks where exact search is a bottleneck. Not suitable for iterative fitting (non-deterministic assignments interfere with convergence) and restricted to p in {1, 2}.

"flat"
nlist int

(IVF only) Number of Voronoi cells. Defaults to sqrt(M).

None
nprobe int

(IVF only) Number of cells searched at query time. Higher values give better recall at the cost of speed. Defaults to nlist // 10.

None
verbose bool

If True, print progress messages during recall analysis. Set to False to suppress all terminal output.

True
Source code in src/vqlp/vq.py
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
def __init__(self, p=2, max_bmu=2, index_type="flat", nlist=None, nprobe=None, verbose=True):
    """
    Initialize VQRecaller.

    Parameters
    ----------
    p : float, default=2
        Order of the Lp distance metric. Any positive value is supported
        for exact search (index_type="flat"). Approximate search
        (index_type="ivf") is restricted to p in {1, 2}.
    max_bmu : int, default=2
        Number of Best Matching Units to track for each observation
    index_type : str, default="flat"
        FAISS index type for nearest-neighbor search:
        - "flat": Exact brute-force search via IndexFlat. Correct for any
          p and recommended for codebooks up to a few thousand prototypes,
          and for any iterative fitting loop.
        - "ivf": Approximate search via IndexIVFFlat. Useful for very
          large codebooks where exact search is a bottleneck. Not suitable
          for iterative fitting (non-deterministic assignments interfere
          with convergence) and restricted to p in {1, 2}.
    nlist : int, optional
        (IVF only) Number of Voronoi cells. Defaults to sqrt(M).
    nprobe : int, optional
        (IVF only) Number of cells searched at query time. Higher values
        give better recall at the cost of speed. Defaults to nlist // 10.
    verbose : bool, default=True
        If True, print progress messages during recall analysis.
        Set to False to suppress all terminal output.
    """
    if index_type not in ("flat", "ivf"):
        raise ValueError(f"index_type must be 'flat' or 'ivf', got {index_type!r}")
    if index_type == "ivf" and p not in (1, 2):
        raise ValueError(
            f"Approximate (IVF) search supports only p in {{1, 2}}, got p={p}. "
            f"Use index_type='flat' for exotic Lp metrics."
        )

    # Model parameters
    self.p = p
    self.max_bmu = max_bmu
    self.index_type = index_type
    self.nlist = nlist
    self.nprobe = nprobe
    self.verbose = verbose

    # Recall products (computed by recall())
    self.BMU = None          # Best Matching Unit indices (N, max_bmu)
    self.QE = None           # Quantization Errors (N, max_bmu)
    self.AFF = None          # Affinities (N, max_bmu): Neuralware-form soft weights from QE
    self.RF = None           # Receptive Field: list of observation indices per prototype
    self.RFSize = None       # Size of Receptive Field per prototype
    self.CONN = None         # Connectivity matrix (sparse, symmetric)
    self.CONN_nhbs = None    # List of nonzero indices for each row of CONN
    self.CONN_nhbs_size = None  # Size of each CONN_nhbs[i] as numpy array
    self.CADJ = None         # Asymmetric co-adjacency matrix (sparse); CONN = CADJ + CADJ^T
    self.CADJ_nhbs = None    # List of nonzero indices for each row of CADJ
    self.CADJ_nhbs_size = None  # Size of each CADJ_nhbs[i] as numpy array

    # Label recall products (computed by recall_labels())
    self.WL = None           # Winning label per prototype, object array (M,); None for empty RFs
    self.WL_Dist = None      # Fuzzy label frequency table (M, n_unique_labels), row-normalized
    self.WL_Purity = None    # Hellinger-based purity score per prototype (M,)
    self.WL_unq = None       # Sorted unique label values; column j of WL_Dist corresponds to WL_unq[j]

    # Store shape info for validation (don't store X itself)
    self._M = None           # Number of prototypes
    self._N = None           # Number of observations
    self._d = None           # Dimensionality

recall

recall(X=None, W=None, p=None, max_bmu=None, labels=None)

Perform recall analysis. Can operate in two modes:

Mode 1 - Full analysis: Provide X and W to compute everything from scratch Mode 2 - Finalize: Provide no arguments to compute derived quantities from existing BMU/QE (assumes update_BMU() was called)

Parameters:

Name Type Description Default
X (array - like, shape(N, d))

Data matrix with N observations and d features

None
W (array - like, shape(M, d), optional)

Prototype matrix with M prototypes and d features

None
p float

Lp distance order. If None, uses self.p

None
max_bmu int

Number of BMUs to track. If None, uses self.max_bmu

None
labels (array - like, shape(N))

Observation labels. Any hashable type is accepted (int, str, float, etc.). If provided, recall_labels() is called automatically after the main recall pipeline. Can also be called independently via recall_labels() on an already-recalled object.

None

Returns:

Name Type Description
self VQRecaller

Returns self for method chaining

Source code in src/vqlp/vq.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
def recall(self, X=None, W=None, p=None, max_bmu=None, labels=None):
    """
    Perform recall analysis. Can operate in two modes:

    Mode 1 - Full analysis: Provide X and W to compute everything from scratch
    Mode 2 - Finalize: Provide no arguments to compute derived quantities 
                      from existing BMU/QE (assumes update_BMU() was called)

    Parameters
    ----------
    X : array-like, shape (N, d), optional
        Data matrix with N observations and d features
    W : array-like, shape (M, d), optional  
        Prototype matrix with M prototypes and d features
    p : float, optional
        Lp distance order. If None, uses self.p
    max_bmu : int, optional
        Number of BMUs to track. If None, uses self.max_bmu
    labels : array-like, shape (N,), optional
        Observation labels. Any hashable type is accepted (int, str, float,
        etc.). If provided, recall_labels() is called automatically after
        the main recall pipeline. Can also be called independently via
        recall_labels() on an already-recalled object.

    Returns
    -------
    self : VQRecaller
        Returns self for method chaining
    """
    # Update parameters if provided
    if p is not None:
        if self.index_type == "ivf" and p not in (1, 2):
            raise ValueError(
                f"Approximate (IVF) search supports only p in {{1, 2}}, got p={p}."
            )
        self.p = p
    if max_bmu is not None:
        self.max_bmu = max_bmu

    # Mode 1: Full analysis from scratch
    if X is not None and W is not None:
        self.update_BMU(X, W)

    # Mode 2: Finalize existing BMU/QE
    elif X is None and W is None:
        # Validate that BMU and QE exist and are consistent
        if self.BMU is None or self.QE is None:
            raise RuntimeError("BMU and QE must be populated first. Call update_BMU() or provide X and W.")
        if self.BMU.shape != self.QE.shape:
            raise RuntimeError(f"BMU shape {self.BMU.shape} doesn't match QE shape {self.QE.shape}")
        if self._N is None or self._M is None:
            raise RuntimeError("Shape information missing. Call update_BMU() first.")

    # Invalid: partial arguments provided
    else:
        raise ValueError("Either provide both X and W, or neither (to finalize existing BMU/QE)")

    # Compute the derived recall products (cheap operations)
    self._compute_receptive_fields()
    self._compute_connectivity_matrix()

    if labels is not None:
        self.recall_labels(labels)

    if self.verbose:
        print(f"Recall analysis complete. MQE: {np.mean(self.QE[:, 0]):.6f}")
    return self

update_BMU

update_BMU(X, W)

Update Best Matching Units (BMU) and Quantization Errors (QE) via FAISS.

This is the computationally expensive part of recall analysis. Can be called repeatedly during iterative fitting algorithms.

Parameters:

Name Type Description Default
X (array - like, shape(N, d))

Data matrix with N observations and d features

required
W (array - like, shape(M, d))

Prototype matrix with M prototypes and d features

required
Source code in src/vqlp/vq.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
def update_BMU(self, X, W):
    """
    Update Best Matching Units (BMU) and Quantization Errors (QE) via FAISS.

    This is the computationally expensive part of recall analysis.
    Can be called repeatedly during iterative fitting algorithms.

    Parameters
    ----------
    X : array-like, shape (N, d)
        Data matrix with N observations and d features
    W : array-like, shape (M, d)
        Prototype matrix with M prototypes and d features
    """
    X = np.array(X)
    W = np.array(W)

    # Store shape info for validation
    self._N, self._d = X.shape
    self._M = W.shape[0]

    if W.shape[1] != self._d:
        raise ValueError(f"W has {W.shape[1]} features but X has {self._d} features")
    if self.max_bmu > self._M:
        raise ValueError(f"max_bmu={self.max_bmu} exceeds number of prototypes M={self._M}")

    # FAISS requires float32 and contiguous arrays
    X_f32 = np.ascontiguousarray(X, dtype=np.float32)
    W_f32 = np.ascontiguousarray(W, dtype=np.float32)

    index = self._build_index(W_f32)
    distances, indices = index.search(X_f32, self.max_bmu)

    self.BMU = indices.astype(int)
    self.QE = distances.astype(X.dtype)
    self._compute_affinity()

recall_labels

recall_labels(labels)

Compute per-prototype label summaries from observation labels.

Must be called after update_BMU() (or recall()) so that self.BMU, self.AFF, self.RF, and self.RFSize are available.

For each observation i, its label receives fractional credit distributed across all max_bmu prototypes in proportion to their affinity weights (self.AFF[i, :]). This produces a fuzzy frequency table (WL_Dist) whose rows are then normalized to probability distributions. The winning label per prototype is the argmax of that distribution, and purity is derived from the Hellinger distance between the distribution and the ideal one-hot encoding of the winner.

This mirrors VQRecallLabels_worker / cpp_RecallLabels() from AnnoyVQRecall.hpp.

Parameters:

Name Type Description Default
labels (array - like, shape(N))

Observation labels. Any hashable type is accepted (int, str, float, etc.). Length must equal the number of observations used in the most recent update_BMU() / recall() call.

required

Returns:

Name Type Description
self VQRecaller

Returns self for method chaining.

Attributes set

WL : np.ndarray of object, shape (M,) Winning label for each prototype. None for prototypes whose receptive field is empty (RFSize == 0). WL_Dist : np.ndarray of float, shape (M, n_unique_labels) Row-normalized fuzzy label frequency table. Column j corresponds to WL_unq[j]. Rows for empty RFs are all-zero. WL_Purity : np.ndarray of float, shape (M,) Hellinger-based purity score in [0, 1]. 1 means all affinity mass falls on a single label; 0 for empty RFs. WL_unq : np.ndarray, shape (n_unique_labels,) Sorted unique label values. Use to interpret WL_Dist columns.

Source code in src/vqlp/vq.py
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def recall_labels(self, labels):
    """
    Compute per-prototype label summaries from observation labels.

    Must be called after update_BMU() (or recall()) so that self.BMU,
    self.AFF, self.RF, and self.RFSize are available.

    For each observation i, its label receives fractional credit distributed
    across all max_bmu prototypes in proportion to their affinity weights
    (self.AFF[i, :]). This produces a fuzzy frequency table (WL_Dist) whose
    rows are then normalized to probability distributions. The winning label
    per prototype is the argmax of that distribution, and purity is derived
    from the Hellinger distance between the distribution and the ideal
    one-hot encoding of the winner.

    This mirrors VQRecallLabels_worker / cpp_RecallLabels() from
    AnnoyVQRecall.hpp.

    Parameters
    ----------
    labels : array-like, shape (N,)
        Observation labels. Any hashable type is accepted (int, str,
        float, etc.). Length must equal the number of observations used
        in the most recent update_BMU() / recall() call.

    Returns
    -------
    self : VQRecaller
        Returns self for method chaining.

    Attributes set
    --------------
    WL : np.ndarray of object, shape (M,)
        Winning label for each prototype. None for prototypes whose
        receptive field is empty (RFSize == 0).
    WL_Dist : np.ndarray of float, shape (M, n_unique_labels)
        Row-normalized fuzzy label frequency table. Column j corresponds
        to WL_unq[j]. Rows for empty RFs are all-zero.
    WL_Purity : np.ndarray of float, shape (M,)
        Hellinger-based purity score in [0, 1]. 1 means all affinity mass
        falls on a single label; 0 for empty RFs.
    WL_unq : np.ndarray, shape (n_unique_labels,)
        Sorted unique label values. Use to interpret WL_Dist columns.
    """
    if self.BMU is None or self.AFF is None:
        raise RuntimeError(
            "BMU and AFF must be populated first. Call update_BMU() or recall() before recall_labels()."
        )

    labels = np.asarray(labels)
    if labels.shape[0] != self._N:
        raise ValueError(
            f"labels has {labels.shape[0]} entries but recall used {self._N} observations."
        )

    # Discover label universe and build index map {label -> col index}
    WL_unq, label_indices = np.unique(labels, return_inverse=True)
    n_labels = len(WL_unq)

    # Accumulate fuzzy frequency table via scatter-add.
    # For each of the max_bmu columns k, every observation i contributes
    # AFF[i, k] to the cell (BMU[i, k], label_col_of_i).
    WL_Dist = np.zeros((self._M, n_labels), dtype=float)
    for k in range(self.max_bmu):
        proto_indices = self.BMU[:, k]          # shape (N,)
        aff_weights   = self.AFF[:, k]          # shape (N,)
        # Scatter-add: WL_Dist[proto_indices[i], label_indices[i]] += aff_weights[i]
        np.add.at(WL_Dist, (proto_indices, label_indices), aff_weights)

    # Row-normalize to get probability distributions; leave empty-RF rows as zeros
    row_sums = WL_Dist.sum(axis=1, keepdims=True)
    active = (row_sums > 0).ravel()             # boolean mask of non-empty RFs
    WL_Dist[active] /= row_sums[active]

    # Winning label and Hellinger purity
    WL = np.empty(self._M, dtype=object)        # object dtype accepts any label type
    WL[:] = None                                 # default: no label for empty RFs
    WL_Purity = np.zeros(self._M, dtype=float)

    winner_cols = np.argmax(WL_Dist, axis=1)    # shape (M,); 0 for empty rows (harmless)
    for i in np.where(active)[0]:
        WL[i] = WL_unq[winner_cols[i]]
        p_winner = WL_Dist[i, winner_cols[i]]
        # Hellinger distance between the prototype's label distribution q
        # and the ideal one-hot e_winner is:
        #   H(q, e) = (1/sqrt(2)) * sqrt( sum_k (sqrt(q_k) - sqrt(e_k))^2 )
        # For a one-hot e_winner the sum collapses to:
        #   H^2 * 2 = (sqrt(p_winner) - 1)^2 + (1 - p_winner)
        #           = 2 - 2*sqrt(p_winner)
        # => H = sqrt(1 - sqrt(p_winner))
        # Purity is defined as 1 - H, so it equals 1 for a pure prototype
        # (all mass on one label) and 0 for an empty RF.
        hell_dist = np.sqrt(max(0.0, 1.0 - np.sqrt(p_winner)))
        WL_Purity[i] = 1.0 - hell_dist

    self.WL      = WL
    self.WL_Dist = WL_Dist
    self.WL_Purity = WL_Purity
    self.WL_unq  = WL_unq

    n_labeled = int(active.sum())
    if self.verbose:
        print(
            f"Label recall complete. {n_labeled}/{self._M} prototypes labeled "
            f"({n_labels} unique labels). Mean purity: {WL_Purity[active].mean():.4f}"
        )
    return self

reconstruct

reconstruct(W, X, method='hard')

Reconstruct data using the quantizer.

Parameters:

Name Type Description Default
W (array - like, shape(M, d))

Prototype matrix with M prototypes and d features

required
X (array - like, shape(N, d))

Data matrix to reconstruct with N observations and d features

required
method str

Reconstruction method: - "hard": Use closest prototype for each observation (respects self.p) - "soft": Weighted average using UMAP-style local connectivity. Always uses Euclidean (L2) distances internally; see _reconstruct_soft for rationale.

"hard"

Returns:

Type Description
np.ndarray : Reconstructed data with shape (N, d)
Source code in src/vqlp/vq.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
def reconstruct(self, W, X, method="hard"):
    """
    Reconstruct data using the quantizer.

    Parameters
    ----------
    W : array-like, shape (M, d)
        Prototype matrix with M prototypes and d features
    X : array-like, shape (N, d)
        Data matrix to reconstruct with N observations and d features
    method : str, default="hard"
        Reconstruction method:
        - "hard": Use closest prototype for each observation (respects self.p)
        - "soft": Weighted average using UMAP-style local connectivity.
          Always uses Euclidean (L2) distances internally; see
          _reconstruct_soft for rationale.

    Returns
    -------
    np.ndarray : Reconstructed data with shape (N, d)
    """
    if self.BMU is None:
        raise RuntimeError("Must call recall() before reconstruct()")

    W = np.array(W)
    X = np.array(X)

    # Validate dimensions
    if W.shape[0] != self._M:
        raise ValueError(f"W has {W.shape[0]} prototypes but recall used {self._M}")
    if X.shape[0] != self._N:
        raise ValueError(f"X has {X.shape[0]} observations but recall used {self._N}")
    if X.shape[1] != self._d or W.shape[1] != self._d:
        raise ValueError(f"Dimension mismatch: expected d={self._d}")

    if method == "hard":
        return self._reconstruct_hard(X, W)
    elif method == "soft":
        return self._reconstruct_soft(X, W)
    else:
        raise ValueError(f"Unknown reconstruction method: {method}")

save

save(path)

Save the VQRecaller to an HDF5 file.

Parameters:

Name Type Description Default
path str

Destination file path. Created or overwritten.

required
See Also

VQRecaller.load : Reconstruct a VQRecaller from a saved file.

Examples:

>>> recaller.save("recaller.h5")
>>> recaller2 = VQRecaller.load("recaller.h5")
Source code in src/vqlp/vq.py
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
def save(self, path):
    """
    Save the VQRecaller to an HDF5 file.

    Parameters
    ----------
    path : str
        Destination file path.  Created or overwritten.

    See Also
    --------
    VQRecaller.load : Reconstruct a VQRecaller from a saved file.

    Examples
    --------
    >>> recaller.save("recaller.h5")
    >>> recaller2 = VQRecaller.load("recaller.h5")
    """
    from .io import VQRecallerIO
    VQRecallerIO(self).save(path)

load classmethod

load(path)

Load a VQRecaller from an HDF5 file created by :meth:save.

Parameters:

Name Type Description Default
path str

Path to the HDF5 file.

required

Returns:

Type Description
VQRecaller

Examples:

>>> recaller = VQRecaller.load("recaller.h5")
Source code in src/vqlp/vq.py
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
@classmethod
def load(cls, path):
    """
    Load a VQRecaller from an HDF5 file created by :meth:`save`.

    Parameters
    ----------
    path : str
        Path to the HDF5 file.

    Returns
    -------
    VQRecaller

    Examples
    --------
    >>> recaller = VQRecaller.load("recaller.h5")
    """
    from .io import VQRecallerIO
    return VQRecallerIO.load(path)

get_summary

get_summary()

Get a summary of the recall analysis results.

Returns:

Type Description
dict

Summary statistics with the following keys:

Always present after recall(): - "M" : int — number of prototypes - "N" : int — number of observations - "d" : int — feature dimensionality - "p_norm" : float — Lp order used - "max_bmu" : int — number of BMUs tracked - "index_type" : str — FAISS index type used - "mean_quantization_error" : float — mean QE over 1st BMUs - "empty_prototypes" : int — number of prototypes with no observations - "largest_rf_size" : int — size of the largest receptive field - "connectivity_edges" : int — number of unique CONN edges (nnz // 2) - "mean_connectivity_degree" : float — mean number of CONN neighbors - "max_connectivity_degree" : int — max number of CONN neighbors

Present only after recall_labels(): - "n_unique_labels" : int - "labeled_prototypes" : int — prototypes with non-empty RF - "mean_label_purity" : float — Hellinger-based purity, mean over active prototypes - "min_label_purity" : float — worst-case purity over active prototypes

Source code in src/vqlp/vq.py
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
def get_summary(self):
    """
    Get a summary of the recall analysis results.

    Returns
    -------
    dict
        Summary statistics with the following keys:

        Always present after recall():
          - ``"M"`` : int — number of prototypes
          - ``"N"`` : int — number of observations
          - ``"d"`` : int — feature dimensionality
          - ``"p_norm"`` : float — Lp order used
          - ``"max_bmu"`` : int — number of BMUs tracked
          - ``"index_type"`` : str — FAISS index type used
          - ``"mean_quantization_error"`` : float — mean QE over 1st BMUs
          - ``"empty_prototypes"`` : int — number of prototypes with no observations
          - ``"largest_rf_size"`` : int — size of the largest receptive field
          - ``"connectivity_edges"`` : int — number of unique CONN edges (nnz // 2)
          - ``"mean_connectivity_degree"`` : float — mean number of CONN neighbors
          - ``"max_connectivity_degree"`` : int — max number of CONN neighbors

        Present only after recall_labels():
          - ``"n_unique_labels"`` : int
          - ``"labeled_prototypes"`` : int — prototypes with non-empty RF
          - ``"mean_label_purity"`` : float — Hellinger-based purity, mean over active prototypes
          - ``"min_label_purity"`` : float — worst-case purity over active prototypes
    """
    if self.BMU is None:
        return {"status": "No recall analysis performed"}

    summary = {
        "M": self._M,                    # Number of prototypes
        "N": self._N,                    # Number of observations  
        "d": self._d,                    # Dimensionality
        "p_norm": self.p,
        "max_bmu": self.max_bmu,
        "index_type": self.index_type,
        "mean_quantization_error": np.mean(self.QE[:, 0]),
        "empty_prototypes": np.sum(self.RFSize == 0),
        "largest_rf_size": np.max(self.RFSize) if self.RFSize is not None else 0,
        "connectivity_edges": self.CONN.nnz // 2 if self.CONN is not None else 0,
        "mean_connectivity_degree": np.mean(self.CONN_nhbs_size) if self.CONN_nhbs_size is not None else 0,
        "max_connectivity_degree": np.max(self.CONN_nhbs_size) if self.CONN_nhbs_size is not None else 0,
    }

    if self.WL is not None:
        active = self.RFSize > 0
        summary.update({
            "n_unique_labels":       len(self.WL_unq),
            "labeled_prototypes":    int(active.sum()),
            "mean_label_purity":     float(self.WL_Purity[active].mean()) if active.any() else float("nan"),
            "min_label_purity":      float(self.WL_Purity[active].min())  if active.any() else float("nan"),
        })

    return summary

to_dict

to_dict()

Return a plain dict representation of this VQRecaller.

All values are Python/numpy primitives (arrays, sparse matrices, ragged lists, scalars, or None) — no HDF5 types. Intended for use with VQRecallerIO, which handles HDF5 encoding via _write_dict.

Returns:

Type Description
dict
Source code in src/vqlp/vq.py
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
def to_dict(self):
    """
    Return a plain dict representation of this VQRecaller.

    All values are Python/numpy primitives (arrays, sparse matrices,
    ragged lists, scalars, or None) — no HDF5 types.  Intended for use
    with VQRecallerIO, which handles HDF5 encoding via _write_dict.

    Returns
    -------
    dict
    """
    d = {
        # Hyperparameters
        "p":          self.p,
        "max_bmu":    self.max_bmu,
        "index_type": self.index_type,
        "verbose":    self.verbose,
        "nlist":      self.nlist,
        "nprobe":     self.nprobe,
        # Shape metadata
        "_M": self._M,
        "_N": self._N,
        "_d": self._d,
        # Dense arrays (None if not yet recalled)
        "BMU":            self.BMU,
        "QE":             self.QE,
        "AFF":            self.AFF,
        "RFSize":         self.RFSize,
        "WL_Dist":        self.WL_Dist,
        "WL_Purity":      self.WL_Purity,
        "CADJ_nhbs_size": self.CADJ_nhbs_size,
        "CONN_nhbs_size": self.CONN_nhbs_size,
        # Object array with None entries (WL)
        "WL":     self.WL,
        "WL_unq": self.WL_unq,
        # Sparse matrices
        "CADJ": self.CADJ,
        "CONN": self.CONN,
        # Ragged lists
        "RF":        self.RF,
        "CADJ_nhbs": self.CADJ_nhbs,
        "CONN_nhbs": self.CONN_nhbs,
    }
    return d

from_dict classmethod

from_dict(d)

Reconstruct a VQRecaller from a dict produced by :meth:to_dict.

Bypasses __init__ so that all saved attributes are restored directly without re-running any computation.

Parameters:

Name Type Description Default
d dict

As returned by :meth:to_dict.

required

Returns:

Type Description
VQRecaller
Source code in src/vqlp/vq.py
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
@classmethod
def from_dict(cls, d):
    """
    Reconstruct a VQRecaller from a dict produced by :meth:`to_dict`.

    Bypasses ``__init__`` so that all saved attributes are restored
    directly without re-running any computation.

    Parameters
    ----------
    d : dict
        As returned by :meth:`to_dict`.

    Returns
    -------
    VQRecaller
    """
    obj = cls.__new__(cls)

    # Hyperparameters
    obj.p          = float(d["p"])
    obj.max_bmu    = int(d["max_bmu"])
    obj.index_type = str(d["index_type"])
    obj.verbose    = bool(d["verbose"])
    obj.nlist      = d.get("nlist")
    obj.nprobe     = d.get("nprobe")

    # Shape metadata (-1 sentinel → None for missing values)
    def _int_or_none(v):
        v = int(v) if v is not None else -1
        return None if v == -1 else v

    obj._M = _int_or_none(d.get("_M"))
    obj._N = _int_or_none(d.get("_N"))
    obj._d = _int_or_none(d.get("_d"))

    # Dense arrays
    for name in ("BMU", "QE", "AFF", "RFSize",
                 "WL_Dist", "WL_Purity", "CADJ_nhbs_size", "CONN_nhbs_size"):
        setattr(obj, name, d.get(name))

    # WL (object array with possible None entries)
    obj.WL = d.get("WL")

    # WL_unq: type is preserved by _write_label_array / _read_label_array
    # so no casting is needed here
    obj.WL_unq = d.get("WL_unq")

    # Sparse matrices
    obj.CADJ = d.get("CADJ")
    obj.CONN = d.get("CONN")

    # Ragged lists
    obj.RF        = d.get("RF")
    obj.CADJ_nhbs = d.get("CADJ_nhbs")
    obj.CONN_nhbs = d.get("CONN_nhbs")

    return obj