fromJson static method

IvfPqIndex fromJson(
  1. Map<String, Object?> j
)

Reconstruct an IvfPqIndex from toJson output.

Implementation

static IvfPqIndex fromJson(Map<String, Object?> j) {
  final dim = (j['dim'] as num).toInt();
  final nlist = (j['nlist'] as num).toInt();
  final m = (j['m'] as num).toInt();
  final idx = IvfPqIndex(
    dim,
    nlist: nlist,
    m: m,
    nprobe: (j['nprobe'] as num?)?.toInt() ?? 1,
  );
  final coarse = _decodeF32Slice(j['coarseCentroids'] as String);
  if (coarse.length != nlist * dim) {
    throw FormatException(
      'IvfPqIndex.fromJson: coarse centroids length ${coarse.length} '
      '!= nlist $nlist * dim $dim',
    );
  }
  idx._coarseQuantizer.centroids = coarse;
  final pqCentroids = _decodeF32Slice(j['pqCentroids'] as String);
  final pqExpected = m * _ProductQuantizer.ksub * (dim ~/ m);
  if (pqCentroids.length != pqExpected) {
    throw FormatException(
      'IvfPqIndex.fromJson: pq centroids length ${pqCentroids.length} '
      '!= $pqExpected',
    );
  }
  idx._pq.centroids = pqCentroids;
  idx._pq.trained = (j['pqTrained'] as bool?) ?? true;
  idx._trained = (j['trained'] as bool?) ?? true;
  idx._n = (j['n'] as num).toInt();
  final cells = (j['cells'] as List).cast<Map>();
  if (cells.length != nlist) {
    throw FormatException(
      'IvfPqIndex.fromJson: cells length ${cells.length} != nlist $nlist',
    );
  }
  for (var c = 0; c < nlist; c++) {
    final cell = cells[c].cast<String, Object?>();
    final count = (cell['count'] as num).toInt();
    idx._cellCounts[c] = count;
    idx._cellIds[c] = (cell['ids'] as List).cast<Object?>().toList();
    idx._cellCodes[c] =
        Uint8List.fromList(base64.decode(cell['codes'] as String));
  }
  return idx;
}