API Reference

network_properties(graphs[, graph_labels, ...])

Compute comprehensive network properties for a collection of graphs.

calculate_centralities(graphs[, ...])

Compute comprehensive centrality measures for nodes across multiple graphs.

communities_measures(graphs[, graph_labels, ...])

Detect and analyze community structures using multiple algorithms.

vertex_properties(graphs, node_name[, ...])

Compute and visualize properties of a specific node across multiple graphs.

compute_edge_dynamics(graphs[, graph_labels])

Compute edge formation and dissolution between consecutive graphs.

edge_formation(graphs[, graph_labels, ...])

Analyze and plot edge formation over time.

edge_dissolution(graphs[, graph_labels, ...])

Analyze and plot edge dissolution over time.

plot_edge_dynamics(dynamics_df, ...[, ...])

Plot edge formation/dissolution dynamics over time with gap handling.

plot_community_evolution(graphs, ...[, ...])

Create interactive animation of community evolution across temporal network.

detect_temporal_gaps(graph_labels[, ...])

Detect temporal gaps in a list of labels with detailed reporting.

snapshots_from_events(df, time_col, ...[, ...])

Bin a timestamped edge list into a sequence of igraph snapshots.

snapshots_from_edgelist(path, time_col, ...)

Load a timestamped edge list from a CSV file into snapshots.

snapshot_similarity(graphs[, graph_labels, ...])

Measure structural similarity between consecutive snapshots.

temporal_correlation_coefficient(graphs[, ...])

Average temporal correlation coefficient over the whole sequence.

inter_event_times(graphs[, graph_labels, ...])

Durations between consecutive activations of each edge or node.

burstiness_coefficient(graphs[, ...])

Goh-Barabasi burstiness coefficient per edge or node.

temporal_reachability(graphs[, ...])

Source–target reachability and first-arrival index for every node pair.

temporal_distances(graphs[, graph_labels, ...])

Time-respecting latency (in snapshot steps) for every source–target pair.

temporal_closeness(graphs[, graph_labels, ...])

Harmonic temporal closeness per node.

temporal_efficiency(graphs[, graph_labels, ...])

Global temporal efficiency of the snapshot sequence.

temporal_betweenness(graphs[, graph_labels, ...])

Per-node temporal betweenness over time-respecting paths.

detect_change_points(series_df[, columns, ...])

Detect change points in one or more metric time series.

flag_anomalous_snapshots(graphs[, ...])

Detect structurally anomalous snapshots from a graph sequence.

track_communities(graphs[, graph_labels, ...])

Match communities across snapshots and label lifecycle events.

plot_community_lineage(tracking_df, ...[, ...])

Timeline view of community lineages over the snapshot sequence.

Data ingestion

temporal_networks.snapshots_from_events(df, time_col, source_col, target_col, freq='M', directed=False, weight_col=None, label_format=None)[source]

Bin a timestamped edge list into a sequence of igraph snapshots.

Groups the events by time bin (freq) and builds one igraph.Graph per non-empty bin. All snapshots share the same (union) vertex set, keyed by node name, so the same node can be tracked across snapshots. Skipped bins (periods with no events) are simply absent from the output, which the package’s gap detector then reports as gaps.

Parameters:
  • df (pandas.DataFrame) – Event table with at least the time, source, and target columns.

  • time_col (str) – Name of the timestamp column (parseable by pandas.to_datetime).

  • source_col (str) – Names of the endpoint columns. Values are cast to str and used as vertex names.

  • target_col (str) – Names of the endpoint columns. Values are cast to str and used as vertex names.

  • freq (str, optional) – Pandas offset alias for the bin width (default "M" = monthly). Common values: "D" daily, "W" weekly, "M" monthly, "Q" quarterly, "Y" yearly.

  • directed (bool, optional) – If True, build directed graphs and treat (u, v) and (v, u) as distinct (default False).

  • weight_col (str, optional) – If given, edge weights are the sum of this (numeric) column over the events that map to each edge in each bin. If None (default), parallel events are collapsed and, when any collapsing occurs, edge weights are the event multiplicity.

  • label_format (str, optional) – Explicit strftime format for the snapshot labels. If None (default), a label is derived from freq that the gap detector can parse (e.g. "%Y-%m" monthly, "%Y-%m-%d" daily, YYYY-Qn quarterly, YYYY-Wnn weekly).

Returns:

  • graphs (list of igraph.Graph) – One graph per non-empty time bin, in chronological order. Vertices carry a name attribute; edges carry a weight attribute when weights are meaningful (see weight_col).

  • graph_labels (list of str) – Chronological labels, one per graph.

Raises:

ValueError – If a required column is missing, df is empty, the time column cannot be parsed or contains missing timestamps (NaT), no non-empty bins are produced, or label_format produces duplicate or unparseable labels.

Return type:

Tuple[List[Graph], List[str]]

Examples

>>> import pandas as pd
>>> from temporal_networks.io import snapshots_from_events
>>> events = pd.DataFrame({
...     "t": ["2024-01-05", "2024-01-20", "2024-03-02"],
...     "u": ["a", "b", "a"],
...     "v": ["b", "c", "c"],
... })
>>> graphs, labels = snapshots_from_events(events, "t", "u", "v", freq="M")
>>> labels
['2024-01', '2024-03']
>>> [g.ecount() for g in graphs]
[2, 1]
temporal_networks.snapshots_from_edgelist(path, time_col, source_col, target_col, **kwargs)[source]

Load a timestamped edge list from a CSV file into snapshots.

Thin convenience wrapper that reads path with pandas.read_csv and forwards to snapshots_from_events().

Parameters:
Returns:

  • graphs (list of igraph.Graph) – One graph per non-empty time bin.

  • graph_labels (list of str) – Chronological labels, one per graph.

Return type:

Tuple[List[Graph], List[str]]

Network-level analysis

temporal_networks.network_properties(graphs, graph_labels=None, filename=None, save_path=None, visualisation=True, report_gaps=False)[source]

Compute comprehensive network properties for a collection of graphs.

This function systematically analyzes a collection of networks, extracting multiple properties including node/edge counts, density, connectivity measures, and clustering coefficients.

KEY FEATURE: Automatically detects and reports temporal gaps in your data, showing you where discontinuities occur (seasonal closures, maintenance windows, missing measurements, etc.). Plots correctly show gaps as visual breaks.

