localvectordb.visualization package
Visualization module for LocalVectorDB.
Provides dimensionality reduction, clustering, and plotting utilities for exploring document embedding spaces.
- Optional dependencies:
scikit-learnandmatplotlib(pip install localvectordb[visualization])plotlyfor interactive plots (pip install localvectordb[visualization-interactive])
- localvectordb.visualization.reduce_dimensions(embeddings: ndarray, method: str = 'tsne', n_components: int = 2, doc_ids: List[str] | None = None, **kwargs) EmbeddingProjection
Project high-dimensional embeddings into a lower-dimensional space.
- Parameters:
- Return type:
- localvectordb.visualization.cluster_embeddings(embeddings: ndarray, n_clusters: int | None = None, method: str = 'kmeans', **kwargs) ClusterResult
Cluster embeddings using k-means.
- Parameters:
embeddings (np.ndarray) – (N, D) embeddings.
n_clusters (int, optional) – Number of clusters. If
None, determined automatically viafind_optimal_clusters().method (str) – Clustering method (currently only
"kmeans").**kwargs – Forwarded to
KMeans.
- Return type:
- localvectordb.visualization.find_optimal_clusters(embeddings: ndarray, max_k: int | None = None) int
Determine the optimal number of clusters via silhouette analysis.
- localvectordb.visualization.plot_embedding_map(projection: EmbeddingProjection, color_by: List[str] | None = None, title: str = 'Document Embedding Map', save_path: str | Path | None = None, queries: List[QueryOverlay] | None = None, figsize: tuple = (10, 8), **kwargs) Figure
Scatter plot of projected document embeddings.
- Parameters:
projection (EmbeddingProjection) – Dimensionality-reduced coordinates.
color_by (list of str, optional) – Category labels for colouring each point.
title (str) – Plot title.
save_path (str or Path, optional) – If provided, save figure to this path.
queries (list of QueryOverlay, optional) – Query overlays to display on the map.
figsize (tuple) – Figure size.
- Return type:
matplotlib.figure.Figure
- localvectordb.visualization.plot_similarity_matrix(sim_matrix: DocumentSimilarityMatrix, title: str = 'Document Similarity Matrix', save_path: str | Path | None = None, figsize: tuple | None = None, **kwargs) Figure
Heatmap of pairwise document similarities.
- Parameters:
sim_matrix (DocumentSimilarityMatrix) – Similarity matrix to plot.
title (str) – Plot title.
save_path (str or Path, optional) – Save path.
figsize (tuple, optional) – Figure size. Auto-scaled if
None.
- Return type:
matplotlib.figure.Figure
- localvectordb.visualization.plot_clusters(projection: EmbeddingProjection, clusters: ClusterResult, title: str = 'Document Clusters', save_path: str | Path | None = None, figsize: tuple = (10, 8), **kwargs) Figure
Scatter plot of projected embeddings coloured by cluster.
- Parameters:
projection (EmbeddingProjection) – Dimensionality-reduced coordinates.
clusters (ClusterResult) – Cluster assignments.
title (str) – Plot title.
save_path (str or Path, optional) – Save path.
figsize (tuple) – Figure size.
- Return type:
matplotlib.figure.Figure
- localvectordb.visualization.plot_similarity_graph(sim_matrix: DocumentSimilarityMatrix, threshold: float = 0.3, layout: str = 'spring', title: str = 'Document Similarity Graph', save_path: str | Path | None = None, figsize: tuple = (10, 8), gravity: float | None = None, spread: float | None = None, **kwargs) Figure
Visualise documents as a similarity graph.
Nodes represent documents; edges connect documents with similarity above threshold. Edge width and opacity are proportional to similarity.
Layout uses scikit-learn MDS to avoid a
networkxdependency.- Parameters:
sim_matrix (DocumentSimilarityMatrix) – Pairwise similarity matrix.
threshold (float) – Edge threshold.
layout (str) –
"spring"(default) runs a force-directed Fruchterman-Reingold layout over the thresholded edges, which groups connected documents and pushes unconnected ones apart."mds"instead embeds the full similarity matrix with multidimensional scaling, placing every node by its distance to every other whether or not an edge is drawn.title (str) – Plot title.
save_path (str or Path, optional) – Save path.
figsize (tuple) – Figure size.
gravity (float, optional) – Tuning for
layout="spring"; see_spring_positions(). Both trade legibility against contrast – raising them loosens a densely connected component so node labels stay readable, at the cost of how sharply connected nodes separate from unconnected ones. Ignored forlayout="mds".spread (float, optional) – Tuning for
layout="spring"; see_spring_positions(). Both trade legibility against contrast – raising them loosens a densely connected component so node labels stay readable, at the cost of how sharply connected nodes separate from unconnected ones. Ignored forlayout="mds".
- Return type:
matplotlib.figure.Figure
- Raises:
ValueError – If
layoutis not"spring"or"mds".
- localvectordb.visualization.build_similarity_graph(sim_matrix: DocumentSimilarityMatrix, threshold: float = 0.3) Dict[str, List[Dict[str, Any]]]
Build a graph structure from a similarity matrix.
- Parameters:
sim_matrix (DocumentSimilarityMatrix) – Pairwise document similarity matrix.
threshold (float) – Minimum similarity for an edge to be included.
- Returns:
{"nodes": [...], "edges": [...]}where each node is{"id": str, "index": int}and each edge is{"source": str, "target": str, "weight": float}.- Return type:
- localvectordb.visualization.plot_synteny(chunk_sim: ChunkSimilarityMatrix, similarity_threshold: float = 0.7, orientation: str = 'horizontal', chunk_labels: bool = False, labels_1: Sequence[str] | None = None, labels_2: Sequence[str] | None = None, title: str | None = None, save_path: str | Path | None = None, figsize: tuple | None = None, cmap: str = 'viridis', **kwargs) Figure
Synteny ribbon diagram comparing chunks of two documents.
Two parallel bars represent the documents, with Bezier ribbons connecting chunks of high similarity – analogous to synteny plots in comparative genomics.
- Parameters:
chunk_sim (ChunkSimilarityMatrix) – Full chunk-level similarity matrix.
similarity_threshold (float) – Minimum similarity for a ribbon to be drawn.
orientation (str) –
"horizontal"(doc1 top, doc2 bottom) or"vertical"(doc1 left, doc2 right).chunk_labels (bool) – If
True, label each chunk segment with its index.labels_1 (sequence of str, optional) – Text to draw on each chunk segment of the first/second document, instead of its index – section headings, for instance. Must be exactly one entry per chunk. Supplying either turns labelling on regardless of
chunk_labels, and moves the labels outside the track (index numerals fit inside a segment; a heading does not).labels_2 (sequence of str, optional) – Text to draw on each chunk segment of the first/second document, instead of its index – section headings, for instance. Must be exactly one entry per chunk. Supplying either turns labelling on regardless of
chunk_labels, and moves the labels outside the track (index numerals fit inside a segment; a heading does not).title (str, optional) – Plot title. Auto-generated if
None.save_path (str or Path, optional) – Save figure to this path.
figsize (tuple, optional) – Figure size. Auto-scaled if
None.cmap (str) – Matplotlib colormap for chunk position colouring.
- Return type:
matplotlib.figure.Figure
- Raises:
ValueError – If
labels_1/labels_2do not match the chunk count.
- localvectordb.visualization.plot_chord(chunk_sim: ChunkSimilarityMatrix, similarity_threshold: float = 0.7, min_chunk_distance: int = 3, chunk_labels: bool = False, labels: Sequence[str] | None = None, title: str | None = None, save_path: str | Path | None = None, figsize: tuple = (10, 10), cmap: str = 'viridis', **kwargs) Figure
Chord (Circos-style) diagram for chunk self-similarity.
Chunks are arranged as arcs around a circle with interior ribbons connecting self-similar regions, analogous to Circos plots in genomics.
- Parameters:
chunk_sim (ChunkSimilarityMatrix) – Chunk self-similarity matrix (
doc_id_1 == doc_id_2).similarity_threshold (float) – Minimum similarity for a chord to be drawn.
min_chunk_distance (int) – Minimum index distance between chunks for a chord to be drawn. Filters out trivially similar adjacent chunks.
chunk_labels (bool) – If
True, label each arc segment with its index.labels (sequence of str, optional) – Text to draw on each arc instead of its index – the section each chunk falls in, for instance. Must be exactly one entry per chunk. Supplying it turns labelling on regardless of
chunk_labels, and rotates the labels to follow the circle so long names stay legible.title (str, optional) – Plot title. Auto-generated if
None.save_path (str or Path, optional) – Save figure to this path.
figsize (tuple) – Figure size.
cmap (str) – Matplotlib colormap for chunk position colouring.
- Return type:
matplotlib.figure.Figure
- Raises:
ValueError – If
chunk_simis not a self-comparison, orlabelsdoes not match the chunk count.
- localvectordb.visualization.plot_embedding_map_interactive(*args, **kwargs)
Interactive plotly embedding map. Requires
plotly.
- localvectordb.visualization.plot_similarity_matrix_interactive(*args, **kwargs)
Interactive plotly similarity heatmap. Requires
plotly.
- localvectordb.visualization.plot_clusters_interactive(*args, **kwargs)
Interactive plotly cluster plot. Requires
plotly.
- localvectordb.visualization.plot_synteny_interactive(*args, **kwargs)
Interactive plotly synteny ribbon diagram. Requires
plotly.
- localvectordb.visualization.plot_chord_interactive(*args, **kwargs)
Interactive plotly chord (Circos) diagram. Requires
plotly.
- class localvectordb.visualization.EmbeddingProjection(coordinates: ndarray, method: str, doc_ids: List[str], transformer: Any = None, n_components: int = 2, explained_variance: ndarray | None = None)
Bases:
objectResult of dimensionality reduction.
- Variables:
coordinates (np.ndarray) – (N, n_components) projected coordinates.
method (str) – Reduction method used (
"pca"or"tsne").doc_ids (list of str) – Document IDs corresponding to each row.
transformer (Any) – Fitted transformer object (PCA instance or dict with params). Used to project new points into the same space.
n_components (int) – Number of output dimensions.
explained_variance (Optional[np.ndarray]) – Explained variance ratio (PCA only).
- class localvectordb.visualization.ClusterResult(labels: ndarray, n_clusters: int, centroids: ndarray | None = None, inertia: float | None = None)
Bases:
objectResult of clustering.
- Variables:
- class localvectordb.visualization.QueryOverlay(query_text: str, query_embedding: ndarray, scores: ndarray)
Bases:
objectOverlay for rendering query points on an embedding map.
- Variables:
query_text (str) – The query string (used for legend/labels).
query_embedding (np.ndarray) – (D,) embedding vector of the query.
scores (np.ndarray) – (N,) similarity score per document; used for dot sizing.