markovq 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
markovq/__init__.py ADDED
@@ -0,0 +1,92 @@
1
+ """Public classical and spectral foundations of MarkovQ."""
2
+
3
+ from .chains import MarkovChain, classify_states, validate_transition_matrix
4
+ from .classification import (
5
+ accessible,
6
+ closed_classes,
7
+ communicates,
8
+ communicating_classes,
9
+ is_irreducible,
10
+ state_period,
11
+ )
12
+ from .continuous import ContinuousChain, birth_death
13
+ from .jumps import compound_poisson
14
+ from .mixing import (
15
+ detailed_balance,
16
+ distances,
17
+ iterate,
18
+ mixing_time,
19
+ reversible_bound,
20
+ stationary_distributions,
21
+ )
22
+ from .passage import (
23
+ absorption,
24
+ hitting,
25
+ passage_distribution,
26
+ recurrence,
27
+ return_generators,
28
+ )
29
+ from .processes import LevyProcess
30
+ from .spectral import (
31
+ graph_operators,
32
+ hamiltonian,
33
+ hermitian_dilation,
34
+ spectral_diagnostics,
35
+ spectrum,
36
+ )
37
+ from .walks import (
38
+ empirical_passage,
39
+ eventual_line_return,
40
+ graph_walk,
41
+ grid_walk,
42
+ increment_walk,
43
+ lattice_paths,
44
+ lattice_recurrence,
45
+ line_return,
46
+ line_walk,
47
+ occupation_times,
48
+ path_statistics,
49
+ )
50
+
51
+ __all__ = [
52
+ "ContinuousChain",
53
+ "LevyProcess",
54
+ "MarkovChain",
55
+ "absorption",
56
+ "state_period",
57
+ "is_irreducible",
58
+ "communicating_classes",
59
+ "communicates",
60
+ "closed_classes",
61
+ "accessible",
62
+ "birth_death",
63
+ "classify_states",
64
+ "compound_poisson",
65
+ "detailed_balance",
66
+ "distances",
67
+ "empirical_passage",
68
+ "eventual_line_return",
69
+ "graph_operators",
70
+ "graph_walk",
71
+ "grid_walk",
72
+ "hamiltonian",
73
+ "hermitian_dilation",
74
+ "hitting",
75
+ "increment_walk",
76
+ "iterate",
77
+ "lattice_paths",
78
+ "lattice_recurrence",
79
+ "line_return",
80
+ "line_walk",
81
+ "mixing_time",
82
+ "occupation_times",
83
+ "passage_distribution",
84
+ "path_statistics",
85
+ "recurrence",
86
+ "return_generators",
87
+ "reversible_bound",
88
+ "spectral_diagnostics",
89
+ "spectrum",
90
+ "stationary_distributions",
91
+ "validate_transition_matrix",
92
+ ]
markovq/_types.py ADDED
@@ -0,0 +1,11 @@
1
+ """Array input and reproducible sampling types shared by the numerical APIs."""
2
+
3
+ from typing import Union
4
+
5
+ import numpy as np
6
+ from numpy.typing import ArrayLike
7
+ from scipy.sparse import spmatrix
8
+
9
+ MatrixInput = Union[ArrayLike, spmatrix]
10
+ Matrix = Union[np.ndarray, spmatrix]
11
+ Seed = Union[int, np.random.Generator, None]
markovq/batch.py ADDED
@@ -0,0 +1,189 @@
1
+ """Independent endpoint trajectories with worker-invariant random streams."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import struct
7
+ from concurrent.futures import ProcessPoolExecutor
8
+ from dataclasses import dataclass, replace
9
+ from typing import Iterable, NamedTuple
10
+
11
+ import numpy as np
12
+ from scipy import sparse
13
+
14
+ from ._types import MatrixInput
15
+ from .chains import count, distribution, validate_transition_matrix
16
+
17
+
18
+ class BatchResult(NamedTuple):
19
+ counts: np.ndarray
20
+ standard_errors: np.ndarray
21
+ batches: int
22
+ storage_bytes: int
23
+
24
+
25
+ class Partition(NamedTuple):
26
+ fingerprint: str
27
+ partition_id: int
28
+ counts: np.ndarray
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class EndpointPlan:
33
+ transition: sparse.csr_matrix
34
+ initial: np.ndarray
35
+ steps: int
36
+ trajectories: int
37
+ seed: int
38
+ batch_size: int
39
+ fingerprint: str
40
+
41
+ @property
42
+ def batches(self) -> int:
43
+ return (self.trajectories + self.batch_size - 1) // self.batch_size
44
+
45
+
46
+ def endpoint_plan(
47
+ transition: MatrixInput,
48
+ initial,
49
+ steps: int,
50
+ trajectories: int,
51
+ *,
52
+ seed: int,
53
+ batch_size: int = 2048,
54
+ ) -> EndpointPlan:
55
+ p = sparse.csr_matrix(validate_transition_matrix(transition), copy=True)
56
+ p.sum_duplicates()
57
+ p.eliminate_zeros()
58
+ p.sort_indices()
59
+ law = distribution(initial, p.shape[0]).copy()
60
+ n, b = count(trajectories), count(batch_size)
61
+ steps, seed = count(steps), count(seed)
62
+ if not min(n, b):
63
+ raise ValueError("positive trajectory and batch counts required")
64
+ fingerprint = _fingerprint(p, law, steps, n, seed, b)
65
+ for array in (p.data, p.indices, p.indptr, law):
66
+ array.flags.writeable = False
67
+ return EndpointPlan(p, law, steps, n, seed, b, fingerprint)
68
+
69
+
70
+ def _fingerprint(p, law, steps, n, seed, b):
71
+ digest = hashlib.sha256()
72
+ digest.update(str((p.shape, steps, n, seed, b)).encode("ascii"))
73
+ for a, dtype in [
74
+ (p.data, "<f8"),
75
+ (p.indices, "<i8"),
76
+ (p.indptr, "<i8"),
77
+ (law, "<f8"),
78
+ ]:
79
+ digest.update(struct.pack("<Q", len(a)))
80
+ digest.update(a.astype(dtype, copy=False).tobytes())
81
+ return digest.hexdigest()
82
+
83
+
84
+ def _verify(plan):
85
+ p = plan.transition
86
+ if (
87
+ p.format != "csr"
88
+ or p.data.dtype != np.float64
89
+ or plan.initial.dtype != np.float64
90
+ or any(a.dtype.kind != "i" for a in (p.indptr, p.indices))
91
+ or any(a.ndim != 1 for a in (p.data, p.indices, p.indptr, plan.initial))
92
+ or _fingerprint(
93
+ p, plan.initial, plan.steps, plan.trajectories, plan.seed, plan.batch_size
94
+ )
95
+ != plan.fingerprint
96
+ ):
97
+ raise ValueError("inconsistent endpoint plan")
98
+
99
+
100
+ def run_partition(plan: EndpointPlan, index: int) -> Partition:
101
+ # Snapshot both mutable containers before verifying the inputs used below.
102
+ plan = replace(plan, transition=plan.transition.copy(), initial=plan.initial.copy())
103
+ _verify(plan)
104
+ i = count(index)
105
+ if i >= plan.batches:
106
+ raise ValueError("partition outside plan")
107
+ rng = np.random.default_rng(np.random.SeedSequence(plan.seed, spawn_key=(i,)))
108
+ n = min(plan.batch_size, plan.trajectories - i * plan.batch_size)
109
+ counts = rng.multinomial(n, plan.initial)
110
+ p = plan.transition
111
+ for _ in range(plan.steps):
112
+ following = np.zeros_like(counts)
113
+ for vertex in np.flatnonzero(counts):
114
+ start, end = p.indptr[vertex : vertex + 2]
115
+ following[p.indices[start:end]] += rng.multinomial(
116
+ counts[vertex], p.data[start:end]
117
+ )
118
+ counts = following
119
+ return Partition(plan.fingerprint, i, counts)
120
+
121
+
122
+ def merge_partitions(plan: EndpointPlan, parts: Iterable[Partition]) -> BatchResult:
123
+ _verify(plan)
124
+ total = np.zeros(plan.transition.shape[0], np.int64)
125
+ seen = set()
126
+ for part in parts:
127
+ i = count(part.partition_id)
128
+ x = np.asarray(part.counts)
129
+ if part.fingerprint != plan.fingerprint or i >= plan.batches or i in seen:
130
+ raise ValueError("foreign, duplicate or invalid partition")
131
+ n = min(plan.batch_size, plan.trajectories - i * plan.batch_size)
132
+ if (
133
+ x.shape != total.shape
134
+ or x.dtype.kind not in "iu"
135
+ or (x < 0).any()
136
+ or sum(map(int, x)) != n
137
+ ):
138
+ raise ValueError("invalid partition counts")
139
+ seen.add(i)
140
+ total += x.astype(np.int64)
141
+ _verify(plan)
142
+ if len(seen) != plan.batches:
143
+ raise ValueError("incomplete partitions")
144
+ p = plan.transition
145
+ prob = total / plan.trajectories
146
+ return BatchResult(
147
+ total,
148
+ np.sqrt(prob * (1 - prob) / plan.trajectories),
149
+ plan.batches,
150
+ p.data.nbytes + p.indices.nbytes + p.indptr.nbytes,
151
+ )
152
+
153
+
154
+ def _initialize(plan):
155
+ global _worker_plan
156
+ _worker_plan = plan
157
+
158
+
159
+ _worker_plan: EndpointPlan
160
+
161
+
162
+ def _execute(index):
163
+ return run_partition(_worker_plan, index)
164
+
165
+
166
+ def simulate_endpoints(
167
+ transition: MatrixInput,
168
+ initial,
169
+ steps: int,
170
+ trajectories: int,
171
+ *,
172
+ seed: int,
173
+ batch_size: int = 2048,
174
+ workers: int = 1,
175
+ ) -> BatchResult:
176
+ plan = endpoint_plan(
177
+ transition, initial, steps, trajectories, seed=seed, batch_size=batch_size
178
+ )
179
+ w = count(workers)
180
+ if not w:
181
+ raise ValueError("positive worker count required")
182
+ if w == 1:
183
+ return merge_partitions(
184
+ plan, (run_partition(plan, i) for i in range(plan.batches))
185
+ )
186
+ with ProcessPoolExecutor(
187
+ max_workers=min(w, plan.batches), initializer=_initialize, initargs=(plan,)
188
+ ) as pool:
189
+ return merge_partitions(plan, pool.map(_execute, range(plan.batches)))
markovq/chains.py ADDED
@@ -0,0 +1,168 @@
1
+ """Finite chains use row distributions and chronological right multiplication."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from math import gcd
6
+ from operator import index
7
+ from typing import Iterable, NamedTuple, Optional
8
+
9
+ import numpy as np
10
+ from numpy.typing import ArrayLike
11
+ from scipy import sparse
12
+ from scipy.sparse.csgraph import connected_components
13
+
14
+ from ._types import Matrix, MatrixInput, Seed
15
+
16
+
17
+ def count(n: int) -> int:
18
+ n = index(n)
19
+ if n < 0:
20
+ raise ValueError("expected a nonnegative integer")
21
+ return n
22
+
23
+
24
+ def state(i: int, size: int) -> int:
25
+ i = count(i)
26
+ if i >= size:
27
+ raise ValueError("state outside model")
28
+ return i
29
+
30
+
31
+ def matrix(a: MatrixInput) -> Matrix:
32
+ if np.iscomplexobj(a):
33
+ raise ValueError("expected real entries")
34
+ a = (
35
+ sparse.csr_matrix(a, dtype=float, copy=True)
36
+ if sparse.issparse(a)
37
+ else np.array(a, dtype=float, copy=True)
38
+ )
39
+ if a.ndim != 2 or a.shape[0] != a.shape[1] or not a.shape[0]:
40
+ raise ValueError("expected a nonempty square matrix")
41
+ values = a.data if sparse.issparse(a) else a
42
+ if not np.isfinite(values).all():
43
+ raise ValueError("nonfinite matrix")
44
+ return a
45
+
46
+
47
+ def validate_transition_matrix(a: MatrixInput) -> Matrix:
48
+ a = matrix(a)
49
+ if a.min() < 0 or not np.allclose(a.sum(axis=1), 1, atol=1e-12, rtol=0):
50
+ raise ValueError("invalid transition probabilities")
51
+ return a
52
+
53
+
54
+ def distribution(p: ArrayLike, size: int) -> np.ndarray:
55
+ if np.iscomplexobj(p):
56
+ raise ValueError("complex probabilities")
57
+ p = np.asarray(p, dtype=float)
58
+ if (
59
+ p.shape != (size,)
60
+ or p.min() < 0
61
+ or not np.isclose(p.sum(), 1, rtol=0, atol=1e-12)
62
+ ):
63
+ raise ValueError("invalid distribution")
64
+ return p
65
+
66
+
67
+ class MarkovChain:
68
+ def __init__(
69
+ self,
70
+ transition: MatrixInput,
71
+ *,
72
+ schedule: Optional[Iterable[MatrixInput]] = None,
73
+ ) -> None:
74
+ self.P = validate_transition_matrix(transition)
75
+ self.n = self.P.shape[0]
76
+ self.steps = (
77
+ None
78
+ if schedule is None
79
+ else [self.P] + [validate_transition_matrix(p) for p in schedule]
80
+ )
81
+ if self.steps and any(p.shape != self.P.shape for p in self.steps):
82
+ raise ValueError("inconsistent state spaces")
83
+
84
+ def _interval(self, steps: int, start: int) -> range:
85
+ steps, start = count(steps), count(start)
86
+ if self.steps is not None and start + steps > len(self.steps):
87
+ raise ValueError("schedule exhausted")
88
+ return range(start, start + steps)
89
+
90
+ def n_step_matrix(self, steps: int, start: int = 0) -> Matrix:
91
+ interval = self._interval(steps, start)
92
+ if self.steps is None:
93
+ return (
94
+ self.P**steps
95
+ if sparse.issparse(self.P)
96
+ else np.linalg.matrix_power(self.P, steps)
97
+ )
98
+ out = (
99
+ sparse.eye(self.n, format="csr")
100
+ if sparse.issparse(self.P)
101
+ else np.eye(self.n)
102
+ )
103
+ for t in interval:
104
+ out = out @ self.steps[t]
105
+ return out
106
+
107
+ def transition_probability(
108
+ self, i: int, j: int, steps: int = 1, start: int = 0
109
+ ) -> float:
110
+ return float(
111
+ self.n_step_matrix(steps, start)[state(i, self.n), state(j, self.n)]
112
+ )
113
+
114
+ def evolve(self, initial: ArrayLike, steps: int, start: int = 0) -> np.ndarray:
115
+ return distribution(initial, self.n) @ self.n_step_matrix(steps, start)
116
+
117
+ def sample_paths(
118
+ self,
119
+ initial: ArrayLike,
120
+ steps: int,
121
+ paths: int = 1,
122
+ seed: Seed = None,
123
+ start: int = 0,
124
+ ) -> np.ndarray:
125
+ interval = self._interval(steps, start)
126
+ rng = np.random.default_rng(seed)
127
+ out = np.empty((count(paths), steps + 1), dtype=int)
128
+ out[:, 0] = rng.choice(self.n, len(out), p=distribution(initial, self.n))
129
+ for col, t in enumerate(interval, 1):
130
+ p = self.P if self.steps is None else self.steps[t]
131
+ for i in np.unique(out[:, col - 1]):
132
+ mask = out[:, col - 1] == i
133
+ row = p[i] if isinstance(p, np.ndarray) else p.getrow(i).toarray()[0]
134
+ out[mask, col] = rng.choice(self.n, mask.sum(), p=row)
135
+ return out
136
+
137
+
138
+ def classify_states(transition: MatrixInput) -> list[StateClass]:
139
+ p = sparse.csr_matrix(validate_transition_matrix(transition))
140
+ p.eliminate_zeros()
141
+ k, labels = connected_components(p, directed=True, connection="strong")
142
+ result = []
143
+ for label in range(k):
144
+ group = np.flatnonzero(labels == label)
145
+ closed = all(labels[j] == label for j in p[group].indices)
146
+ depth = {int(group[0]): 0}
147
+ queue = [int(group[0])]
148
+ period = 0
149
+ for i in queue:
150
+ for j in p.indices[p.indptr[i] : p.indptr[i + 1]]:
151
+ if labels[j] != label:
152
+ continue
153
+ if j not in depth:
154
+ depth[j] = depth[i] + 1
155
+ queue.append(j)
156
+ period = gcd(period, depth[i] + 1 - depth[j])
157
+ result.append(StateClass(tuple(map(int, group)), closed, period))
158
+ return result
159
+
160
+
161
+ class StateClass(NamedTuple):
162
+ states: tuple
163
+ recurrent: bool
164
+ period: int
165
+
166
+ @property
167
+ def absorbing(self) -> bool:
168
+ return self.recurrent and len(self.states) == 1
markovq/circuits.py ADDED
@@ -0,0 +1,162 @@
1
+ """Qiskit walk circuits. Position occupies the least significant qubits."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from time import perf_counter
6
+ from typing import Any, Optional
7
+
8
+ import numpy as np
9
+ from numpy.typing import ArrayLike
10
+
11
+ from .chains import count
12
+ from .quantum.walks import ket, unitary
13
+
14
+
15
+ def cycle_circuit(size: int, steps: int = 1):
16
+ from qiskit import QuantumCircuit
17
+
18
+ size = count(size)
19
+ if size < 2 or size & (size - 1):
20
+ raise ValueError("cycle size must be a power of two >= 2")
21
+ m = size.bit_length() - 1
22
+ circuit = QuantumCircuit(m + 1)
23
+ for _ in range(count(steps)):
24
+ circuit.h(m)
25
+ for increment in (True, False):
26
+ if not increment:
27
+ circuit.x(m)
28
+ circuit.x(range(m))
29
+ for target in reversed(range(m)):
30
+ controls = [m, *range(target)]
31
+ if len(controls) == 1:
32
+ circuit.cx(m, target)
33
+ else:
34
+ circuit.mcx(controls, target)
35
+ if not increment:
36
+ circuit.x(range(m))
37
+ circuit.x(m)
38
+ return circuit
39
+
40
+
41
+ def graph_circuit(operator: ArrayLike):
42
+ """Exact small-graph embedding; unused computational states evolve by identity."""
43
+ from qiskit import QuantumCircuit
44
+
45
+ u = unitary(operator)
46
+ m = max(1, (len(u) - 1).bit_length())
47
+ if m > 8:
48
+ raise ValueError("dense synthesis supports at most eight logical qubits")
49
+ full = np.eye(2**m, dtype=complex)
50
+ full[: len(u), : len(u)] = u
51
+ circuit = QuantumCircuit(m)
52
+ circuit.unitary(full, range(m))
53
+ return circuit
54
+
55
+
56
+ def circuit_resources(original, compiled, backend=None) -> dict:
57
+ """Use initial placement to distinguish input-data wires from workspace."""
58
+ operations = [
59
+ op for op in compiled.data if not getattr(op.operation, "_directive", False)
60
+ ]
61
+ used = {compiled.find_bit(q).index for op in operations for q in op.qubits}
62
+ data = [i for i, q in enumerate(original.qubits) if q not in original.ancillas]
63
+ mapping = None
64
+ if compiled.layout is not None:
65
+ mapping = compiled.layout.initial_index_layout(filter_ancillas=True)
66
+ elif compiled.qubits == original.qubits:
67
+ mapping = list(range(original.num_qubits))
68
+ placed = (
69
+ None
70
+ if mapping is None or len(mapping) != original.num_qubits
71
+ else {mapping[i] for i in data}
72
+ )
73
+ return {
74
+ "logical_qubits": len(data),
75
+ "represented_logical_qubits": None if placed is None else len(placed),
76
+ "physical_qubits_addressed": len(used),
77
+ "addressed_wire_indices": sorted(used),
78
+ "ancillary_qubits": None if placed is None else len(used - placed),
79
+ "compiled_width": compiled.num_qubits,
80
+ "backend_capacity": getattr(backend, "num_qubits", None),
81
+ "measurement_count": sum(op.operation.name == "measure" for op in operations),
82
+ "depth": compiled.depth(),
83
+ "two_qubit_gates": sum(len(op.qubits) == 2 for op in operations),
84
+ }
85
+
86
+
87
+ def simulate(
88
+ circuit,
89
+ initial: ArrayLike,
90
+ *,
91
+ seed: int,
92
+ shots: int = 0,
93
+ backend: Optional[object] = None,
94
+ ) -> dict:
95
+ """Ideal local statevector and independent multinomial shots; optional target compilation."""
96
+ from qiskit import QuantumCircuit, transpile
97
+ from qiskit.quantum_info import Statevector
98
+
99
+ started = perf_counter()
100
+ n = circuit.num_qubits
101
+ v = ket(initial, 2**n)
102
+ prepared = QuantumCircuit(list(circuit.qubits))
103
+ prepared.prepare_state(v, range(n))
104
+ prepared.compose(circuit, inplace=True)
105
+ probabilities = Statevector.from_instruction(prepared).probabilities()
106
+ measured = prepared.measure_all(inplace=False)
107
+ kwargs: dict[str, Any] = (
108
+ {"basis_gates": ["rz", "sx", "x", "cx"]}
109
+ if backend is None
110
+ else {"backend": backend}
111
+ )
112
+ compiled = transpile(
113
+ measured, seed_transpiler=count(seed), optimization_level=1, **kwargs
114
+ )
115
+ counts = np.random.default_rng(seed).multinomial(count(shots), probabilities)
116
+ return {
117
+ "probabilities": probabilities,
118
+ "counts": counts,
119
+ **circuit_resources(circuit, compiled, backend),
120
+ "requested_shots": shots,
121
+ "returned_shots": int(counts.sum()),
122
+ "shots": shots,
123
+ "provider_jobs": 0,
124
+ "runtime_s": perf_counter() - started,
125
+ "evidence": "ideal circuit simulation",
126
+ }
127
+
128
+
129
+ def execute_backend(circuit, initial: ArrayLike, backend, *, shots: int, seed: int):
130
+ """Submit a measured circuit to a caller-selected backend supporting Backend.run.
131
+
132
+ The seed controls compilation. Backend sampling and queue policies belong to the
133
+ caller's provider. Runtime includes compilation and waiting for the result.
134
+ """
135
+ from qiskit import QuantumCircuit, transpile
136
+
137
+ shots = count(shots)
138
+ if not shots:
139
+ raise ValueError("backend execution requires positive shots")
140
+ started = perf_counter()
141
+ n = circuit.num_qubits
142
+ prepared = QuantumCircuit(list(circuit.qubits))
143
+ prepared.prepare_state(ket(initial, 2**n), range(n))
144
+ prepared.compose(circuit, inplace=True)
145
+ prepared.measure_all()
146
+ compiled = transpile(prepared, backend, seed_transpiler=count(seed))
147
+ job = backend.run(compiled, shots=shots)
148
+ counts = job.result().get_counts()
149
+ if sum(counts.values()) != shots:
150
+ raise ValueError("backend returned an inconsistent shot count")
151
+ return {
152
+ "backend": backend.name,
153
+ "job_id": job.job_id(),
154
+ "counts": dict(counts),
155
+ "shots": shots,
156
+ "provider_jobs": 1,
157
+ **circuit_resources(circuit, compiled, backend),
158
+ "requested_shots": shots,
159
+ "returned_shots": sum(counts.values()),
160
+ "evidence": "caller-selected backend execution",
161
+ "runtime_s": perf_counter() - started,
162
+ }
@@ -0,0 +1,43 @@
1
+ """Finite-chain communication and reachability queries."""
2
+
3
+ from scipy.sparse import csr_matrix
4
+ from scipy.sparse.csgraph import breadth_first_order
5
+
6
+ from ._types import MatrixInput
7
+ from .chains import classify_states, state, validate_transition_matrix
8
+
9
+
10
+ def accessible(transition: MatrixInput, source: int, target: int) -> bool:
11
+ """Whether a positive-probability path exists, allowing a zero-length path."""
12
+ graph = csr_matrix(validate_transition_matrix(transition))
13
+ graph.eliminate_zeros()
14
+ start = state(source, graph.shape[0])
15
+ end = state(target, graph.shape[0])
16
+ reachable = breadth_first_order(
17
+ graph, start, directed=True, return_predecessors=False
18
+ )
19
+ return bool(end in reachable)
20
+
21
+
22
+ def communicates(transition: MatrixInput, source: int, target: int) -> bool:
23
+ return accessible(transition, source, target) and accessible(
24
+ transition, target, source
25
+ )
26
+
27
+
28
+ def communicating_classes(transition: MatrixInput) -> list[tuple[int, ...]]:
29
+ return [c.states for c in classify_states(transition)]
30
+
31
+
32
+ def closed_classes(transition: MatrixInput) -> list[tuple[int, ...]]:
33
+ return [c.states for c in classify_states(transition) if c.recurrent]
34
+
35
+
36
+ def state_period(transition: MatrixInput, source: int) -> int:
37
+ p = validate_transition_matrix(transition)
38
+ i = state(source, p.shape[0])
39
+ return next(c.period for c in classify_states(p) if i in c.states)
40
+
41
+
42
+ def is_irreducible(transition: MatrixInput) -> bool:
43
+ return len(classify_states(transition)) == 1