Parameters:
  • graphs (list of igraph.Graph) – List of igraph.Graph objects to analyze

  • graph_labels (list of str, optional) – Labels for each graph (e.g., [“2019-01”, “2019-02”, …]) Supports multiple formats: YYYY-MM, YYYY-MM-DD, YYYY-W##, YYYY-Q#, YYYY If not provided, defaults to “Graph 1”, “Graph 2”, etc.

  • filename (str, optional) – If provided, saves numerical results to CSV with this filename

  • save_path (str, optional) – Directory path for saving visualizations. If None (default), no files are saved.

  • visualisation (bool, optional) – If True (default), generates plots for each numerical property

  • report_gaps (bool, optional) – If True, print a temporal gap report to the console (default: False)

Returns:

DataFrame containing network properties for each graph, with one row per graph and columns for each metric

Return type:

pandas.DataFrame

Examples

>>> import random
>>> import igraph as ig
>>> from temporal_networks import network_properties
>>> # Seed igraph's RNG so the snapshots are reproducible
>>> ig.set_random_number_generator(random.Random(42))
>>> graphs = [ig.Graph.Barabasi(n=50, m=2) for _ in range(12)]
>>> labels = [f"2024-{i + 1:02d}" for i in range(12)]
>>> props = network_properties(graphs, graph_labels=labels, report_gaps=False)
>>> props.shape
(12, 19)

Notes

Properties computed include: - Basic metrics: node count, edge count, density - Connectivity: diameter, average path length, strongly connected components - Local structure: clustering coefficient, reciprocity - Graph type: directed, weighted, bipartite, etc.

For undirected graphs, the “Strongly Connected Components” column equals the number of connected components (every undirected component is trivially strongly connected).

Gap Detection: - Automatically analyzes temporal labels - Reports if data has gaps (missing time periods) - Shows exactly where gaps occur - Plots preserve gaps as visual discontinuities

temporal_networks.calculate_centralities(graphs, graph_labels=None, filename=None, report_gaps=False, visualize_evolution=False, save_path=None)[source]

Compute comprehensive centrality measures for nodes across multiple graphs.

Calculates various centrality metrics for each node in a collection of networks, including degree, closeness, betweenness, eigenvector, PageRank, harmonic, eccentricity, clustering coefficient, and HITS scores.

KEY FEATURE: Automatically detects and reports temporal gaps in your data. Optionally visualizes how node centralities evolve over time with proper gap handling.

Parameters:
  • graphs (list of igraph.Graph) – List of igraph.Graph objects to analyze

  • graph_labels (list of str, optional) – Labels for each graph (e.g., [“2019-01”, “2019-02”, …]) Supports multiple formats: YYYY-MM, YYYY-MM-DD, YYYY-W##, YYYY-Q#, YYYY If not provided, defaults to “Graph 1”, “Graph 2”, etc.

  • filename (str, optional) – CSV filename for saving results. If None (default), results are not saved to file (no files are written unless a filename is given).

  • report_gaps (bool, optional) – If True, print a temporal gap report to the console (default: False)

  • visualize_evolution (bool, optional) – If True, creates plots showing how centrality measures evolve over time (default: False). This is useful for tracking important nodes. Requires save_path; a warning is emitted if it is missing.

  • save_path (str, optional) – Directory for saving visualizations. If None (default), no plot files are written.

Returns:

DataFrame with centrality measures, one row per node per graph. Columns include: Graph, Node, and various centrality measures

Return type:

pandas.DataFrame

Examples

>>> import random
>>> import igraph as ig
>>> from temporal_networks import calculate_centralities
>>> ig.set_random_number_generator(random.Random(42))
>>> graphs = [ig.Graph.Barabasi(n=50, m=2) for _ in range(12)]
>>> for g in graphs:
...     g.vs["name"] = [f"Node_{i}" for i in range(g.vcount())]
>>> labels = [f"2024-{i + 1:02d}" for i in range(12)]
>>> centralities = calculate_centralities(
...     graphs, graph_labels=labels, filename=None, report_gaps=False)
>>> centralities.shape
(600, 13)

Notes

Centrality measures computed: - Degree: Number of direct connections - Closeness: Average distance to all other nodes - Betweenness: Number of shortest paths node lies on - Eigenvector: Importance based on connections to important nodes - PageRank: Probabilistic measure of node importance - Harmonic: Closeness variant less sensitive to disconnected components - Eccentricity: Greatest distance to any other node - Clustering Coefficient: Tendency of neighbors to be connected - HITS Authority/Hub: Measures from hyperlink-induced topic search

Temporal Gaps: - Automatically analyzes temporal labels for gaps - Reports if data has missing periods - Temporal plots preserve gaps as visual breaks

Community analysis

temporal_networks.communities_measures(graphs, graph_labels=None, algorithms=None, save_path=None, visualisation=True, report_gaps=False)[source]

Detect and analyze community structures using multiple algorithms.

Applies various community detection algorithms to each graph in the temporal sequence and tracks how community structure evolves over time. Provides both detailed community membership and summary statistics.

Temporal gaps are detected automatically and plots show them as visual breaks.

Parameters:
  • graphs (list of igraph.Graph) – List of igraph.Graph objects to analyze

  • graph_labels (list of str, optional) – Labels for each graph (e.g., [“2019-01”, “2019-02”, …]) Supports multiple formats: YYYY-MM, YYYY-MM-DD, YYYY-W##, YYYY-Q#, YYYY If not provided, defaults to “Graph 1”, “Graph 2”, etc.

  • algorithms (list of str, optional) – Community detection algorithms to run. Available: "leiden", "louvain", "walktrap", "fast_greedy", "label_prop", "spinglass", "infomap". If None (default), all of them except "spinglass" are run — spinglass raises an error on any disconnected graph, so it must be requested explicitly (and only for connected snapshots).

  • save_path (str, optional) – Directory path for saving results and visualizations. If None (default), no files are saved.

  • visualisation (bool, optional) – If True (default), generates plots for community evolution

  • report_gaps (bool, optional) – If True, print a temporal gap report to the console (default: False)

Returns:

Dictionary with results for each algorithm, mapping algorithm names to DataFrames containing community assignments. Every requested algorithm is present as a key; an algorithm that failed on all graphs maps to an empty DataFrame (with a warning), never a missing key.

Return type:

dict

Raises:

