API Reference
Main Package
Graph Builders
ts2net public API — four graph builders and a factory function.
Primary interface: builder.build(x) — builds and returns self.
Sklearn interface: builder.fit_transform(x) — returns NetworkX graph.
Split interface: builder.fit(x).transform() — deprecated; prefer build().
- All builders share the same output methods after build():
.n_nodes int .n_edges int .degree_sequence() NDArray[int64] .adjacency_matrix() sparse CSR (default) or dense .stats() dict of summary metrics .as_networkx() nx.Graph (optional; large graphs refused unless force=True)
- class ts2net.api.HVG(weighted=False, limit=None, only_degrees=False, output='edges', directed=False, weight_mode=None)[source]
Bases:
objectHorizontal Visibility Graph (HVG).
Two nodes i < j are connected if every intermediate value is strictly below the lower of the two endpoints:
x[k] < min(x[i], x[j]) for all i < k < j
Complexity: O(n) time and space (monotone stack algorithm).
Key invariants (random i.i.d. series): - Mean degree → 4 as n → ∞ (Luque et al. 2009) - Degree distribution follows P(k) ~ (1/3)(2/3)^(k-2) for k ≥ 2
- Parameters:
weighted (bool) – Edge weights = abs(y_i - y_j)
limit (int, optional) – Maximum temporal distance between connected nodes.
Nonemeans unconstrained (default). Useful for very long series where distant connections are not meaningful.output ({"edges", "degrees", "stats"}, default "edges") –
"edges"stores the full edge list;"degrees"stores only the degree sequence (fast, low memory);"stats"stores only summary statistics (lowest memory).directed (bool, default False) – Produce a directed graph with edges pointing forward in time (i → j for i < j). Enables irreversibility analysis.
only_degrees (bool)
weight_mode (str | None)
References
Luque, B., Lacasa, L., Ballesteros, F., & Luque, J. (2009). Horizontal visibility graphs: Exact results for random time series. Physical Review E, 80(4), 046103. https://doi.org/10.1103/PhysRevE.80.046103
Examples
>>> import numpy as np >>> from ts2net import HVG >>> x = np.random.randn(1000) >>> hvg = HVG().build(x) # build() returns self for chaining >>> print(hvg.n_nodes, hvg.n_edges) >>> degrees = hvg.degree_sequence >>> A = hvg.adjacency_matrix() # sparse CSR by default >>> G_nx = hvg.as_networkx() # Optional
- adjacency_matrix(format='sparse')[source]
Adjacency matrix.
- Parameters:
format ({"sparse", "coo", "dense"}, default "sparse") –
"sparse"returns a SciPy CSR matrix."coo"returns a SciPy COO matrix."dense"returns a NumPy array; refused for n > 50 000 nodes (would require ≥ 20 GB RAM).- Returns:
A – Symmetric adjacency matrix of shape (n_nodes, n_nodes).
- Return type:
csr_matrix | coo_matrix | ndarray
- as_networkx(force=False)[source]
Convert to a NetworkX graph.
- Parameters:
force (bool, default False) – If False, raises for n > 200 000 nodes to prevent accidental allocation of very large objects.
- Returns:
G
- Return type:
nx.Graph or nx.DiGraph
- build(x)[source]
Build HVG from time series.
Equivalent to
fit(x); returnsselffor method chaining.- Parameters:
x (array-like of shape (n,)) – Input time series.
- Returns:
self
- Return type:
- degree_sequence()[source]
Node degree sequence.
- Returns:
d – Out-degree for directed graphs; total degree for undirected.
- Return type:
NDArray[int64] of shape (n_nodes,)
- property edges
Edge list (None if output=’degrees’ or ‘stats’)
- edges_coo()[source]
Edge list in COO (coordinate) format.
- Returns:
rows (NDArray[int64] — source node indices)
cols (NDArray[int64] — target node indices)
weights (NDArray[float64] or None — edge weights (None if unweighted))
- Return type:
Tuple[ndarray[tuple[Any, …], dtype[int64]], ndarray[tuple[Any, …], dtype[int64]], ndarray[tuple[Any, …], dtype[float64]] | None]
- fit(x)[source]
Fit the HVG model to the time series (scikit-learn compatible).
- Parameters:
x (array-like) – Input time series (1D array)
- Returns:
self – Returns self for method chaining
- Return type:
Examples
>>> from ts2net import HVG >>> import numpy as np >>> x = np.random.randn(100) >>> hvg = HVG() >>> hvg.fit(x) # scikit-learn style >>> hvg.transform() # Get graph
- fit_transform(x)[source]
Fit the model and transform in one step (scikit-learn compatible).
- Parameters:
x (array-like) – Input time series
- Returns:
G – The visibility graph
- Return type:
networkx.Graph or DiGraph
Examples
>>> hvg = HVG() >>> G = hvg.fit_transform(x)
- property n_edges
Number of edges
- property n_nodes
Number of nodes
- network_metrics(include=None, sample_size=None, **kwargs)[source]
Compute advanced network metrics (clustering, path lengths, modularity).
- Parameters:
include (list, optional) – Metrics to include: [“clustering”, “path_lengths”, “modularity”] If None, includes all metrics
sample_size (int, optional) – For large graphs, sample nodes/pairs for expensive computations
**kwargs – Additional arguments passed to metric functions (e.g., method, weight, resolution, seed)
- Returns:
Dictionary with network metrics: - Clustering: avg_clustering, transitivity - Path lengths: avg_path_length, diameter, radius - Modularity: modularity, n_communities
- Return type:
dict
Examples
>>> from ts2net import HVG >>> import numpy as np >>> x = np.random.randn(100) >>> hvg = HVG() >>> hvg.build(x) >>> metrics = hvg.network_metrics() >>> print(f"Clustering: {metrics['avg_clustering']:.3f}") >>> print(f"Avg path length: {metrics['avg_path_length']:.3f}") >>> print(f"Modularity: {metrics['modularity']:.3f}")
- stats(include_triangles=False)[source]
Summary statistics (memory efficient, no dense matrix)
- Parameters:
include_triangles (bool)
- Return type:
dict
- test_significance(metric='density', method='shuffle', n_surrogates=200, alpha=0.05, rng=None, **kwargs)[source]
Test significance of a network metric against null distribution.
- Parameters:
metric (str, default "density") – Metric to test. Options: “density”, “deg_mean”, “deg_std”, “avg_clustering”, “assortativity”, or any key from stats()
method (str, default "shuffle") – Surrogate generation method: “shuffle”, “phase”, “circular”, “iaaft”, “block_bootstrap”
n_surrogates (int, default 200) – Number of surrogate series to generate
alpha (float, default 0.05) – Significance level (two-tailed)
rng (np.random.Generator, optional) – Random number generator
**kwargs – Additional arguments for surrogate generation (e.g., block_size for block_bootstrap)
- Returns:
result – Significance test result
- Return type:
NetworkSignificanceResult
Examples
>>> from ts2net import HVG >>> import numpy as np >>> x = np.random.randn(100) >>> hvg = HVG() >>> hvg.build(x) >>> result = hvg.test_significance(metric="density", method="phase", n_surrogates=100) >>> print(result)
- class ts2net.api.NVG(weighted=False, limit=None, only_degrees=False, output='edges', max_edges=None, max_edges_per_node=None, max_memory_mb=None, weight_mode=None)[source]
Bases:
objectNatural Visibility Graph (NVG).
Two nodes i < j are connected if the straight line between (i, x[i]) and (j, x[j]) lies strictly above all intermediate data points:
x[k] < x[i] + (x[j] - x[i]) * (k - i) / (j - i) for all i < k < j
NVG is a superset of HVG: every HVG edge is also an NVG edge.
Complexity: O(n log n) average (sweep-line algorithm).
- Parameters:
weighted (bool or str, default False) – See HVG for weight mode options.
limit (int, optional) – Horizon limit — maximum temporal distance between connected nodes. Recommended for series > 10 000 points (2 000–5 000 suggested).
output ({"edges", "degrees", "stats"}, default "edges") – Controls what is stored after build().
only_degrees (bool)
max_edges (int | None)
max_edges_per_node (int | None)
max_memory_mb (float | None)
weight_mode (str | None)
References
Lacasa, L., Luque, B., Ballesteros, F., Luque, J., & Nuño, J. C. (2008). From time series to complex networks: The visibility graph. PNAS, 105(13), 4972–4975. https://doi.org/10.1073/pnas.0709247105
Examples
>>> import numpy as np >>> from ts2net import NVG >>> x = np.random.randn(500) >>> nvg = NVG(limit=500).build(x) >>> print(nvg.n_nodes, nvg.n_edges)
- adjacency_matrix(format='sparse')[source]
Adjacency matrix.
- Parameters:
format ({"sparse", "coo", "dense"}, default "sparse") –
"sparse"returns a SciPy CSR matrix."coo"returns a SciPy COO matrix."dense"returns a NumPy array; refused for n > 50 000 nodes (would require ≥ 20 GB RAM).- Returns:
A – Symmetric adjacency matrix of shape (n_nodes, n_nodes).
- Return type:
csr_matrix | coo_matrix | ndarray
- as_networkx(force=False)[source]
Convert to a NetworkX graph.
- Parameters:
force (bool, default False) – If False, raises for n > 200 000 nodes to prevent accidental allocation of very large objects.
- Returns:
G
- Return type:
nx.Graph or nx.DiGraph
- build(x)[source]
Build NVG from time series.
Equivalent to
fit(x); returnsselffor method chaining.- Parameters:
x (array-like of shape (n,)) – Input time series.
- Returns:
self
- Return type:
- degree_sequence()[source]
Node degree sequence — shape (n_nodes,).
- Return type:
ndarray[tuple[Any, …], dtype[int64]]
- property edges
- edges_coo()[source]
Edge list in COO (coordinate) format.
- Returns:
rows (NDArray[int64] — source node indices)
cols (NDArray[int64] — target node indices)
weights (NDArray[float64] or None — edge weights (None if unweighted))
- Return type:
Tuple[ndarray[tuple[Any, …], dtype[int64]], ndarray[tuple[Any, …], dtype[int64]], ndarray[tuple[Any, …], dtype[float64]] | None]
- fit(x)[source]
Fit the NVG model to the time series (scikit-learn compatible).
- Parameters:
x (array-like) – Input time series (1D array)
- Returns:
self – Returns self for method chaining
- Return type:
Examples
>>> from ts2net import NVG >>> import numpy as np >>> x = np.random.randn(100) >>> nvg = NVG() >>> nvg.fit(x) # scikit-learn style >>> nvg.transform() # Get graph
- fit_transform(x)[source]
Fit the model and transform in one step (scikit-learn compatible).
- Parameters:
x (array-like) – Input time series
- Returns:
G – The visibility graph
- Return type:
networkx.Graph
Examples
>>> nvg = NVG() >>> G = nvg.fit_transform(x)
- property n_edges: int
Number of edges.
- property n_nodes: int
Number of nodes (equals length of input series).
- network_metrics(include=None, sample_size=None, **kwargs)[source]
Compute advanced network metrics (clustering, path lengths, modularity).
- Parameters:
include (list, optional) – Metrics to include: [“clustering”, “path_lengths”, “modularity”] If None, includes all metrics
sample_size (int, optional) – For large graphs, sample nodes/pairs for expensive computations
**kwargs – Additional arguments passed to metric functions (e.g., method, weight, resolution, seed)
- Returns:
Dictionary with network metrics: - Clustering: avg_clustering, transitivity - Path lengths: avg_path_length, diameter, radius - Modularity: modularity, n_communities
- Return type:
dict
Examples
>>> from ts2net import HVG >>> import numpy as np >>> x = np.random.randn(100) >>> hvg = HVG() >>> hvg.build(x) >>> metrics = hvg.network_metrics() >>> print(f"Clustering: {metrics['avg_clustering']:.3f}") >>> print(f"Avg path length: {metrics['avg_path_length']:.3f}") >>> print(f"Modularity: {metrics['modularity']:.3f}")
- stats(include_triangles=False)[source]
Summary statistics (no dense matrix required).
- Parameters:
include_triangles (bool)
- Return type:
dict
- test_significance(metric='density', method='shuffle', n_surrogates=200, alpha=0.05, rng=None, **kwargs)[source]
Test significance of a network metric against null distribution.
- Parameters:
metric (str, default "density") – Metric to test. Options: “density”, “deg_mean”, “deg_std”, “avg_clustering”, “assortativity”, or any key from stats()
method (str, default "shuffle") – Surrogate generation method: “shuffle”, “phase”, “circular”, “iaaft”, “block_bootstrap”
n_surrogates (int, default 200) – Number of surrogate series to generate
alpha (float, default 0.05) – Significance level (two-tailed)
rng (np.random.Generator, optional) – Random number generator
**kwargs – Additional arguments for surrogate generation (e.g., block_size for block_bootstrap)
- Returns:
result – Significance test result
- Return type:
NetworkSignificanceResult
Examples
>>> from ts2net import NVG >>> import numpy as np >>> x = np.random.randn(100) >>> nvg = NVG() >>> nvg.build(x) >>> result = nvg.test_significance(metric="density", method="phase", n_surrogates=100) >>> print(result)
- class ts2net.api.RecurrenceNetwork(m=None, tau=1, rule='knn', k=5, epsilon=0.1, metric='euclidean', only_degrees=False, output='edges')[source]
Bases:
objectRecurrence Network.
A recurrence network is derived from a recurrence plot. After delay-embedding the series into an m-dimensional phase space, two states i, j are connected if their distance falls below a threshold (
rule="epsilon") or if one is among the other’s k nearest neighbours (rule="knn").- Parameters:
m (int, optional) – Embedding dimension.
Nonemeans no embedding (1-D, i.e., the raw series is used as the phase-space trajectory).tau (int, default 1) – Time delay for Takens embedding.
rule ({"knn", "epsilon"}, default "knn") –
"knn"connects each point to its k nearest neighbours."epsilon"connects all pairs closer than epsilon.k (int, default 5) – Number of nearest neighbours (
rule="knn"only).epsilon (float, default 0.1) – Recurrence threshold (
rule="epsilon"only).metric (str, default "euclidean") – Distance metric for phase-space proximity.
output ({"edges", "degrees", "stats"}, default "edges") – Controls what is stored after build().
only_degrees (bool)
References
Marwan, N., Donges, J. F., Zou, Y., Donner, R. V., & Kurths, J. (2009). Complex network approach for recurrence analysis of time series. Physics Letters A, 373(46), 4246–4254. https://doi.org/10.1016/j.physleta.2009.09.042
Examples
>>> import numpy as np >>> from ts2net import RecurrenceNetwork >>> x = np.sin(np.linspace(0, 8*np.pi, 300)) + 0.1*np.random.randn(300) >>> rn = RecurrenceNetwork(rule="epsilon", epsilon=0.3).build(x) >>> print(rn.n_nodes, rn.n_edges)
- adjacency_matrix(format='sparse')[source]
Adjacency matrix.
- Parameters:
format ({"sparse", "coo", "dense"}, default "sparse") –
"sparse"returns a SciPy CSR matrix."coo"returns a SciPy COO matrix."dense"returns a NumPy array; refused for n > 50 000 nodes (would require ≥ 20 GB RAM).- Returns:
A – Symmetric adjacency matrix of shape (n_nodes, n_nodes).
- Return type:
csr_matrix | coo_matrix | ndarray
- as_networkx(force=False)[source]
Convert to a NetworkX graph.
- Parameters:
force (bool, default False) – If False, raises for n > 200 000 nodes to prevent accidental allocation of very large objects.
- Returns:
G
- Return type:
nx.Graph or nx.DiGraph
- build(x)[source]
Build recurrence network from time series.
- Parameters:
x (array-like of shape (n,)) – Input time series.
- Returns:
self
- Return type:
- degree_sequence()[source]
Node degree sequence — shape (n_nodes,).
- Return type:
ndarray[tuple[Any, …], dtype[int64]]
- property edges
- edges_coo()[source]
Edge list in COO (coordinate) format.
- Returns:
rows (NDArray[int64] — source node indices)
cols (NDArray[int64] — target node indices)
weights (NDArray[float64] or None — edge weights (None if unweighted))
- Return type:
Tuple[ndarray[tuple[Any, …], dtype[int64]], ndarray[tuple[Any, …], dtype[int64]], ndarray[tuple[Any, …], dtype[float64]] | None]
- property n_edges: int
Number of edges.
- property n_nodes: int
Number of nodes (equals length of input series).
- class ts2net.api.TransitionNetwork(symbolizer='ordinal', order=3, delay=1, tie_rule='stable', bins=5, normalize=True, sparse=False, only_degrees=False, output='edges')[source]
Bases:
objectTransition Network (Ordinal Partition Network).
The time series is symbolised — each subsequence of length
order+1is mapped to its rank-order pattern (an ordinal pattern). A directed graph is then built where nodes are distinct patterns and a weighted edge (i → j) records how often pattern i is immediately followed by pattern j.The resulting graph captures the Markov-like transition dynamics of the series and is sensitive to nonlinear structure invisible to linear methods.
- Parameters:
symbolizer ({"ordinal", "equal_width", "equal_freq", "kmeans"}) – How to discretise the series into symbolic states.
"ordinal"(default) uses rank-order patterns — invariant to monotone transformations and well-studied analytically.order (int, default 3) – Pattern length =
order + 1.order=3gives 3! = 6 possible patterns. Larger values capture longer-range dependencies at the cost of sparsity (and needing longer series).delay (int, default 1) – Sampling delay for pattern extraction.
output ({"edges", "degrees", "stats"}, default "edges") – Controls what is stored after build().
tie_rule (str)
bins (int)
normalize (bool)
sparse (bool)
only_degrees (bool)
References
Small, M. (2013). Complex networks from time series: Capturing nonlinear dynamics. Chaos, 23(3), 033127. https://doi.org/10.1063/1.4818261
Examples
>>> import numpy as np >>> from ts2net import TransitionNetwork >>> x = np.random.randn(500) >>> tn = TransitionNetwork(order=3).build(x) >>> print(tn.n_nodes, tn.n_edges) # nodes = distinct patterns, directed
- adjacency_matrix(format='sparse')[source]
Adjacency matrix.
- Parameters:
format ({"sparse", "coo", "dense"}, default "sparse") –
"sparse"returns a SciPy CSR matrix."coo"returns a SciPy COO matrix."dense"returns a NumPy array; refused for n > 50 000 nodes (would require ≥ 20 GB RAM).- Returns:
A – Symmetric adjacency matrix of shape (n_nodes, n_nodes).
- Return type:
csr_matrix | coo_matrix | ndarray
- as_networkx(force=False)[source]
Convert to a NetworkX graph.
- Parameters:
force (bool, default False) – If False, raises for n > 200 000 nodes to prevent accidental allocation of very large objects.
- Returns:
G
- Return type:
nx.Graph or nx.DiGraph
- build(x)[source]
Build transition network from time series.
- Parameters:
x (array-like of shape (n,)) – Input time series.
- Returns:
self
- Return type:
- degree_sequence()[source]
Node degree sequence — shape (n_nodes,).
- Return type:
ndarray[tuple[Any, …], dtype[int64]]
- property edges
- edges_coo()[source]
Edge list in COO (coordinate) format.
- Returns:
rows (NDArray[int64] — source node indices)
cols (NDArray[int64] — target node indices)
weights (NDArray[float64] or None — edge weights (None if unweighted))
- Return type:
Tuple[ndarray[tuple[Any, …], dtype[int64]], ndarray[tuple[Any, …], dtype[int64]], ndarray[tuple[Any, …], dtype[float64]] | None]
- property n_edges: int
Number of edges.
- property n_nodes: int
Number of nodes (equals length of input series).
- ts2net.api.build_network(x, method, **kwargs)[source]
Build network from time series (factory pattern).
- Parameters:
x (array) – Time series
method (str) – ‘hvg’, ‘nvg’, ‘recurrence’, ‘transition’
**kwargs – Method-specific parameters
- Returns:
graph – Built network with .edges, .degree_sequence(), etc.
- Return type:
Graph-like object
Examples
>>> x = np.random.randn(1000) >>> hvg = build_network(x, 'hvg') >>> rn = build_network(x, 'recurrence', m=3, rule='knn', k=5)
Core
Core module for time series to network conversion.
This module provides implementations of various time series to network conversion algorithms including Recurrence Networks, Visibility Graphs, and Transition Networks.
- ts2net.core.batch_transform(X, builder, **kwargs)[source]
Transform multiple time series using the specified builder.
- Parameters:
X (Sequence[np.ndarray]) – Sequence of time series arrays
builder (str) – Name of the builder to use
**kwargs – Additional keyword arguments for the builder
- Returns:
List of transformed graphs
- Return type:
List[Union[nx.Graph, nx.DiGraph]]
- ts2net.core.directed_3node_motifs(G, max_samples=None, seed=3363)[source]
- Parameters:
G (DiGraph)
max_samples (int | None)
seed (int)
- Return type:
dict
- ts2net.core.embed(x, m, tau)[source]
Time-delay embedding of a time series.
- Parameters:
x (np.ndarray) – 1D time series
m (int) – Embedding dimension
tau (int) – Time delay
- Returns:
2D array of shape (L, m) where L = len(x) - (m-1)*tau
- Return type:
np.ndarray
- ts2net.core.graph_summary(G, motifs=None, motif_samples=None, seed=3363)[source]
Compute a comprehensive summary of graph properties.
- Parameters:
G (nx.Graph or nx.DiGraph) – Input graph
motifs (str, optional) – Type of motifs to compute (‘3node’, ‘4node’, or None)
motif_samples (int, optional) – Maximum number of samples for motif counting
seed (int, default 3363) – Random seed for sampling
- Returns:
Dictionary of graph properties
- Return type:
dict
- ts2net.core.motif_counts(G, motif_type='3node', max_samples=None, seed=3363)[source]
Count motifs in a graph.
- Parameters:
G (nx.Graph or nx.DiGraph) – Input graph
motif_type (str, default '3node') – Type of motifs to count (‘3node’ or ‘4node’)
max_samples (int, optional) – Maximum number of samples for motif counting
seed (int, default 3363) – Random seed for sampling
- Returns:
Dictionary of motif counts
- Return type:
Dict[str, int]
Visualization
Visualization module for ts2net.
Clean, scalable plotting functions for time series network analysis. All functions return (fig, ax) for further customization.
- class ts2net.viz.TSGraph(graph, pos, meta)[source]
Bases:
objectContainer for a time-series-derived graph plus geometry and build metadata.
- Parameters:
graph (Graph | DiGraph)
pos (Dict[int, ndarray] | None)
meta (Dict[str, Any])
- graph
NetworkX graph with node and edge attributes.
- Type:
networkx.classes.graph.Graph | networkx.classes.digraph.DiGraph
- pos
Optional 2D coordinates for nodes. Keys match graph nodes. Defaults to (t, x[t]) for visibility graphs.
- Type:
Dict[int, numpy.ndarray] | None
- meta
Build metadata such as method, parameters, and data shape.
- Type:
Dict[str, Any]
- graph: Graph | DiGraph
- meta: Dict[str, Any]
- pos: Dict[int, ndarray] | None
- ts2net.viz.build_ordinal_partition_graph(x, *, embed_dim=4, delay=1, directed=True, weighted=True, include_self_loops=True, tie_break='stable', return_pos=False, dtype=<class 'numpy.float64'>)[source]
Build an ordinal partition network.
Nodes represent permutation patterns. Directed edges represent observed transitions between patterns. Edge weight equals count or probability.
- Parameters:
x (ndarray | Iterable[float]) – 1D time series.
embed_dim (int) – Embedding dimension d (order of permutation).
delay (int) – Time delay τ.
directed (bool) – If True, create directed graph (default True).
weighted (bool) – If True, edge weights are transition counts.
include_self_loops (bool) – If True, allow self-transitions.
tie_break (Literal['stable', 'jitter']) – How to handle ties in permutation patterns. - “stable”: Use stable sort (preserves order of ties). - “jitter”: Add small noise to break ties.
return_pos (bool) – If True, compute 2D positions for nodes (default False).
dtype (dtype) – Numeric dtype.
- Returns:
graph: DiGraph (or Graph if directed=False) with pattern nodes.
node attribute “pattern”: tuple[int, …] representing permutation.
node attribute “count”: occurrence count of pattern.
edge attribute “weight”: transition count (if weighted).
pos: Optional 2D positions for visualization.
meta: Build parameters and statistics.
- Return type:
TSGraph with
- ts2net.viz.build_recurrence_graph(x, *, embed_dim=3, delay=1, eps=0.2, eps_mode='fraction_max', metric='euclidean', exclude_diagonal=True, theiler_window=0, knn=0, knn_mode='none', weighted=False, weight_mode='inverse_distance', return_pos=True, node_id='time', dtype=<class 'numpy.float64'>)[source]
Build an ε-recurrence network from a time series.
You embed the series into state space, then connect nodes whose state vectors fall within an ε ball. This matches the style in recurrence-network figures where ε changes density.
- Parameters:
x (ndarray | Iterable[float]) – 1D array-like of shape (n,) or array of shape (n, p) for multivariate.
embed_dim (int) – Embedding dimension m.
delay (int) – Delay τ in samples.
eps (float) – Threshold value. Interpreted by eps_mode.
eps_mode (Literal['fraction_max', 'percentile']) – How to interpret eps. - “fraction_max”: eps * max_pairwise_distance. - “percentile”: eps is a percentile in [0, 100].
metric (Literal['euclidean', 'sqeuclidean', 'manhattan', 'chebyshev']) – Distance metric in state space.
exclude_diagonal (bool) – Remove self edges.
theiler_window (int) – Exclude edges for |i - j| <= theiler_window.
knn (int) – If > 0, also connect k nearest neighbors per node.
knn_mode (Literal['none', 'mutual', 'directed']) – How to apply knn edges. - “none”: ignore knn parameter. - “mutual”: keep only mutual kNN edges. - “directed”: create directed kNN edges (returns DiGraph).
weighted (bool) – Store weights on edges.
weight_mode (Literal['distance', 'inverse_distance']) – Weight definition if weighted.
return_pos (bool) – If True, return node positions as embedded vectors.
node_id (Literal['time', 'state']) – Node labeling scheme. - “time”: node id equals time index i. - “state”: node id equals integer state index in embedding.
dtype (dtype) – Numeric dtype.
- Returns:
graph nodes ordered by time index.
node attributes: “t” time index, “state” embedded vector.
edge attributes: “dist” and optionally “weight”.
pos: embedded vectors (or None).
meta: method and parameters.
- Return type:
TSGraph with
- ts2net.viz.build_visibility_graph(x, *, kind='hvg', directed=False, weighted=False, weight_mode=None, limit=None, max_edges=None, max_edges_per_node=None, max_memory_mb=None, include_self_loops=False, return_pos=True, dtype=<class 'numpy.float64'>)[source]
Construct HVG or NVG style graphs with optional direction and weights.
Nodes map to time index i. Edge direction uses time forward orientation i -> j when i < j. Weights attach as edge attribute “weight”. Distances and aux values attach as edge attributes when needed.
- Parameters:
x (ndarray | Iterable[float]) – 1D series.
kind (Literal['hvg', 'nvg', 'bounded_nvg']) – hvg, nvg, or bounded_nvg.
directed (bool) – If True, emit a DiGraph and only time forward edges.
weighted (bool | Literal['none', 'absdiff', 'time_gap', 'min_clearance', 'slope']) – False, True, or a string mode.
weight_mode (Literal['none', 'absdiff', 'time_gap', 'min_clearance', 'slope'] | None) – Optional explicit mode. Overrides weighted when set.
limit (int | None) – Window limit for NVG variants.
max_edges (int | None) – Global cap for bounded_nvg.
max_edges_per_node (int | None) – Per node cap for bounded_nvg.
max_memory_mb (int | None) – Memory guard for bounded_nvg.
include_self_loops (bool) – Rare. Default False.
return_pos (bool) – If True, pos uses (t, x[t]) so plots match the series.
dtype (dtype) – Numeric dtype.
- Returns:
TSGraph container with graph, pos, and meta.
- Return type:
- ts2net.viz.draw_tsgraph(tsgraph, *, ax=None, node_size=10.0, edge_alpha=0.15, node_alpha=0.9, color_by='time', cmap='viridis', show=True, layout=None)[source]
Draw graph with thin edges and colored nodes.
Expects tsgraph.pos. Falls back to a layout if pos is None.
- Parameters:
tsgraph (TSGraph) – Graph container with graph, pos, and meta
ax (matplotlib.axes.Axes, optional) – Axes to draw on (creates new figure if None)
node_size (float, default 10.0) – Size of nodes in points
edge_alpha (float, default 0.15) – Transparency of edges (0-1)
node_alpha (float, default 0.9) – Transparency of nodes (0-1)
color_by (str, default "time") – Node coloring scheme: - “time”: Color by time index (uses node attribute ‘t’) - “degree”: Color by node degree - “community”: Color by community (requires community detection) - “none”: Single color for all nodes
cmap (str, default "viridis") – Colormap name for node colors
show (bool, default True) – If True, call plt.show()
layout (str, optional) – Layout algorithm if pos is None (e.g., “spring”, “kamada_kawai”) Defaults to “spring” for undirected, “circular” for directed
- Returns:
fig (matplotlib.figure.Figure)
ax (matplotlib.axes.Axes)
- Return type:
Tuple[Figure, Axes]
- ts2net.viz.optimal_dim(x, delay=1, dim_range=(2, 8))[source]
Estimate optimal embedding dimension d by maximizing OPN degree variance.
This heuristic builds ordinal partition networks for different dimensions and selects the dimension that maximizes variance in the degree distribution. Higher variance suggests richer structure.
- Parameters:
x (ndarray) – 1D time series.
delay (int) – Time delay τ (use optimal_lag if unsure).
dim_range (Tuple[int, int]) – (min_dim, max_dim) to search.
- Returns:
Optimal embedding dimension d.
- Return type:
int
- ts2net.viz.optimal_lag(x, max_lag=50)[source]
Estimate optimal time delay τ using first zero of autocorrelation.
This is a simple heuristic: find the first lag where autocorrelation crosses zero. If no zero crossing, return lag with minimum autocorrelation.
- Parameters:
x (ndarray) – 1D time series.
max_lag (int) – Maximum lag to consider.
- Returns:
Optimal delay τ (in samples).
- Return type:
int
- ts2net.viz.plot_degree_ccdf(degrees, title=None, figsize=None)[source]
Figure 3: Degree distribution as CCDF (Complementary CDF).
Plots the complementary CDF of degrees on log y scale. Works better than a histogram, stays stable across sample size, makes cross-zone comparison easy.
- Parameters:
degrees (array (n,)) – Degree sequence
title (str, optional) – Plot title
figsize (tuple, optional) – Figure size (default: (10, 6))
- Returns:
fig (matplotlib.figure.Figure)
ax (matplotlib.axes.Axes)
- Return type:
Tuple[Figure, Axes]
- ts2net.viz.plot_degree_profile(degrees, time_index=None, title=None, figsize=None)[source]
Figure 2: Degree profile across time.
Plots degree versus time index. This becomes a direct proxy for “local complexity” in the signal. Reads well and scales well.
- Parameters:
degrees (array (n,)) – Degree sequence (one per node/time point)
time_index (array (n,), optional) – Time indices (default: 0, 1, 2, …)
title (str, optional) – Plot title
figsize (tuple, optional) – Figure size (default: (10, 6))
- Returns:
fig (matplotlib.figure.Figure)
ax (matplotlib.axes.Axes)
- Return type:
Tuple[Figure, Axes]
- ts2net.viz.plot_hvg_small(x, edges, time_index=None, title=None, figsize=None)[source]
Optional: Small n graph drawing for HVG.
Uses fixed layout based on time index. Nodes at x = time, y = normalized value. Edges drawn as faint arcs or straight lines. Shows visibility logic.
- Parameters:
x (array (n,)) – Time series values
edges (list of tuples) – Edge list [(i, j), …]
time_index (array (n,), optional) – Time indices (default: 0, 1, 2, …)
title (str, optional) – Plot title
figsize (tuple, optional) – Figure size (default: (10, 6))
- Returns:
fig (matplotlib.figure.Figure)
ax (matplotlib.axes.Axes)
- Return type:
Tuple[Figure, Axes]
- ts2net.viz.plot_method_comparison(df_metrics, methods=None, figsize=None)[source]
Figure 4: Method comparison panel.
Creates a small table graphic with three aligned dot plots: - Edge count - Average degree - Normalized density (edges / n)
Uses one axis per metric. Zones/methods on y-axis.
- Parameters:
df_metrics (dict or array) – Dictionary mapping method names to dicts with ‘n_edges’, ‘avg_degree’, ‘density’ OR array of dicts with ‘method’ key
methods (list of str, optional) – Method names (if df_metrics is array)
figsize (tuple, optional) – Figure size (default: (12, 6))
- Returns:
fig (matplotlib.figure.Figure)
axes (list of matplotlib.axes.Axes)
- Return type:
Tuple[Figure, List[Axes]]
- ts2net.viz.plot_recurrence_matrix(recurrence_matrix, title=None, figsize=None)[source]
Optional: Recurrence plot style view for recurrence networks.
Draws the recurrence matrix as an image for a short window. Users already understand this visual.
- Parameters:
recurrence_matrix (array (n, n)) – Recurrence/adjacency matrix
title (str, optional) – Plot title
figsize (tuple, optional) – Figure size (default: (8, 8))
- Returns:
fig (matplotlib.figure.Figure)
ax (matplotlib.axes.Axes)
- Return type:
Tuple[Figure, Axes]
- ts2net.viz.plot_series_with_events(x, events=None, window=None, window_bounds=None, time_index=None, title=None, figsize=None)[source]
Figure 1: Time series with change points and window boundaries.
Shows the signal with detected change points as thin vertical lines and window edges as faint bands. Provides context for network results.
- Parameters:
x (array (n,)) – Time series values
events (array (m,), optional) – Indices of detected change points
window (tuple (start, end), optional) – Single window boundaries to highlight
window_bounds (list of tuples, optional) – Multiple window boundaries [(start, end), …]
time_index (array (n,), optional) – Time indices (default: 0, 1, 2, …)
title (str, optional) – Plot title
figsize (tuple, optional) – Figure size (default: (10, 6))
- Returns:
fig (matplotlib.figure.Figure)
ax (matplotlib.axes.Axes)
- Return type:
Tuple[Figure, Axes]
- ts2net.viz.plot_timeseries_network(graphs, timestamps, pos=None, node_colors=None, title='Time Series Network Evolution', show=True, filename=None)[source]
Create an interactive Plotly visualization showing network evolution over time.
- Parameters:
graphs (list of nx.Graph) – List of NetworkX graphs, one for each time step
timestamps (list) – List of timestamps/labels for each time step (e.g., dates, indices)
pos (dict, optional) – Node positions dictionary. If None, computes spring layout from first graph
node_colors (str, list, or dict, optional) – Node coloring scheme: - “degree”: Color by node degree - “time”: Color by time index - list: List of colors for each node - dict: Mapping of node -> color
title (str, default "Time Series Network Evolution") – Plot title
show (bool, default True) – If True, display the plot
filename (str, optional) – If provided, save the plot to this HTML file
- Returns:
fig – Interactive Plotly figure with time slider
- Return type:
plotly.graph_objects.Figure
Examples
>>> from ts2net.viz.plotly_viz import plot_timeseries_network >>> import networkx as nx >>> >>> # Create example graphs for different time steps >>> graphs = [nx.erdos_renyi_graph(20, 0.3) for _ in range(5)] >>> timestamps = [f"Step {i}" for i in range(5)] >>> >>> fig = plot_timeseries_network(graphs, timestamps) >>> fig.show()
- ts2net.viz.plot_window_feature_map(df_window_features, feature_names=None, time_labels=None, figsize=None)[source]
Figure 5: Window level feature map.
Computes window stats (mean degree, degree variance, assortativity proxy, transition entropy) and plots as a heatmap with time on x and feature on y. Provides anomaly signatures.
- Parameters:
df_window_features (dict or array) – Dictionary mapping feature names to arrays OR array of dicts
feature_names (list of str, optional) – Feature names (if df_window_features is dict, uses keys)
time_labels (list of str, optional) – Time window labels (default: 0, 1, 2, …)
figsize (tuple, optional) – Figure size (default: (12, 8))
- Returns:
fig (matplotlib.figure.Figure)
ax (matplotlib.axes.Axes)
- Return type:
Tuple[Figure, Axes]
- ts2net.viz.plot_windowed_networks(x, window, step=1, method='hvg', pos=None, **method_kwargs)[source]
Create interactive visualization of networks built from sliding windows.
- Parameters:
x (array (n_points,)) – Input time series
window (int) – Window width (number of time points per window)
step (int, default 1) – Step size between consecutive windows
method (str, default "hvg") – Network method: ‘hvg’, ‘nvg’, ‘recurrence’, ‘transition’
pos (dict, optional) – Node positions. If None, computes from first window
**method_kwargs – Additional parameters for the network builder
- Returns:
fig – Interactive Plotly figure
- Return type:
plotly.graph_objects.Figure
Examples
>>> import numpy as np >>> from ts2net.viz.plotly_viz import plot_windowed_networks >>> >>> x = np.random.randn(1000) >>> fig = plot_windowed_networks(x, window=50, step=10, method='hvg') >>> fig.show()
Unified Graph API
Unified graph visualization API for ts2net.
Provides TSGraph dataclass and builder functions for creating visualization-ready graph objects with geometry and metadata.
- class ts2net.viz.graph.TSGraph(graph, pos, meta)[source]
Bases:
objectContainer for a time-series-derived graph plus geometry and build metadata.
- Parameters:
graph (Graph | DiGraph)
pos (Dict[int, ndarray] | None)
meta (Dict[str, Any])
- graph
NetworkX graph with node and edge attributes.
- Type:
networkx.classes.graph.Graph | networkx.classes.digraph.DiGraph
- pos
Optional 2D coordinates for nodes. Keys match graph nodes. Defaults to (t, x[t]) for visibility graphs.
- Type:
Dict[int, numpy.ndarray] | None
- meta
Build metadata such as method, parameters, and data shape.
- Type:
Dict[str, Any]
- graph: Graph | DiGraph
- meta: Dict[str, Any]
- pos: Dict[int, ndarray] | None
- ts2net.viz.graph.build_ordinal_partition_graph(x, *, embed_dim=4, delay=1, directed=True, weighted=True, include_self_loops=True, tie_break='stable', return_pos=False, dtype=<class 'numpy.float64'>)[source]
Build an ordinal partition network.
Nodes represent permutation patterns. Directed edges represent observed transitions between patterns. Edge weight equals count or probability.
- Parameters:
x (ndarray | Iterable[float]) – 1D time series.
embed_dim (int) – Embedding dimension d (order of permutation).
delay (int) – Time delay τ.
directed (bool) – If True, create directed graph (default True).
weighted (bool) – If True, edge weights are transition counts.
include_self_loops (bool) – If True, allow self-transitions.
tie_break (Literal['stable', 'jitter']) – How to handle ties in permutation patterns. - “stable”: Use stable sort (preserves order of ties). - “jitter”: Add small noise to break ties.
return_pos (bool) – If True, compute 2D positions for nodes (default False).
dtype (dtype) – Numeric dtype.
- Returns:
graph: DiGraph (or Graph if directed=False) with pattern nodes.
node attribute “pattern”: tuple[int, …] representing permutation.
node attribute “count”: occurrence count of pattern.
edge attribute “weight”: transition count (if weighted).
pos: Optional 2D positions for visualization.
meta: Build parameters and statistics.
- Return type:
TSGraph with
- ts2net.viz.graph.build_recurrence_graph(x, *, embed_dim=3, delay=1, eps=0.2, eps_mode='fraction_max', metric='euclidean', exclude_diagonal=True, theiler_window=0, knn=0, knn_mode='none', weighted=False, weight_mode='inverse_distance', return_pos=True, node_id='time', dtype=<class 'numpy.float64'>)[source]
Build an ε-recurrence network from a time series.
You embed the series into state space, then connect nodes whose state vectors fall within an ε ball. This matches the style in recurrence-network figures where ε changes density.
- Parameters:
x (ndarray | Iterable[float]) – 1D array-like of shape (n,) or array of shape (n, p) for multivariate.
embed_dim (int) – Embedding dimension m.
delay (int) – Delay τ in samples.
eps (float) – Threshold value. Interpreted by eps_mode.
eps_mode (Literal['fraction_max', 'percentile']) – How to interpret eps. - “fraction_max”: eps * max_pairwise_distance. - “percentile”: eps is a percentile in [0, 100].
metric (Literal['euclidean', 'sqeuclidean', 'manhattan', 'chebyshev']) – Distance metric in state space.
exclude_diagonal (bool) – Remove self edges.
theiler_window (int) – Exclude edges for |i - j| <= theiler_window.
knn (int) – If > 0, also connect k nearest neighbors per node.
knn_mode (Literal['none', 'mutual', 'directed']) – How to apply knn edges. - “none”: ignore knn parameter. - “mutual”: keep only mutual kNN edges. - “directed”: create directed kNN edges (returns DiGraph).
weighted (bool) – Store weights on edges.
weight_mode (Literal['distance', 'inverse_distance']) – Weight definition if weighted.
return_pos (bool) – If True, return node positions as embedded vectors.
node_id (Literal['time', 'state']) – Node labeling scheme. - “time”: node id equals time index i. - “state”: node id equals integer state index in embedding.
dtype (dtype) – Numeric dtype.
- Returns:
graph nodes ordered by time index.
node attributes: “t” time index, “state” embedded vector.
edge attributes: “dist” and optionally “weight”.
pos: embedded vectors (or None).
meta: method and parameters.
- Return type:
TSGraph with
- ts2net.viz.graph.build_visibility_graph(x, *, kind='hvg', directed=False, weighted=False, weight_mode=None, limit=None, max_edges=None, max_edges_per_node=None, max_memory_mb=None, include_self_loops=False, return_pos=True, dtype=<class 'numpy.float64'>)[source]
Construct HVG or NVG style graphs with optional direction and weights.
Nodes map to time index i. Edge direction uses time forward orientation i -> j when i < j. Weights attach as edge attribute “weight”. Distances and aux values attach as edge attributes when needed.
- Parameters:
x (ndarray | Iterable[float]) – 1D series.
kind (Literal['hvg', 'nvg', 'bounded_nvg']) – hvg, nvg, or bounded_nvg.
directed (bool) – If True, emit a DiGraph and only time forward edges.
weighted (bool | Literal['none', 'absdiff', 'time_gap', 'min_clearance', 'slope']) – False, True, or a string mode.
weight_mode (Literal['none', 'absdiff', 'time_gap', 'min_clearance', 'slope'] | None) – Optional explicit mode. Overrides weighted when set.
limit (int | None) – Window limit for NVG variants.
max_edges (int | None) – Global cap for bounded_nvg.
max_edges_per_node (int | None) – Per node cap for bounded_nvg.
max_memory_mb (int | None) – Memory guard for bounded_nvg.
include_self_loops (bool) – Rare. Default False.
return_pos (bool) – If True, pos uses (t, x[t]) so plots match the series.
dtype (dtype) – Numeric dtype.
- Returns:
TSGraph container with graph, pos, and meta.
- Return type:
- ts2net.viz.graph.optimal_dim(x, delay=1, dim_range=(2, 8))[source]
Estimate optimal embedding dimension d by maximizing OPN degree variance.
This heuristic builds ordinal partition networks for different dimensions and selects the dimension that maximizes variance in the degree distribution. Higher variance suggests richer structure.
- Parameters:
x (ndarray) – 1D time series.
delay (int) – Time delay τ (use optimal_lag if unsure).
dim_range (Tuple[int, int]) – (min_dim, max_dim) to search.
- Returns:
Optimal embedding dimension d.
- Return type:
int
- ts2net.viz.graph.optimal_lag(x, max_lag=50)[source]
Estimate optimal time delay τ using first zero of autocorrelation.
This is a simple heuristic: find the first lag where autocorrelation crosses zero. If no zero crossing, return lag with minimum autocorrelation.
- Parameters:
x (ndarray) – 1D time series.
max_lag (int) – Maximum lag to consider.
- Returns:
Optimal delay τ (in samples).
- Return type:
int
Multivariate
Multivariate time series to network construction.
This module provides tools to construct networks from multiple time series, where nodes represent time series and edges represent similarities/associations.
Examples
>>> import numpy as np
>>> from ts2net.multivariate import ts_dist, net_knn
>>> X = np.random.randn(10, 100) # 10 time series, 100 points each
>>> D = ts_dist(X, method='correlation', n_jobs=-1)
>>> G, A = net_knn(D, k=3)
>>> print(f"Network: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges")
- ts2net.multivariate.cluster_series_by_features(features_df, n_clusters=None, method='kmeans')[source]
Cluster time series based on their network features.
Groups series with similar network properties together.
- Parameters:
features_df (pandas.DataFrame) – DataFrame from compute_network_features() with network features
n_clusters (int, optional) – Number of clusters (if None, uses elbow method)
method (str, default "kmeans") – Clustering method: “kmeans” or “hierarchical”
- Returns:
clusters – Dictionary mapping series name to cluster ID
- Return type:
dict
Examples
>>> features = compute_network_features(X, method="hvg") >>> clusters = cluster_series_by_features(features, n_clusters=3) >>> print(f"Series grouped into {len(set(clusters.values()))} clusters")
- ts2net.multivariate.compare_network_features(features_df, metric=None)[source]
Compare network features across multiple series.
Computes summary statistics and similarity measures for network features across different time series.
- Parameters:
features_df (pandas.DataFrame) – DataFrame from compute_network_features() with network features for multiple series
metric (str, optional) – Specific metric to compare (if None, compares all numeric columns)
- Returns:
comparison – Dictionary with comparison metrics: - “mean”: Mean value across series - “std”: Standard deviation across series - “min”: Minimum value - “max”: Maximum value - “range”: Range (max - min) - “cv”: Coefficient of variation (std / mean) - “similarity_matrix”: Correlation matrix of features (if multiple metrics)
- Return type:
dict
Examples
>>> features = compute_network_features(X, method="hvg") >>> comparison = compare_network_features(features) >>> print(f"Avg density: {comparison['density']['mean']:.3f}") >>> print(f"Density CV: {comparison['density']['cv']:.3f}")
- ts2net.multivariate.compute_network_features(X, method='hvg', series_names=None, **kwargs)[source]
Compute network features for multiple time series.
For each time series, builds a network and extracts summary statistics. Returns a DataFrame with one row per series and columns for each feature.
- Parameters:
X (list of arrays or array (n_series, n_points)) – Multiple time series to analyze
method (str, default "hvg") – Network construction method: “hvg”, “nvg”, “recurrence”, or “transition”
series_names (list of str, optional) – Names for each series (default: “Series_0”, “Series_1”, …)
**kwargs – Additional arguments passed to network builder (e.g., weighted, k, threshold)
- Returns:
df – DataFrame with network features for each series: - n_nodes: Number of nodes - n_edges: Number of edges - density: Edge density - avg_degree: Average degree - std_degree: Standard deviation of degree - min_degree: Minimum degree - max_degree: Maximum degree - (and method-specific features)
- Return type:
pandas.DataFrame
Examples
>>> import numpy as np >>> from ts2net.multivariate import compute_network_features >>> >>> # Create multiple time series >>> X = [np.random.randn(100) for _ in range(5)] >>> >>> # Compute HVG features for all series >>> features = compute_network_features(X, method="hvg") >>> print(features) >>> >>> # Compare series >>> print(features.describe())
- ts2net.multivariate.coupling_strength(x1, x2, method='joint_recurrence', threshold=None, k=None)[source]
Compute coupling strength between two time series.
- Parameters:
x1 (array (n,)) – First time series
x2 (array (n,)) – Second time series
method (str, default "joint_recurrence") – Coupling method: “joint_recurrence” or “cross_visibility”
threshold (float, optional) – Threshold for recurrence (if method=”joint_recurrence”)
k (int, optional) – k for k-NN recurrence (if method=”joint_recurrence”)
- Returns:
metrics – Dictionary with coupling metrics: - coupling_strength: Overall coupling strength (0-1) - joint_recurrence_rate: Fraction of joint recurrences - synchronization: Degree of synchronization - asymmetry: Asymmetry in coupling (0 = symmetric)
- Return type:
dict
Examples
>>> import numpy as np >>> x1 = np.random.randn(100) >>> x2 = x1 + 0.1 * np.random.randn(100) # Coupled series >>> metrics = coupling_strength(x1, x2, method="joint_recurrence", threshold=0.5) >>> print(f"Coupling strength: {metrics['coupling_strength']:.3f}")
- ts2net.multivariate.cross_visibility_graph(x1, x2, method='hvg', weighted=False, weight_mode=None, limit=None, directed=False)[source]
Construct a cross visibility graph between two time series.
A cross visibility graph connects points from different series if they are visible to each other. Visibility is determined by the visibility criterion applied across series boundaries.
- Parameters:
x1 (array (n1,)) – First time series
x2 (array (n2,)) – Second time series (can have different length)
method (str, default "hvg") – Visibility method: “hvg” (horizontal) or “nvg” (natural)
weighted (bool or str, default False) – If True, use “absdiff” weight mode. If str, use that weight mode.
weight_mode (str, optional) – Explicit weight mode (overrides weighted if provided)
limit (int, optional) – Maximum temporal distance for visibility
directed (bool, default False) – If True, create directed graph
- Returns:
G (networkx.Graph or DiGraph) – Cross visibility graph (bipartite: nodes 0..n1-1 from x1, n1..n1+n2-1 from x2)
A (array (n1+n2, n1+n2)) – Adjacency matrix
- Return type:
Tuple[Graph, ndarray[tuple[Any, …], dtype[_ScalarT]]]
Examples
>>> import numpy as np >>> x1 = np.random.randn(50) >>> x2 = np.random.randn(50) >>> G, A = cross_visibility_graph(x1, x2, method="hvg") >>> print(f"Cross visibility: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges")
- ts2net.multivariate.joint_recurrence_network(x1, x2, threshold=None, k=None, method='epsilon', metric='euclidean', weighted=False, directed=False)[source]
Construct a joint recurrence network from two time series.
A joint recurrence occurs when both series are recurrent at the same time. An edge (i, j) exists if: - Series 1: points i and j are recurrent (within threshold or k-NN) - Series 2: points i and j are recurrent (within threshold or k-NN)
- Parameters:
x1 (array (n,)) – First time series
x2 (array (n,)) – Second time series (must have same length as x1)
threshold (float, optional) – Distance threshold for epsilon recurrence (required if method=”epsilon”)
k (int, optional) – Number of nearest neighbors for k-NN recurrence (required if method=”knn”)
method (str, default "epsilon") – Recurrence method: “epsilon” (threshold-based) or “knn” (k-nearest neighbors)
metric (str, default "euclidean") – Distance metric (only used for embedding if needed)
weighted (bool, default False) – If True, weight edges by average distance
directed (bool, default False) – If True, create directed graph
- Returns:
G (networkx.Graph or DiGraph) – Joint recurrence network
A (array (n, n)) – Adjacency matrix
- Return type:
Tuple[Graph, ndarray[tuple[Any, …], dtype[_ScalarT]]]
Examples
>>> import numpy as np >>> x1 = np.random.randn(100) >>> x2 = np.random.randn(100) >>> G, A = joint_recurrence_network(x1, x2, threshold=0.5, method="epsilon") >>> print(f"Joint recurrence network: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges")
- ts2net.multivariate.net_enn(D, epsilon=None, percentile=None, weighted=False, directed=False)[source]
ε-Nearest Neighbors network from distance matrix.
Nodes are connected if distance < ε.
- Parameters:
D (array (n, n)) – Distance matrix
epsilon (float, optional) – Distance threshold (connect if D[i,j] < epsilon)
percentile (float, optional) – Use percentile of distances as epsilon (0-100) If both epsilon and percentile given, epsilon takes precedence
weighted (bool) – If True, edge weights = distances
directed (bool) – If True, create directed graph
- Returns:
G (networkx.Graph or DiGraph) – ε-NN network
A (array (n, n)) – Adjacency matrix
- Return type:
Tuple[Graph, ndarray]
Examples
>>> D = np.random.rand(10, 10) >>> # Connect top 30% shortest distances >>> G, A = net_enn(D, percentile=30, weighted=False)
- ts2net.multivariate.net_enn_approx(D, epsilon=None, percentile=None, metric='precomputed', n_neighbors=50, weighted=False, directed=False)[source]
Approximate ε-NN network using PyNNDescent.
Faster than exact ε-NN for large datasets, but may miss some edges.
- Parameters:
D (array (n, n)) – Distance matrix or feature matrix
epsilon (float, optional) – Distance threshold
percentile (float, optional) – Use percentile of distances (if epsilon is None)
metric (str) – ‘precomputed’ or distance metric name
n_neighbors (int) – Number of neighbors to search (larger = more accurate)
weighted (bool) – If True, edge weights = distances
directed (bool) – If True, create directed graph
- Returns:
G (networkx.Graph or DiGraph) – Approximate ε-NN network
A (array (n, n)) – Adjacency matrix
- Return type:
Tuple[Graph, ndarray]
Notes
Requires: pip install pynndescent
- ts2net.multivariate.net_knn(D, k, mutual=False, weighted=False, directed=False)[source]
k-Nearest Neighbors network from distance matrix.
Each node is connected to its k nearest neighbors.
- Parameters:
D (array (n, n)) – Distance matrix (smaller = more similar)
k (int) – Number of nearest neighbors per node
mutual (bool) – If True, require mutual k-NN (i in kNN(j) AND j in kNN(i))
weighted (bool) – If True, edge weights = distances
directed (bool) – If True, create directed graph (i → j if j in kNN(i))
- Returns:
G (networkx.Graph or DiGraph) – k-NN network
A (array (n, n)) – Adjacency matrix (weighted if weighted=True)
- Return type:
Tuple[Graph, ndarray]
Examples
>>> D = np.random.rand(10, 10) >>> D = (D + D.T) / 2 # Make symmetric >>> np.fill_diagonal(D, 0) >>> G, A = net_knn(D, k=3, mutual=False, weighted=True) >>> G.number_of_edges() 30
- ts2net.multivariate.net_knn_approx(D, k, metric='precomputed', n_neighbors=15, weighted=False, directed=False)[source]
Approximate k-NN network using PyNNDescent.
Much faster than exact k-NN for large datasets (>1000 nodes), but may miss some nearest neighbors.
- Parameters:
D (array (n, n)) – Distance matrix (if metric=’precomputed’) OR raw feature matrix (if metric=’euclidean’, etc.)
k (int) – Number of nearest neighbors
metric (str) – ‘precomputed’ (use D as distance matrix) OR ‘euclidean’, ‘cosine’, ‘manhattan’, etc. (compute on the fly)
n_neighbors (int) – Number of neighbors for approximation (>= k, larger = more accurate)
weighted (bool) – If True, edge weights = distances
directed (bool) – If True, create directed graph
- Returns:
G (networkx.Graph or DiGraph) – Approximate k-NN network
A (array (n, n)) – Adjacency matrix
- Return type:
Tuple[Graph, ndarray]
Notes
Requires: pip install pynndescent
Speed comparison (n=10,000 nodes): - Exact k-NN: ~2 minutes - Approximate k-NN: ~3 seconds (40x faster)
Examples
>>> # For very large datasets >>> X = np.random.randn(10000, 1000) # 10k series, 1k points each >>> G, A = net_knn_approx(X, k=10, metric='euclidean')
>>> # Or with precomputed distances >>> D = ts_dist(X, method='correlation', n_jobs=-1) >>> G, A = net_knn_approx(D, k=10, metric='precomputed')
- ts2net.multivariate.net_weighted(D, threshold=None, directed=False)[source]
Complete weighted network from distance matrix.
All pairs connected with edge weight = distance.
- Parameters:
D (array (n, n)) – Distance matrix
threshold (float, optional) – Remove edges with distance > threshold
directed (bool) – If True, create directed graph
- Returns:
G (networkx.Graph or DiGraph) – Weighted network
A (array (n, n)) – Adjacency matrix (weighted)
- Return type:
Tuple[Graph, ndarray]
Examples
>>> D = np.random.rand(10, 10) >>> G, A = net_weighted(D, threshold=0.5)
- ts2net.multivariate.network_comparison_metrics(networks, names=None)[source]
Compute comparison metrics for multiple networks.
- Parameters:
networks (list of networkx.Graph) – List of networks to compare
names (list of str, optional) – Names for each network
- Returns:
metrics – Dictionary with comparison metrics: - density_similarity: Pairwise density correlations - degree_correlation: Pairwise degree sequence correlations - edge_overlap: Pairwise edge overlap (Jaccard similarity) - structural_similarity: Overall structural similarity matrix
- Return type:
dict
- ts2net.multivariate.ts_dist(X, method='correlation', n_jobs=1, **kwargs)[source]
Calculate pairwise distance matrix between multiple time series.
- Parameters:
X (array (n_series, n_timepoints)) – Multiple time series to compare
method (str) – Distance function: ‘correlation’, ‘ccf’, ‘dtw’, ‘nmi’, ‘es’
n_jobs (int) – Number of parallel workers (-1 = all cores)
**kwargs – Distance-specific parameters
- Returns:
D – Distance matrix (symmetric, diagonal = 0)
- Return type:
array (n_series, n_series)
Examples
>>> import numpy as np >>> X = np.random.randn(10, 100) >>> D = ts_dist(X, method='correlation', n_jobs=-1) >>> D.shape (10, 10)
- ts2net.multivariate.ts_dist_part(X, start_idx, end_idx, method='correlation', **kwargs)[source]
Calculate partial distance matrix for HPC batch processing.
- Parameters:
X (array (n_series, n_timepoints)) – All time series
start_idx (int) – Start row index (inclusive)
end_idx (int) – End row index (exclusive)
method (str) – Distance function name
**kwargs – Distance-specific parameters
- Returns:
D_part – Partial distance matrix (rows start_idx:end_idx)
- Return type:
array (end_idx - start_idx, n_series)
Examples
>>> # On cluster node 1 >>> D_part = ts_dist_part(X, 0, 100, method='dtw') >>> np.save('D_part_0_100.npy', D_part)
- ts2net.multivariate.ts_to_windows(x, width, by=1, start=0, end=None)[source]
Extract sliding windows from a time series.
This function is equivalent to R ts2net’s ts_to_windows() and enables proximity network construction where each window becomes a node.
- Parameters:
x (array (n_points,)) – Input time series
width (int) – Window width (number of time points per window)
by (int) – Step size between consecutive windows
start (int) – Starting index (0-based)
end (int, optional) – Ending index (exclusive). If None, use len(x)
- Returns:
windows – Matrix where each row is a window
- Return type:
array (n_windows, width)
Examples
>>> x = np.sin(np.linspace(0, 4*np.pi, 100)) >>> windows = ts_to_windows(x, width=10, by=1) >>> windows.shape (91, 10)
>>> # Build proximity network from windows >>> from ts2net.multivariate import ts_dist, net_enn >>> D = ts_dist(windows, method='correlation', n_jobs=-1) >>> G, A = net_enn(D, percentile=20)
Notes
This implements the R ts2net approach for single time series: 1. Extract sliding windows 2. Treat each window as a time series 3. Calculate pairwise distances 4. Construct network (k-NN, ε-NN, etc.)
- ts2net.multivariate.ts_to_windows_labeled(x, width, by=1)[source]
Extract windows with temporal labels.
Returns both windows and their starting indices for temporal analysis.
- Parameters:
x (array) – Input time series
width (int) – Window width
by (int) – Step size
- Returns:
windows (array (n_windows, width)) – Window matrix
indices (array (n_windows,)) – Starting index of each window
- Return type:
tuple
Examples
>>> x = np.arange(100) >>> windows, indices = ts_to_windows_labeled(x, width=10, by=5) >>> indices[:5] array([ 0, 5, 10, 15, 20])
- ts2net.multivariate.ts_to_windows_list(X, width, by=1)[source]
Extract windows from multiple time series and concatenate.
- Parameters:
X (list of arrays) – List of time series
width (int) – Window width
by (int) – Step size
- Returns:
windows – All windows from all series
- Return type:
array (total_windows, width)
Examples
>>> series_list = [np.random.randn(100) for _ in range(5)] >>> windows = ts_to_windows_list(series_list, width=10, by=5)
- ts2net.multivariate.ts_window_stats(windows)[source]
Calculate statistics for each window.
Useful for feature extraction before network construction.
- Parameters:
windows (array (n_windows, width)) – Window matrix
- Returns:
stats – Dictionary with arrays of statistics: - mean, std, min, max, median - skewness, kurtosis - trend (linear regression slope)
- Return type:
dict
Examples
>>> windows = ts_to_windows(x, width=10, by=1) >>> stats = ts_window_stats(windows) >>> print(stats['mean'].shape) (n_windows,)
Distances
I/O
Polars-based Parquet ingestion for time series data.
This module provides efficient lazy-loading of time series from Parquet files using Polars, converting to NumPy arrays for use with ts2net core algorithms.
- ts2net.io_polars.load_series_from_parquet_polars(path, time_col, value_col, id_col=None, start=None, end=None, freq=None, agg='mean', tz=None, columns_extra=None)[source]
Load time series from Parquet file using Polars (lazy evaluation).
Uses lazy evaluation to minimize memory usage. Converts to NumPy arrays for compatibility with ts2net core algorithms.
- Parameters:
path (str) – Path to Parquet file or directory of Parquet files
time_col (str) – Column name for timestamps
value_col (str) – Column name for values
id_col (str, optional) – Column name for series identifier (e.g., meter_id, region) If None, returns single series as tuple (times, values)
start (str, optional) – Start timestamp filter (ISO format or parseable by Polars)
end (str, optional) – End timestamp filter (ISO format or parseable by Polars)
freq (str, optional) – Time frequency for bucketing (e.g., ‘1h’, ‘1d’, ‘15m’) Uses Polars group_by_dynamic for efficient time-based aggregation
agg (str, default 'mean') – Aggregation function: ‘mean’, ‘sum’, ‘min’, ‘max’, ‘median’, ‘first’, ‘last’
tz (str, optional) – Timezone for time_col (e.g., ‘UTC’, ‘Europe/Madrid’)
columns_extra (list[str], optional) – Additional columns to keep in output (not used for aggregation)
- Returns:
If id_col is provided: dict mapping id -> values array If id_col is None: tuple of (times, values) arrays
- Return type:
dict[str, np.ndarray] or tuple[np.ndarray, np.ndarray]
Examples
>>> # Single series >>> times, values = load_series_from_parquet_polars( ... 'data.parquet', time_col='timestamp', value_col='consumption' ... )
>>> # Multiple series by meter_id >>> series = load_series_from_parquet_polars( ... 'data.parquet', ... time_col='timestamp', ... value_col='consumption', ... id_col='meter_id', ... freq='1h', ... start='2024-01-01', ... end='2024-12-31' ... ) >>> # series = {'meter_1': np.array([...]), 'meter_2': np.array([...]), ...}
Columnar data adapters for ts2net.
Provides thin adapters that convert pandas/polars DataFrames to NumPy arrays for use with ts2net core algorithms. Core algorithms remain pure NumPy.
- ts2net.io_adapters.from_pandas(df, value_col, group_col=None, time_col=None, sort_by_time=True)[source]
Convert pandas DataFrame to NumPy arrays for ts2net.
- Parameters:
df (pd.DataFrame) – Input DataFrame
value_col (str) – Column name for time series values
group_col (str, optional) – Column name for grouping (e.g., meter_id, region) If provided, returns dict mapping group -> values array
time_col (str, optional) – Column name for timestamps (used for sorting only)
sort_by_time (bool, default True) – If True and time_col provided, sort by time
- Returns:
If group_col is None: single array of values If group_col is provided: dict mapping group -> values array
- Return type:
np.ndarray or dict[str, np.ndarray]
Examples
>>> import pandas as pd >>> df = pd.DataFrame({'timestamp': pd.date_range('2024-01-01', periods=100, freq='1h'), ... 'consumption': np.random.randn(100), ... 'meter_id': ['meter_1'] * 100}) >>> # Single series >>> values = from_pandas(df, value_col='consumption', time_col='timestamp') >>> # Multiple series >>> series = from_pandas(df, value_col='consumption', group_col='meter_id', time_col='timestamp')
- ts2net.io_adapters.from_polars(df, value_col, group_col=None, time_col=None, sort_by_time=True)[source]
Convert polars DataFrame to NumPy arrays for ts2net.
- Parameters:
df (pl.DataFrame) – Input DataFrame
value_col (str) – Column name for time series values
group_col (str, optional) – Column name for grouping (e.g., meter_id, region) If provided, returns dict mapping group -> values array
time_col (str, optional) – Column name for timestamps (used for sorting only)
sort_by_time (bool, default True) – If True and time_col provided, sort by time
- Returns:
If group_col is None: single array of values If group_col is provided: dict mapping group -> values array
- Return type:
np.ndarray or dict[str, np.ndarray]
Examples
>>> import polars as pl >>> df = pl.DataFrame({ ... 'timestamp': pl.datetime_range(pl.date(2024, 1, 1), pl.date(2024, 1, 5), '1h', eager=True), ... 'consumption': np.random.randn(97), ... 'meter_id': ['meter_1'] * 97 ... }) >>> # Single series >>> values = from_polars(df, value_col='consumption', time_col='timestamp') >>> # Multiple series >>> series = from_polars(df, value_col='consumption', group_col='meter_id', time_col='timestamp')
BSTS (Bayesian Structural Time Series)
Bayesian Structural Time Series (BSTS) decomposition and residual topology analysis.
This module provides structural decomposition of time series and network analysis of residuals to separate predictable structure from irregular dynamics.
- class ts2net.bsts.BSTSSpec(level=True, trend=False, seasonal_periods=None, robust=False, standardize_residual=True)[source]
Bases:
objectSpecification for structural time series decomposition.
- Parameters:
level (bool, default True) – Include local level component
trend (bool, default False) – Include local linear trend
seasonal_periods (list of int, optional) – Seasonal periods (e.g., [24, 168] for hourly data with daily/weekly seasonality)
robust (bool, default False) – Use Student-t errors for heavy tails (slower, more robust)
standardize_residual (bool, default True) – Standardize residual before analysis (recommended)
- level: bool = True
- robust: bool = False
- seasonal_periods: List[int] | None = None
- standardize_residual: bool = True
- trend: bool = False
- class ts2net.bsts.FeaturesResult(raw_stats, structural_stats, residual_network_stats)[source]
Bases:
objectResult of feature extraction with BSTS decomposition.
- Parameters:
raw_stats (Dict[str, Any])
structural_stats (Dict[str, Any])
residual_network_stats (Dict[str, Any])
- raw_stats
Basic statistics of raw series (mean, std, min, max, etc.)
- Type:
dict
- structural_stats
Structural component statistics (variances, seasonal strength, etc.)
- Type:
dict
- residual_network_stats
Network statistics computed on residual (HVG, NVG, transition)
- Type:
dict
- raw_stats: Dict[str, Any]
- residual_network_stats: Dict[str, Any]
- structural_stats: Dict[str, Any]
- ts2net.bsts.decompose(series, spec)[source]
Decompose time series into structural components using state space model.
Uses statsmodels state space models for fast MLE estimation.
- Parameters:
series (array) – Input time series
spec (BSTSSpec) – Decomposition specification
- Returns:
Components, residual, and variance estimates
- Return type:
DecompositionResult
- Raises:
ImportError – If statsmodels is not installed
ValueError – If series is too short or constant
- ts2net.bsts.features(series, methods=None, bsts=None, window=None, nvg_limit=None)[source]
Extract features from time series with optional BSTS decomposition.
If BSTS is enabled, decomposes series and analyzes residual with network methods. If BSTS is disabled, analyzes raw series.
- Parameters:
series (array) – Input time series
methods (list of str, optional) – Network methods to apply: ‘hvg’, ‘nvg’, ‘transition’ Default: [‘hvg’, ‘transition’]
bsts (BSTSSpec, optional) – BSTS decomposition specification. If None, analyzes raw series.
window (int, optional) – Window size for windowed analysis. If None, analyzes full series.
nvg_limit (int, optional) – Horizon limit for NVG (default: 3000)
- Returns:
Three blocks: raw_stats, structural_stats, residual_network_stats
- Return type:
Examples
>>> from ts2net.bsts import features, BSTSSpec >>> spec = BSTSSpec(level=True, seasonal_periods=[24, 168]) >>> result = features(x, methods=['hvg', 'transition'], bsts=spec) >>> print(result.structural_stats['seasonal_strength']) >>> print(result.residual_network_stats['hvg']['avg_degree'])
Temporal CNN
Temporal CNN for time series feature extraction.
Provides a simple 1D dilated CNN for fast, stable feature extraction from time series windows.
- ts2net.temporal_cnn.temporal_cnn_embeddings(x, window, stride, *, channels=(32, 64, 64), kernel_size=5, dilations=(1, 2, 4), dropout=0.1, device='cpu', batch_size=256, seed=7)[source]
Compute per-window embeddings with a small dilated 1D CNN.
- Parameters:
x (ndarray[tuple[Any, ...], dtype[float64]]) – Array of shape (n, f) or (n,). For multivariate, f is number of features.
window (int) – Window length in time steps.
stride (int) – Step between windows.
channels (Tuple[int, ...]) – Output channels per conv block. Length must match dilations.
kernel_size (int) – Kernel size for each conv.
dilations (Tuple[int, ...]) – Dilation per block. Length must match channels length.
dropout (float) – Dropout rate.
device (str) – Torch device string (‘cpu’ or ‘cuda’).
batch_size (int) – Batch size for inference.
seed (int) – Random seed for determinism.
- Returns:
Array of shape (n_windows, channels[-1]) with embeddings.
- Raises:
ImportError – If PyTorch is not installed.
ValueError – If input shape is invalid or parameters don’t match.
- Return type:
ndarray[tuple[Any, …], dtype[float64]]
CLI
Configuration
Configuration schemas for ts2net YAML-based pipeline.
Provides type-safe, validated configuration classes using dataclasses.
- class ts2net.config.BSTSConfig(enabled=False, level=True, trend=False, seasonal_periods=None, robust=False, standardize_residual=True, max_points=10000, window=None)[source]
Bases:
objectBSTS decomposition configuration.
- Parameters:
enabled (bool)
level (bool)
trend (bool)
seasonal_periods (List[int] | None)
robust (bool)
standardize_residual (bool)
max_points (int)
window (int | None)
- enabled: bool = False
- level: bool = True
- max_points: int = 10000
- robust: bool = False
- seasonal_periods: List[int] | None = None
- standardize_residual: bool = True
- trend: bool = False
- window: int | None = None
- class ts2net.config.DatasetConfig(name, path, id_col=None, time_col='timestamp', value_col='value', start=None, end=None, tz=None)[source]
Bases:
objectDataset configuration.
- Parameters:
name (str)
path (str)
id_col (str | None)
time_col (str)
value_col (str)
start (str | None)
end (str | None)
tz (str | None)
- end: str | None = None
- id_col: str | None = None
- name: str
- path: str
- start: str | None = None
- time_col: str = 'timestamp'
- tz: str | None = None
- value_col: str = 'value'
- class ts2net.config.GraphsConfig(hvg=<factory>, nvg=<factory>, recurrence=<factory>, transition=<factory>)[source]
Bases:
objectGraph methods configuration.
- Parameters:
hvg (HVGConfig)
nvg (NVGConfig)
recurrence (RecurrenceConfig)
transition (TransitionConfig)
- classmethod from_dict(data)[source]
Create GraphsConfig from dictionary.
- Parameters:
data (Dict[str, Any])
- Return type:
- recurrence: RecurrenceConfig
- transition: TransitionConfig
- class ts2net.config.HVGConfig(enabled=False, output='stats', weighted=False, weight_mode=None, limit=None, directed=False)[source]
Bases:
objectHorizontal Visibility Graph configuration.
- Parameters:
enabled (bool)
output (str)
weighted (bool)
weight_mode (str | None)
limit (int | None)
directed (bool)
- directed: bool = False
- enabled: bool = False
- limit: int | None = None
- output: str = 'stats'
- weight_mode: str | None = None
- weighted: bool = False
- class ts2net.config.LoggingConfig(log_errors=True, error_path=None)[source]
Bases:
objectLogging configuration.
- Parameters:
log_errors (bool)
error_path (str | None)
- error_path: str | None = None
- log_errors: bool = True
- class ts2net.config.NVGConfig(enabled=False, output='stats', weighted=False, weight_mode=None, limit=None, max_edges=None, max_edges_per_node=None, max_memory_mb=None)[source]
Bases:
objectNatural Visibility Graph configuration.
- Parameters:
enabled (bool)
output (str)
weighted (bool)
weight_mode (str | None)
limit (int | None)
max_edges (int | None)
max_edges_per_node (int | None)
max_memory_mb (int | None)
- enabled: bool = False
- limit: int | None = None
- max_edges: int | None = None
- max_edges_per_node: int | None = None
- max_memory_mb: int | None = None
- output: str = 'stats'
- weight_mode: str | None = None
- weighted: bool = False
- class ts2net.config.OutputConfig(format='parquet', path='results/output.parquet', overwrite=True, mode=None)[source]
Bases:
objectOutput configuration.
- Parameters:
format (str)
path (str)
overwrite (bool)
mode (str | None)
- format: str = 'parquet'
- mode: str | None = None
- overwrite: bool = True
- path: str = 'results/output.parquet'
- class ts2net.config.PipelineConfig(dataset, graphs, output, sampling=<factory>, windows=<factory>, bsts=<factory>, logging=<factory>)[source]
Bases:
objectComplete pipeline configuration.
- Parameters:
dataset (DatasetConfig)
graphs (GraphsConfig)
output (OutputConfig)
sampling (SamplingConfig)
windows (WindowsConfig)
bsts (BSTSConfig)
logging (LoggingConfig)
- bsts: BSTSConfig
- dataset: DatasetConfig
- classmethod from_dict(data)[source]
Create PipelineConfig from dictionary (e.g., from YAML).
- Parameters:
data (Dict[str, Any])
- Return type:
- classmethod from_yaml(yaml_path)[source]
Load configuration from YAML file.
- Parameters:
yaml_path (str | Path)
- Return type:
- graphs: GraphsConfig
- logging: LoggingConfig
- output: OutputConfig
- sampling: SamplingConfig
- windows: WindowsConfig
- class ts2net.config.RecurrenceConfig(enabled=False, output='stats', rule='knn', k=10, m=None, tau=1, epsilon=0.1, metric='euclidean')[source]
Bases:
objectRecurrence Network configuration.
- Parameters:
enabled (bool)
output (str)
rule (str)
k (int)
m (int | None)
tau (int)
epsilon (float)
metric (str)
- enabled: bool = False
- epsilon: float = 0.1
- k: int = 10
- m: int | None = None
- metric: str = 'euclidean'
- output: str = 'stats'
- rule: str = 'knn'
- tau: int = 1
- class ts2net.config.SamplingConfig(frequency=None, agg='mean', resample=False)[source]
Bases:
objectSampling/resampling configuration.
- Parameters:
frequency (str | None)
agg (str)
resample (bool)
- agg: str = 'mean'
- frequency: str | None = None
- resample: bool = False
- class ts2net.config.TransitionConfig(enabled=False, output='stats', symbolizer='ordinal', order=3, n_states=None, partition_mode=False)[source]
Bases:
objectTransition Network configuration.
- Parameters:
enabled (bool)
output (str)
symbolizer (str)
order (int)
n_states (int | None)
partition_mode (bool)
- enabled: bool = False
- n_states: int | None = None
- order: int = 3
- output: str = 'stats'
- partition_mode: bool = False
- symbolizer: str = 'ordinal'
Factory
Graph builder factory for creating network builders from configuration.
Uses dispatch dictionary pattern for clean, extensible graph creation.
- ts2net.factory.aggregate_stats(stats, aggregate)[source]
Aggregate statistics using dispatch pattern.
- Parameters:
stats (dict) – Statistics dictionary from graph builder
aggregate (str) – Aggregation function: ‘mean’, ‘std’, ‘min’, ‘max’
- Returns:
Aggregated statistic value
- Return type:
float
- ts2net.factory.build_graph_from_config(series, graph_type, config, include_triangles=False)[source]
Build a graph from configuration and return statistics.
- Parameters:
series (array) – Input time series
graph_type (str) – Graph type: ‘hvg’, ‘nvg’, ‘recurrence’, or ‘transition’
config (GraphConfig) – Configuration object for the graph type
include_triangles (bool) – Whether to include triangle counting in stats (computationally expensive)
- Returns:
Graph statistics dictionary
- Return type:
dict
- ts2net.factory.create_graph_builder(graph_type, config, n_points=None)[source]
Create a graph builder from configuration using dispatch pattern.
- Parameters:
graph_type (str) – Graph type: ‘hvg’, ‘nvg’, ‘recurrence’, or ‘transition’
config (GraphConfig) – Configuration object for the graph type
n_points (int, optional) – Number of points in series (used for safety checks)
- Returns:
Configured graph builder instance
- Return type:
GraphBuilder
- Raises:
ValueError – If graph_type is unknown or configuration is invalid
- ts2net.factory.create_recurrence_builder(config, n_points=None)[source]
Create RecurrenceNetwork builder from configuration.
- Parameters:
config (RecurrenceConfig)
n_points (int | None)
- Return type:
- ts2net.factory.create_transition_builder(config)[source]
Create TransitionNetwork builder from configuration.
- Parameters:
config (TransitionConfig)
- Return type:
Spatial
Spatial analysis utilities for ts2net.
This module provides functions for spatial weights matrix generation.