fromJson static method

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

Reconstruct an IvfFlatIndex from toJson output.

Implementation

static IvfFlatIndex fromJson(Map<String, Object?> j) {
  final dim = (j['dim'] as num).toInt();
  final metric = VectorMetric.values.firstWhere(
    (m) => m.name == j['metric'],
    orElse: () => VectorMetric.l2sq,
  );
  final nlist = (j['nlist'] as num).toInt();
  final idx = IvfFlatIndex(
    dim,
    nlist: nlist,
    nprobe: (j['nprobe'] as num?)?.toInt() ?? 1,
    defaultMetric: metric,
  );
  final centroids = _decodeF32Slice(j['centroids'] as String);
  if (centroids.length != nlist * dim) {
    throw FormatException(
      'IvfFlatIndex.fromJson: centroids length ${centroids.length} '
      '!= nlist $nlist * dim $dim',
    );
  }
  idx._quantizer.centroids = centroids;
  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(
      'IvfFlatIndex.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._cellVecs[c] = _decodeF32Slice(cell['vecs'] as String);
  }
  return idx;
}