ValueError – If algorithms contains an unknown algorithm name.

Warns:

UserWarning – When an algorithm fails on a graph (that snapshot is skipped for that algorithm) or produces no communities at all.

Examples

>>> import random
>>> import igraph as ig
>>> from temporal_networks import communities_measures
>>> ig.set_random_number_generator(random.Random(42))
>>> graphs = [ig.Graph.Barabasi(n=100, m=2) for _ in range(2)]
>>> labels = ["2019-01", "2019-02"]
>>> communities = communities_measures(
...     graphs, graph_labels=labels)

Notes

Community detection algorithms available:

  • Leiden: Optimizes modularity with refined granularity

  • Louvain: Fast modularity optimization

  • Walktrap: Uses random walks to find communities

  • Fast Greedy: Greedy optimization of modularity

  • Label Propagation: Fast method based on label propagation

  • Spinglass: Based on statistical mechanics (connected graphs only; opt-in via algorithms)

  • Infomap: Information-theoretic approach

Temporal Gaps:

  • Automatically analyzes temporal labels for gaps

  • Reports if data has missing periods

  • Community plots preserve gaps as visual breaks

temporal_networks.plot_community_evolution(graphs, community_algorithm, output_file='community_evolution.html', seed=None)[source]

Create interactive animation of community evolution across temporal network.

Generates an interactive Plotly animation showing how community structures detected by a specified algorithm evolve across a sequence of networks. Nodes are colored by community membership and animation allows frame-by-frame viewing of the temporal evolution.

Parameters:
  • graphs (list of igraph.Graph) – List of igraph.Graph objects to analyze. All graphs should have consistent node labels.

  • community_algorithm (str) – Community detection algorithm to use. Options: - “edge_betweenness” - “walktrap” - “fast_greedy” - “label_prop” - “spinglass” - “leiden” - “louvain”

  • output_file (str, optional) – Filename for saving the HTML animation (default: “community_evolution.html”)

  • seed (int, optional) – Seed for the random node positions used when graphs carry no “x”/”y” vertex attributes. Positions come from a local RNG, so the global random module state is never touched. If None (default), positions differ between runs.

Returns:

Saves output_file with interactive animation

Return type:

None

Examples

>>> import random
>>> import igraph as ig
>>> from temporal_networks import plot_community_evolution
>>> ig.set_random_number_generator(random.Random(42))
>>> graphs = [ig.Graph.Barabasi(n=50, m=2) for _ in range(12)]
>>> plot_community_evolution(
...     graphs, community_algorithm="louvain")

Notes

The animation creates one frame per graph, with playback controls: - Play: Animate through all frames - Pause: Stop animation - Restart: Return to first frame

Node positions are randomly assigned if not present in graph attributes. For better visualization, pre-compute positions (e.g., using Fruchterman-Reingold) and store as “x” and “y” vertex attributes.

Vertex-level analysis

temporal_networks.vertex_properties(graphs, node_name, graph_labels=None, filename=None, save_path=None, visualisation=True, report_gaps=False)[source]

Compute and visualize properties of a specific node across multiple graphs.

Tracks how various metrics for a single node evolve over time across a temporal network. Computes centrality measures, structural properties, and constraint metrics for the specified node.

KEY FEATURE: Automatically detects and reports temporal gaps in your data. Plots correctly show gaps as visual breaks.

Parameters:
  • graphs (list of igraph.Graph) – List of igraph.Graph objects to analyze

  • node_name (str) – Name/label of the node of interest (must match node attribute in graphs)

  • graph_labels (list of str, optional) – Labels for each graph (e.g., [“2019-01”, “2019-02”, …]) Supports multiple formats: YYYY-MM, YYYY-MM-DD, YYYY-W##, YYYY-Q#, YYYY If not provided, defaults to “Graph 1”, “Graph 2”, etc.

  • filename (str, optional) – CSV filename for saving results. If None, results are not saved.

  • save_path (str, optional) – Directory for saving visualizations. If None (default), plots are not saved.

  • visualisation (bool, optional) – If True (default), generates plots for each property over time

  • report_gaps (bool, optional) – If True, print a temporal gap report to the console (default: False)

Returns:

DataFrame with one row per graph, showing how the node’s properties evolve across time. Includes columns for each computed metric.

Return type:

pandas.DataFrame

Examples

>>> import random
>>> import igraph as ig
>>> from temporal_networks import vertex_properties
>>> ig.set_random_number_generator(random.Random(42))
>>> G1 = ig.Graph.Barabasi(n=50, m=2)
>>> G2 = ig.Graph.Barabasi(n=50, m=2)
>>> G1.vs["name"] = [f"Node_{i}" for i in range(50)]
>>> G2.vs["name"] = [f"Node_{i}" for i in range(50)]
>>> props = vertex_properties(
...     [G1, G2], node_name="Node_5",
...     graph_labels=["2019-01", "2019-02"], report_gaps=False)
>>> props.shape
(2, 13)

Notes

Properties computed for the node:

  • Centrality: degree, closeness, betweenness, eigenvector, PageRank, harmonic, eccentricity

  • Local structure: clustering coefficient, constraint

  • Importance: authority score, hub score, coreness

Temporal Gaps:

  • Automatically analyzes temporal labels for gaps

  • Reports if data has missing periods

  • Vertex property plots preserve gaps as visual breaks

Edge dynamics

temporal_networks.compute_edge_dynamics(graphs, graph_labels=None)[source]

Compute edge formation and dissolution between consecutive graphs.

Analyzes how the edge structure changes from one temporal snapshot to the next, computing the number of edges that appear (formed) and disappear (dissolved) at each time step.

Gap-aware: consecutive pairs that straddle a detected temporal gap are reported as NaN, so edge churn is never computed across missing data — consistent with snapshot_similarity().

Parameters:
  • graphs (list of igraph.Graph) – List of igraph.Graph objects representing consecutive time points

  • graph_labels (list of str, optional) – Labels for each graph (e.g., [“2019-01”, “2019-02”, …]) If not provided, defaults to “Graph 1”, “Graph 2”, etc.

Returns:

DataFrame with columns: - Graph: Label for the current time point - Edges_Formed: Number of new edges created - Edges_Dissolved: Number of edges removed - Edges_Formed_Percent: Percentage change relative to previous graph - Edges_Dissolved_Percent: Percentage change relative to previous graph

Gap-straddling pairs are NaN (which makes the count columns float for gapped data).

Return type:

pandas.DataFrame

Examples

>>> import igraph as ig
>>> from temporal_networks import compute_edge_dynamics
>>> graphs = [ig.Graph.Barabasi(n=50, m=2) for _ in range(12)]
>>> labels = [f"2019-{i+1:02d}" for i in range(12)]
>>> dynamics = compute_edge_dynamics(graphs, graph_labels=labels)

Notes

Comparison starts from the second graph. The first row corresponds to differences between Graph 0 and Graph 1.

Edges are matched by node name (or label) when those vertex attributes are present, so snapshots whose nodes are stored in a different order are still compared correctly. If no such attribute exists, vertex indices are used, which assumes a consistent node ordering across snapshots. Undirected edges are treated as unordered pairs.

temporal_networks.edge_formation(graphs, graph_labels=None, save_path=None, report_gaps=False)[source]

Analyze and plot edge formation over time.

Convenience function combining edge dynamics computation and visualization for edge formation specifically. Automatically detects and reports temporal gaps.

Parameters:
  • graphs (list of igraph.Graph) – List of igraph.Graph objects

  • graph_labels (list of str, optional) – Labels for each graph (e.g., [“2019-01”, “2019-02”, …]) If not provided, defaults to “Graph 1”, “Graph 2”, etc.

  • save_path (str, optional) – Directory for saving plots. If None (default), no file is saved.

  • report_gaps (bool, optional) – If True, print a temporal gap report to the console (default: False)

Returns:

DataFrame with edge dynamics

Return type:

pandas.DataFrame

Examples

>>> import random
>>> import igraph as ig
>>> from temporal_networks import edge_formation
>>> ig.set_random_number_generator(random.Random(42))
>>> graphs = [ig.Graph.Barabasi(n=30, m=2) for _ in range(6)]
>>> labels = [f"2024-{i + 1:02d}" for i in range(6)]
>>> dynamics = edge_formation(graphs, graph_labels=labels, report_gaps=False)
>>> dynamics.shape
(5, 5)
temporal_networks.edge_dissolution(graphs, graph_labels=None, save_path=None, report_gaps=False)[source]

Analyze and plot edge dissolution over time.

Convenience function combining edge dynamics computation and visualization for edge dissolution specifically. Automatically detects and reports temporal gaps.

Parameters:
  • graphs (list of igraph.Graph) – List of igraph.Graph objects

  • graph_labels (list of str, optional) – Labels for each graph (e.g., [“2019-01”, “2019-02”, …]) If not provided, defaults to “Graph 1”, “Graph 2”, etc.

  • save_path (str, optional) – Directory for saving plots. If None (default), no file is saved.

  • report_gaps (bool, optional) – If True, print a temporal gap report to the console (default: False)

Returns:

DataFrame with edge dynamics

Return type:

pandas.DataFrame

Examples

>>> import random
>>> import igraph as ig
>>> from temporal_networks import edge_dissolution
>>> ig.set_random_number_generator(random.Random(42))
>>> graphs = [ig.Graph.Barabasi(n=30, m=2) for _ in range(6)]
>>> labels = [f"2024-{i + 1:02d}" for i in range(6)]
>>> dynamics = edge_dissolution(graphs, graph_labels=labels, report_gaps=False)
>>> dynamics.shape
(5, 5)
temporal_networks.plot_edge_dynamics(dynamics_df, graph_labels, gap_info, metric='Edges_Formed', output_file=None, save_path=None)[source]

Plot edge formation/dissolution dynamics over time with gap handling.

Creates a line plot showing how edges are formed or dissolved at each time step. Properly shows gaps in temporal data as visual breaks.

Parameters:
  • dynamics_df (pd.DataFrame) – DataFrame from compute_edge_dynamics()

  • graph_labels (list of str) – Temporal labels

  • gap_info (dict) – Gap detection information

  • metric (str, optional) – Metric to plot: “Edges_Formed”, “Edges_Dissolved”, etc. (default: “Edges_Formed”)

  • output_file (str, optional) – Filename for saving the plot. If None, uses metric name. (default: None → “{metric}.pdf”)

  • save_path (str, optional) – Directory for saving plots. If None (default), no file is saved.

Returns:

Saves plot to file

Return type:

None

Notes

The plot uses gap-aware plotting to preserve temporal gaps. If you have data for Jan, Mar (Feb missing), the plot will show that gap visually instead of drawing a false line.

Examples

>>> import random
>>> import igraph as ig
>>> from temporal_networks import (compute_edge_dynamics, plot_edge_dynamics,
...                                detect_temporal_gaps)
>>> ig.set_random_number_generator(random.Random(42))
>>> graphs = [ig.Graph.Barabasi(n=30, m=2) for _ in range(6)]
>>> labels = [f"2024-{i + 1:02d}" for i in range(6)]
>>> dynamics = compute_edge_dynamics(graphs, graph_labels=labels)
>>> gap_info = detect_temporal_gaps(labels)
>>> plot_edge_dynamics(dynamics, labels, gap_info, metric="Edges_Formed")

Snapshot stability

temporal_networks.snapshot_similarity(graphs, graph_labels=None, save_path=None, report_gaps=False)[source]

Measure structural similarity between consecutive snapshots.

For each consecutive pair of graphs, computes how similar their edge sets are (Jaccard), what fraction of edges and active nodes survive, and the node-averaged temporal correlation. Comparison starts from the second graph, so the result has one row per consecutive pair.

Gap-aware: consecutive pairs that straddle a detected temporal gap are reported as NaN, so structure is never compared across missing data, and gap-aware plots break the line there.

Parameters:
  • graphs (list of igraph.Graph) – List of igraph.Graph objects representing consecutive time points.

  • graph_labels (list of str, optional) – Labels for each graph (e.g., [“2019-01”, “2019-02”, …]). If not provided, defaults to “Graph 1”, “Graph 2”, etc.

  • save_path (str, optional) – Directory for saving plots. If None (default), no file is saved.

  • report_gaps (bool, optional) – If True, print a temporal gap report to the console (default: False).

Returns:

One row per consecutive pair, with columns:

  • Graph: label of the current (later) snapshot

  • jaccard: intersection size divided by union size

  • edge_persistence: fraction of prior edges surviving

  • node_persistence: fraction of active nodes surviving

  • temporal_correlation: node-averaged topological overlap

Undefined ratios (e.g. an empty edge set) and gap-straddling pairs are NaN.

Return type:

pandas.DataFrame

Examples

>>> import igraph as ig
>>> from temporal_networks import snapshot_similarity
>>> g0 = ig.Graph(n=4, edges=[(0, 1), (1, 2)])
>>> g1 = ig.Graph(n=4, edges=[(1, 2), (2, 3)])
>>> labels = ["2024-01", "2024-02"]
>>> sim = snapshot_similarity([g0, g1], graph_labels=labels,
...                           report_gaps=False)
>>> round(float(sim.loc[0, "jaccard"]), 3)
0.333
>>> float(sim.loc[0, "edge_persistence"])
0.5
temporal_networks.temporal_correlation_coefficient(graphs, graph_labels=None)[source]

Average temporal correlation coefficient over the whole sequence.

Averages the node-averaged topological overlap across all consecutive pairs, skipping pairs that straddle a detected temporal gap. A value near 1 means neighbourhoods are highly stable over time; near 0 means they reshuffle from snapshot to snapshot.

Parameters:
  • graphs (list of igraph.Graph) – List of igraph.Graph objects representing consecutive time points.

  • graph_labels (list of str, optional) – Labels for each graph. If not provided, defaults to “Graph 1”, etc.

Returns:

The sequence-level temporal correlation coefficient, or NaN if no valid (non-gap, non-empty) consecutive pair exists.

Return type:

float

Examples

>>> import igraph as ig
>>> from temporal_networks import temporal_correlation_coefficient
>>> g = ig.Graph(n=4, edges=[(0, 1), (1, 2), (2, 3)])
>>> # Two identical snapshots -> perfectly correlated
>>> temporal_correlation_coefficient([g, g.copy()])
1.0

Burstiness & inter-event analysis

temporal_networks.inter_event_times(graphs, graph_labels=None, by='edge', exclude_gaps=True)[source]

Durations between consecutive activations of each edge or node.

For every entity, the snapshots in which it is active are ordered and each consecutive pair contributes one inter-event interval, measured in the time unit inferred from the labels (falling back to snapshot-index distance for non-datetime labels).

Gap-aware: intervals whose span crosses a detected temporal gap are flagged via spans_gap. When exclude_gaps is True (default) those intervals are dropped, so a data closure is not counted as a long quiet period.

Parameters:
  • graphs (list of igraph.Graph) – List of igraph.Graph objects representing consecutive time points.

  • graph_labels (list of str, optional) – Labels for each graph (e.g., [“2019-01”, “2019-02”, …]). If not provided, defaults to “Graph 1”, “Graph 2”, etc.

  • by (str, optional) – "edge" (default) to track edge activations, "node" to track node activations.

  • exclude_gaps (bool, optional) – If True (default), drop intervals that straddle a detected temporal gap. If False, keep them (still flagged via spans_gap).

Returns:

One row per inter-event interval, with columns:

  • entity: edge key "(u, v)" or node key

  • start_label / end_label: bounding snapshots of the interval

  • interval: duration in the inferred time unit

  • spans_gap: whether the interval crosses a detected data gap

Sorted by entity then snapshot order (chronological, not lexicographic). Empty input returns an empty DataFrame with these columns.

Return type:

pandas.DataFrame

Examples

>>> import igraph as ig
>>> from temporal_networks import inter_event_times
>>> on = ig.Graph(n=2, edges=[(0, 1)])
>>> off = ig.Graph(n=2)
>>> graphs = [on, off, on.copy()]  # edge active at snapshots 0 and 2
>>> labels = ["2024-01", "2024-02", "2024-03"]
>>> iet = inter_event_times(graphs, graph_labels=labels)
>>> list(iet["interval"])
[2.0]
>>> bool(iet.loc[0, "spans_gap"])
False
temporal_networks.burstiness_coefficient(graphs, graph_labels=None, by='edge', exclude_gaps=True, save_path=None, report_gaps=False)[source]

Goh-Barabasi burstiness coefficient per edge or node.

For each entity, the inter-event intervals are summarised by their mean and standard deviation, and the burstiness coefficient B = (sigma - mu) / (sigma + mu) is reported. B = -1 indicates a perfectly regular (periodic) activation pattern, B = 0 a Poisson-like one, and B approaching 1 an increasingly bursty (clustered) one.

Gap-aware: when exclude_gaps is True (default), intervals straddling a detected temporal gap are left out of the statistics, so a data closure is not read as a long inactive stretch.

Parameters:
  • graphs (list of igraph.Graph) – List of igraph.Graph objects representing consecutive time points.

  • graph_labels (list of str, optional) – Labels for each graph (e.g., [“2019-01”, “2019-02”, …]). If not provided, defaults to “Graph 1”, “Graph 2”, etc.

  • by (str, optional) – "edge" (default) to score edges, "node" to score nodes.

  • exclude_gaps (bool, optional) – If True (default), exclude gap-straddling intervals from the statistics.

  • save_path (str, optional) – Directory for saving the burstiness-distribution plot. If None (default), no file is saved.

  • report_gaps (bool, optional) – If True, print a temporal gap report to the console (default: False).

Returns:

One row per entity, with columns:

  • entity: edge/node key

  • n_events: number of active snapshots

  • mean_interval / std_interval: of the inter-event times

  • burstiness: B in [-1, 1]; NaN for entities with fewer than two events or no usable intervals

Empty input returns an empty DataFrame with these columns.

Return type:

pandas.DataFrame

Notes

The standard deviation is the population standard deviation (ddof=0), so an entity with a single usable interval has std_interval == 0 and burstiness == -1 (maximally regular).

Examples

>>> import igraph as ig
>>> from temporal_networks import burstiness_coefficient
>>> g_on = ig.Graph(n=2, edges=[(0, 1)])
>>> graphs = [g_on, g_on.copy(), g_on.copy()]  # active every snapshot
>>> labels = ["2024-01", "2024-02", "2024-03"]
>>> bdf = burstiness_coefficient(graphs, graph_labels=labels,
...                              report_gaps=False)
>>> int(bdf.loc[0, "n_events"])
3
>>> float(bdf.loc[0, "burstiness"])  # perfectly regular -> -1
-1.0

Time-respecting paths

Note

cross_gaps=False (the default) is the key differentiator: paths cannot cross a detected temporal gap, so a data closure is not assumed to be transparent to transmission. Pass cross_gaps=True for standard contact-sequence behaviour.

temporal_networks.temporal_reachability(graphs, graph_labels=None, allow_wait=True, cross_gaps=False)[source]

Source–target reachability and first-arrival index for every node pair.

Uses a forward BFS over the snapshot sequence: a node is reachable from source if there exists a time-respecting path — a sequence of hops each using an edge that appears in a later snapshot than the previous hop. Edges within one snapshot are simultaneous contacts, so a path traverses at most one edge per snapshot.

Gap-aware (default): with cross_gaps=False, a time-respecting path is valid only if it lies entirely within one continuous segment — no hop, and no waiting, across a detected temporal gap. A closure in the data is not assumed to be transparent to transmission. Paths within the post-gap segments still count (the source starts fresh paths in every segment), and first_arrival_idx is the earliest arrival over all segments. Pass cross_gaps=True for standard contact-sequence behaviour.

Parameters:
  • graphs (list of igraph.Graph) – Temporal snapshots in chronological order.

  • graph_labels (list of str, optional) – Labels for each snapshot. If None, defaults to “Graph 1”, etc.

  • allow_wait (bool, optional) – If True (default), a reached node may wait and use edges in later snapshots. If False, paths are strict: each node must move at the next available snapshot after it is reached.

  • cross_gaps (bool, optional) – If False (default), time-respecting paths cannot cross detected temporal gaps; paths within a single continuous segment remain valid. If True, gaps are ignored and the sequence is treated as contiguous.

Returns:

One row per ordered (source, target) pair — including self-pairs — with columns:

  • source, target: node identity keys

  • reachable: True if a time-respecting path exists

  • first_arrival_idx: snapshot step of first arrival, or NaN

Self-pairs have first_arrival_idx = 0. Returns an empty DataFrame with the correct columns on empty or all-failing input.

Return type:

pandas.DataFrame

Examples

>>> import igraph as ig
>>> from temporal_networks import temporal_reachability
>>> g0 = ig.Graph(n=3, edges=[(0, 1)])
>>> g1 = ig.Graph(n=3, edges=[(1, 2)])
>>> df = temporal_reachability([g0, g1], graph_labels=["t0", "t1"])
>>> bool(df[(df.source == 0) & (df.target == 2)]["reachable"].iloc[0])
True
>>> int(df[(df.source == 0) & (df.target == 2)]["first_arrival_idx"].iloc[0])
2
temporal_networks.temporal_distances(graphs, graph_labels=None, allow_wait=True, cross_gaps=False)[source]

Time-respecting latency (in snapshot steps) for every source–target pair.

Latency is the snapshot step at which the target is first reached when BFS starts at step 0. Unreachable pairs have latency inf; self-pairs have latency 0.

Parameters:
  • graphs (list of igraph.Graph) – Temporal snapshots in chronological order.

  • graph_labels (list of str, optional) – Labels for each snapshot. If None, defaults to “Graph 1”, etc.

  • allow_wait (bool, optional) – If True (default), waiting at intermediate nodes is permitted.

  • cross_gaps (bool, optional) – If False (default), paths cannot cross detected temporal gaps; paths within a single continuous segment remain valid.

Returns:

One row per (source, target) pair with columns:

  • source, target: node identity keys

  • latency: float snapshot steps (0 for self, inf if unreachable)

Return type:

pandas.DataFrame

Examples

>>> import igraph as ig
>>> from temporal_networks import temporal_distances
>>> g0 = ig.Graph(n=3, edges=[(0, 1)])
>>> g1 = ig.Graph(n=3, edges=[(1, 2)])
>>> dist = temporal_distances([g0, g1], graph_labels=["t0", "t1"])
>>> float(dist[(dist.source == 0) & (dist.target == 2)]["latency"].iloc[0])
2.0
temporal_networks.temporal_closeness(graphs, graph_labels=None, cross_gaps=False, save_path=None, report_gaps=False)[source]

Harmonic temporal closeness per node.

For each node v, closeness is the normalised sum of inverse latencies to all other nodes:

closeness(v) = (1 / (n-1)) * sum_{u != v} 1 / latency(v, u)

where 1 / inf = 0 (unreachable targets contribute zero). Values range from 0 (no outgoing time-respecting paths) to 1 (all nodes reachable in one snapshot step).

Parameters:
  • graphs (list of igraph.Graph) – Temporal snapshots in chronological order.

  • graph_labels (list of str, optional) – Labels for each snapshot. If None, defaults to “Graph 1”, etc.

  • cross_gaps (bool, optional) – If False (default), paths cannot cross detected temporal gaps; paths within a single continuous segment remain valid.

  • save_path (str, optional) – Directory for saving the closeness bar-chart PDF. If None (default), no file is saved.

  • report_gaps (bool, optional) – If True, print a temporal gap report to the console (default: False).

Returns:

One row per node with columns node and closeness. Sorted descending by closeness.

Return type:

pandas.DataFrame

Examples

>>> import igraph as ig
>>> from temporal_networks import temporal_closeness
>>> g0 = ig.Graph(n=3, edges=[(0, 1)])
>>> g1 = ig.Graph(n=3, edges=[(1, 2)])
>>> cl = temporal_closeness([g0, g1], graph_labels=["t0", "t1"],
...                          report_gaps=False)
>>> float(cl[cl["node"] == 0]["closeness"].iloc[0]) > 0
True
temporal_networks.temporal_efficiency(graphs, graph_labels=None, cross_gaps=False)[source]

Global temporal efficiency of the snapshot sequence.

Defined as the mean of 1 / latency over all ordered source–target pairs with source ≠ target, where 1 / inf = 0. Ranges from 0 (no time-respecting paths) to 1 (every pair reachable in one step).

Parameters:
  • graphs (list of igraph.Graph) – Temporal snapshots in chronological order.

  • graph_labels (list of str, optional) – Labels for each snapshot. If None, defaults to “Graph 1”, etc.

  • cross_gaps (bool, optional) – If False (default), paths cannot cross detected temporal gaps; paths within a single continuous segment remain valid.

Returns:

Global temporal efficiency, or NaN if there are no non-self pairs.

Return type:

float

Examples

>>> import igraph as ig
>>> from temporal_networks import temporal_efficiency
>>> g0 = ig.Graph(n=2, edges=[(0, 1)])
>>> eff = temporal_efficiency([g0], graph_labels=["t0"])
>>> float(eff) > 0
True
temporal_networks.temporal_betweenness(graphs, graph_labels=None, cross_gaps=False, normalized=True, save_path=None, report_gaps=False)[source]

Per-node temporal betweenness over time-respecting paths.

For every ordered source–target pair, the fraction of foremost (earliest-arrival) time-respecting paths passing through each intermediate node is accumulated, using a temporal adaptation of Brandes’ algorithm. A high value means a node frequently lies on the quickest time-respecting routes between other nodes — a temporal bottleneck or broker.

Gap-aware (default): with cross_gaps=False, foremost paths cannot cross a detected temporal gap, so a data closure never inflates a node’s brokerage. Brokerage on paths confined to a single continuous segment still counts (each source–target pair is counted once, at its earliest arrival over all segments). Pass cross_gaps=True to treat the sequence as contiguous.

Parameters:
  • graphs (list of igraph.Graph) – Temporal snapshots in chronological order.

  • graph_labels (list of str, optional) – Labels for each snapshot. If None, defaults to “Graph 1”, etc.

  • cross_gaps (bool, optional) – If False (default), paths cannot cross detected temporal gaps; paths within a single continuous segment remain valid.

  • normalized (bool, optional) – If True (default), divide by (n - 1) * (n - 2) (the number of ordered pairs not involving the node), giving values in [0, 1]. If False, report raw pair-dependency sums.

  • save_path (str, optional) – Directory for saving the betweenness bar-chart PDF. If None (default), no file is saved.

  • report_gaps (bool, optional) – If True, print a temporal gap report to the console (default: False).

Returns:

One row per node with columns node and betweenness, sorted descending by betweenness. Returns an empty DataFrame with the correct columns on empty input.

Return type:

pandas.DataFrame

Notes

Temporal paths are inherently directed by time, so each ordered (source, target) pair is counted once (no factor-of-two halving as in undirected static betweenness). “Foremost” paths are those achieving the earliest arrival, consistent with the latency used by temporal_distances() and temporal_closeness().

Examples

>>> import igraph as ig
>>> from temporal_networks import temporal_betweenness
>>> g0 = ig.Graph(n=3, edges=[(0, 1)])
>>> g1 = ig.Graph(n=3, edges=[(1, 2)])
>>> bt = temporal_betweenness([g0, g1], graph_labels=["t0", "t1"],
...                            report_gaps=False)
>>> # Node 1 brokers the 0 -> 2 path; others broker nothing
>>> float(bt[bt["node"] == 1]["betweenness"].iloc[0])
0.5
>>> float(bt[bt["node"] == 0]["betweenness"].iloc[0])
0.0

Change-point & anomaly detection

temporal_networks.detect_change_points(series_df, columns=None, method='zscore', threshold=3.0, label_col='Graph', gap_info=None)[source]

Detect change points in one or more metric time series.

Analyses the output DataFrame of any temporal-network analysis function (e.g. network_properties(), snapshot_similarity()) and flags snapshots where a metric shifts unusually.

Gap-aware: when gap_info is supplied, rolling statistics and first differences are computed independently within each continuous segment so a data closure is never mistaken for an anomaly.

Parameters:
  • series_df (pandas.DataFrame) – Input data, typically the output of an analysis function. Must contain a label column (see label_col) and at least one numeric column.

  • columns (list of str, optional) – Numeric columns to analyse. If None (default), all numeric columns except label_col are used.

  • method (str, optional) –

    Detection method:

    • "zscore" (default): flag points whose per-segment z-score exceeds threshold.

    • "diff": flag points where the first difference is a MAD outlier exceeding threshold normalised MAD units.

    • "pelt": PELT change-point detection via the ruptures package (must be installed separately; raises ImportError with an install hint otherwise).

  • threshold (float, optional) –

    Detection threshold. For "zscore" and "diff", the standard 3-sigma rule (threshold=3.0) is a common starting point. For "pelt", this is the penalty value forwarded to ruptures.Pelt.predict.

    Note that the z-score uses the population standard deviation, so the largest absolute z-score any point in an n-point segment can attain is sqrt(n - 1): threshold=3.0 can only ever flag points in segments of 11 or more snapshots (threshold=2.0 needs 6). A warning is emitted when a segment is too short for the chosen threshold; lower the threshold or use "diff" for short segments.

  • label_col (str, optional) – Column in series_df that contains the snapshot label (default "Graph"). Used to populate the label column in the output.

  • gap_info (dict, optional) – Gap information from detect_temporal_gaps(). When provided, statistics are reset at each gap boundary. Gap boundaries are matched to rows through label_col, so frames that do not have one row per label (e.g. snapshot_similarity() output, which has one row per consecutive pair) are still split at the correct rows.

Returns:

One row per detected change point with columns:

  • column: name of the metric where the change was detected

  • index: row index in series_df

  • label: value from label_col at that row

  • score: detection score (z-score, normalised MAD multiple, or NaN for PELT)

  • method: the detection method used

Returns an empty DataFrame with the correct columns when no change points are found.

Return type:

pandas.DataFrame

Warns:

UserWarning – With method="zscore", when a segment is too short for any point to reach threshold (see the threshold parameter).

Examples

>>> import pandas as pd
>>> from temporal_networks import detect_change_points
>>> values = [1.0] * 5 + [20.0] + [1.0] * 5
>>> df = pd.DataFrame({"Graph": [str(i) for i in range(11)],
...                    "metric": values})
>>> cp = detect_change_points(df, threshold=2.0)
>>> len(cp) > 0
True
>>> cp.loc[0, "column"]
'metric'
temporal_networks.flag_anomalous_snapshots(graphs, graph_labels=None, method='zscore', threshold=3.0)[source]

Detect structurally anomalous snapshots from a graph sequence.

Convenience wrapper: computes network_properties() internally and passes the result to detect_change_points(). Gap information is inferred from the labels and used so that metric jumps at gap boundaries are not falsely flagged.

Parameters:
  • graphs (list of igraph.Graph) – Temporal snapshots in chronological order.

  • graph_labels (list of str, optional) – Labels for each snapshot. If None, defaults to “Graph 1”, etc.

  • method (str, optional) – Detection method passed through to detect_change_points() ("zscore" by default).

  • threshold (float, optional) – Detection threshold passed through to detect_change_points().

Returns:

Same schema as detect_change_points(): one row per detected anomalous snapshot per metric.

Return type:

pandas.DataFrame

Examples

>>> import igraph as ig
>>> from temporal_networks import flag_anomalous_snapshots
>>> g_normal = ig.Graph.Full(n=5)
>>> g_sparse = ig.Graph(n=5, edges=[(0, 1)])
>>> graphs = [g_normal] * 8 + [g_sparse] + [g_normal] * 8
>>> labels = [f"{2024 + i // 12}-{i % 12 + 1:02d}" for i in range(17)]
>>> flags = flag_anomalous_snapshots(graphs, graph_labels=labels,
...                                   threshold=2.0)
>>> len(flags) > 0
True

Community tracking

temporal_networks.track_communities(graphs, graph_labels=None, algorithm='multilevel', match_threshold=0.3, bridge_gaps=False, report_gaps=False)[source]

Match communities across snapshots and label lifecycle events.

Communities are detected per snapshot, then matched between consecutive snapshots by Jaccard overlap of their member node-keys. Each community receives a persistent lineage_id and a lifecycle event.

Gap-aware (default): with bridge_gaps=False, communities are not matched across a detected temporal gap, so a community appearing after a closure starts a fresh lineage. Pass bridge_gaps=True to link across gaps.

Parameters:
  • graphs (list of igraph.Graph) – Temporal snapshots in chronological order.

  • graph_labels (list of str, optional) – Labels for each snapshot. If None, defaults to “Graph 1”, etc.

  • algorithm (str, optional) – Community detection algorithm (default "multilevel"). One of edge_betweenness, walktrap, fast_greedy, label_prop, spinglass, leiden, louvain / multilevel, infomap.

  • match_threshold (float, optional) – Minimum Jaccard overlap for two communities in consecutive snapshots to be considered the same lineage (default 0.3).

  • bridge_gaps (bool, optional) – If False (default), lineages are not linked across a detected gap.

  • report_gaps (bool, optional) – If True, print a temporal gap report to the console (default: False).

Returns:

One row per (snapshot, community), with columns:

  • Graph: snapshot label

  • community_id: local id within the snapshot

  • lineage_id: persistent id across snapshots

  • size: member count

  • event: birth / death / continue / merge / split

  • members: sorted list of member node-keys

Returns an empty DataFrame with these columns on empty input.

Return type:

pandas.DataFrame

Notes

Events are classified by match multiplicity, in priority order: a community with two or more predecessors is a merge; one whose single predecessor also produced other communities is a split; one with no predecessor is a birth; one with no successor is a death; otherwise it is a continue. The taxonomy is intentionally minimal — size-based grow / shrink are left to the size column.

Examples

>>> import igraph as ig
>>> from temporal_networks import track_communities
>>> # Two clear clusters that persist across two snapshots
>>> edges = [(0, 1), (1, 2), (0, 2), (3, 4), (4, 5), (3, 5)]
>>> g = ig.Graph(n=6, edges=edges)
>>> df = track_communities([g, g.copy()], graph_labels=["t0", "t1"],
...                         algorithm="louvain", report_gaps=False)
>>> sorted(df["event"].unique())
['birth', 'continue']
temporal_networks.plot_community_lineage(tracking_df, graph_labels, gap_info, save_path=None)[source]

Timeline view of community lineages over the snapshot sequence.

Each community is plotted at (snapshot, lineage_id), sized by member count and coloured by lifecycle event. Communities sharing a lineage are connected across consecutive snapshots; connections are not drawn across a detected temporal gap.

Parameters:
  • tracking_df (pandas.DataFrame) – Output of track_communities().

  • graph_labels (list of str) – Temporal labels for all snapshots (defines the x-axis order).

  • gap_info (dict) – Gap information from detect_temporal_gaps(); connections are suppressed across each gap boundary.

  • save_path (str, optional) – Directory for saving the PDF. If None (default), no file is written.

Return type:

None

Temporal gaps

temporal_networks.detect_temporal_gaps(graph_labels, gap_threshold=None, unit=None, verbose=False)[source]

Detect temporal gaps in a list of labels with detailed reporting.

A gap occurs when consecutive labels are more than gap_threshold apart (in specified units). This is useful for identifying seasonal closures, maintenance windows, data collection gaps, etc.

Parameters:
  • graph_labels (list of str) – Temporal labels (e.g., [“2024-03”, “2024-04”, “2024-11”])

  • gap_threshold (int, optional) – A gap is flagged when consecutive labels are more than gap_threshold unit apart. If None (default), it is inferred from the label format (1 for monthly/daily/weekly/yearly, 3 for quarterly) so that a regularly spaced series reports no gaps. Pass an explicit value to override.

  • unit (str, optional) – Time unit for the gap calculation: “days”, “weeks”, “months”, or “years”. If None (default), inferred from the label format (e.g. “months” for YYYY-MM, “days” for YYYY-MM-DD, “years” for YYYY, “weeks” for YYYY-W##). Pass an explicit value to override.

  • verbose (bool, optional) – If True, print detailed gap report (default: False)

Returns:

Dictionary with keys:

  • ”has_gaps” (bool): Whether gaps were detected

  • ”num_gaps” (int): Number of gaps found

  • ”gaps” (list): List of gap information dicts with:

    • ”start_idx” (int): Index of last point before gap

    • ”end_idx” (int): Index of first point after gap

    • ”start_label” (str): Label before gap

    • ”end_label” (str): Label after gap

    • ”gap_size” (float): Size of gap in specified units

  • ”segments” (list): List of (start_idx, end_idx) tuples for continuous segments

  • ”report” (str): Human-readable gap report

Return type:

dict

Warns:

UserWarning – If any label cannot be parsed as a date, gap detection is disabled (the result reports no gaps and a single continuous segment) and a UserWarning is emitted naming the offending labels. No warning is emitted for the auto-generated placeholder labels ("Graph 1", "Graph 2", …) used when no labels are given.

Examples

>>> labels = ["2024-03", "2024-04", "2024-05", "2024-11", "2024-12"]
>>> result = detect_temporal_gaps(labels, verbose=False)
>>> result["has_gaps"]
True
>>> result["num_gaps"]
1
>>> result["gaps"][0]["gap_size"]
6.0