spmviz 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.
- spmviz/__init__.py +80 -0
- spmviz/backends.py +168 -0
- spmviz/data.py +835 -0
- spmviz/datasets/__init__.py +54 -0
- spmviz/datasets/_bundled.py +174 -0
- spmviz/datasets/data/README.md +10 -0
- spmviz/datasets/data/alarm_log.csv.gz +0 -0
- spmviz/datasets/data/chess_openings.json +200 -0
- spmviz/datasets/data/clickstream.csv.gz +0 -0
- spmviz/datasets/data/melodies.json +139 -0
- spmviz/datasets/fetch.py +130 -0
- spmviz/datasets/generators.py +219 -0
- spmviz/embedding.py +246 -0
- spmviz/interactive.py +221 -0
- spmviz/io.py +453 -0
- spmviz/layout.py +197 -0
- spmviz/measures.py +366 -0
- spmviz/mining/__init__.py +27 -0
- spmviz/mining/_common.py +62 -0
- spmviz/mining/api.py +128 -0
- spmviz/mining/episodes.py +268 -0
- spmviz/mining/gsp.py +116 -0
- spmviz/mining/postprocess.py +76 -0
- spmviz/mining/prefixspan.py +231 -0
- spmviz/mining/rules.py +74 -0
- spmviz/mining/spade.py +109 -0
- spmviz/mining/spam.py +252 -0
- spmviz/nbvfs.py +204 -0
- spmviz/networks.py +513 -0
- spmviz/patterns.py +428 -0
- spmviz/predict.py +85 -0
- spmviz/summary.py +204 -0
- spmviz/viz/__init__.py +93 -0
- spmviz/viz/_style.py +154 -0
- spmviz/viz/dashboard.py +37 -0
- spmviz/viz/flows.py +415 -0
- spmviz/viz/matrices.py +191 -0
- spmviz/viz/nbvfs.py +198 -0
- spmviz/viz/patterns.py +100 -0
- spmviz/viz/projections.py +202 -0
- spmviz/viz/sequences.py +435 -0
- spmviz/viz/sets.py +139 -0
- spmviz/viz/trees.py +442 -0
- spmviz-1.0.dist-info/METADATA +189 -0
- spmviz-1.0.dist-info/RECORD +47 -0
- spmviz-1.0.dist-info/WHEEL +4 -0
- spmviz-1.0.dist-info/licenses/LICENSE +21 -0
spmviz/__init__.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""spmviz: mining and visualization of frequent sequential patterns.
|
|
2
|
+
|
|
3
|
+
The package mines frequent sequences with built-in algorithms (PrefixSpan,
|
|
4
|
+
CM-SPAM, SPAM, SPADE, GSP, top-k, episodes) or external back ends, and offers
|
|
5
|
+
more than thirty visualizations of the results: the network-based methods of
|
|
6
|
+
Bántay & Abonyi (2024) — the weighted extension network and the confidence- and
|
|
7
|
+
transaction-based MDS maps — together with prefix trees, sunbursts, icicles,
|
|
8
|
+
double trees, Sankey and transition diagrams, matrix views, pattern lattices,
|
|
9
|
+
sequence index plots, sequence logos, MDL summaries and new methods such as
|
|
10
|
+
continuation-entropy trees, pattern-induced higher-order networks, pattern
|
|
11
|
+
communities and pattern landscapes. Every result exports to networkx, pandas,
|
|
12
|
+
GraphML, GEXF, Cytoscape, JSON and SPMF.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from . import backends, datasets, embedding, io, layout, measures, networks, predict, summary
|
|
16
|
+
from .data import (
|
|
17
|
+
Constraints,
|
|
18
|
+
SequenceDatabase,
|
|
19
|
+
as_pattern,
|
|
20
|
+
contains,
|
|
21
|
+
find_occurrence,
|
|
22
|
+
format_pattern,
|
|
23
|
+
is_subpattern,
|
|
24
|
+
parent_pattern,
|
|
25
|
+
pattern_length,
|
|
26
|
+
)
|
|
27
|
+
from .mining import (
|
|
28
|
+
EpisodeSet,
|
|
29
|
+
cmspam,
|
|
30
|
+
gsp,
|
|
31
|
+
mine,
|
|
32
|
+
mine_episodes,
|
|
33
|
+
prefixspan,
|
|
34
|
+
sequential_rules,
|
|
35
|
+
spade,
|
|
36
|
+
spam,
|
|
37
|
+
topk,
|
|
38
|
+
)
|
|
39
|
+
from .nbvfs import NBVFS
|
|
40
|
+
from .patterns import PatternSet
|
|
41
|
+
from .predict import predict_next
|
|
42
|
+
from .summary import mdl_summary
|
|
43
|
+
|
|
44
|
+
__version__ = "1.0"
|
|
45
|
+
|
|
46
|
+
__all__ = [
|
|
47
|
+
"NBVFS",
|
|
48
|
+
"Constraints",
|
|
49
|
+
"EpisodeSet",
|
|
50
|
+
"PatternSet",
|
|
51
|
+
"SequenceDatabase",
|
|
52
|
+
"__version__",
|
|
53
|
+
"as_pattern",
|
|
54
|
+
"backends",
|
|
55
|
+
"cmspam",
|
|
56
|
+
"contains",
|
|
57
|
+
"datasets",
|
|
58
|
+
"embedding",
|
|
59
|
+
"find_occurrence",
|
|
60
|
+
"format_pattern",
|
|
61
|
+
"gsp",
|
|
62
|
+
"io",
|
|
63
|
+
"is_subpattern",
|
|
64
|
+
"layout",
|
|
65
|
+
"mdl_summary",
|
|
66
|
+
"measures",
|
|
67
|
+
"mine",
|
|
68
|
+
"mine_episodes",
|
|
69
|
+
"networks",
|
|
70
|
+
"parent_pattern",
|
|
71
|
+
"pattern_length",
|
|
72
|
+
"predict",
|
|
73
|
+
"predict_next",
|
|
74
|
+
"prefixspan",
|
|
75
|
+
"sequential_rules",
|
|
76
|
+
"spade",
|
|
77
|
+
"spam",
|
|
78
|
+
"summary",
|
|
79
|
+
"topk",
|
|
80
|
+
]
|
spmviz/backends.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Adapters to external sequential pattern miners.
|
|
2
|
+
|
|
3
|
+
Every adapter returns a :class:`~spmviz.PatternSet`, so the visualizations of the
|
|
4
|
+
package work on the results of any miner. Supporting sequence ids are taken from
|
|
5
|
+
the back end when it reports them (SPMF) and computed otherwise.
|
|
6
|
+
|
|
7
|
+
================= ==============================================================
|
|
8
|
+
algorithm package
|
|
9
|
+
================= ==============================================================
|
|
10
|
+
``prefixspan-py`` ``prefixspan`` (PyPI; PrefixSpan, BIDE closed, FEAT generators, top-k)
|
|
11
|
+
``seq2pat`` ``seq2pat`` (Fidelity, AAAI 2022; constraint-based)
|
|
12
|
+
``gsppy`` ``gsppy`` (GSP with an optional Rust back end; version 5.3 returned the
|
|
13
|
+
same supports as the built-in miners but missed some patterns that
|
|
14
|
+
repeat an item, e.g. ⟨product product⟩)
|
|
15
|
+
``spmf`` the SPMF Java library (``spmf.jar``; more than 200 algorithms)
|
|
16
|
+
================= ==============================================================
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import os
|
|
22
|
+
import pathlib
|
|
23
|
+
import shutil
|
|
24
|
+
import subprocess
|
|
25
|
+
import tempfile
|
|
26
|
+
|
|
27
|
+
import numpy as np
|
|
28
|
+
|
|
29
|
+
from .data import Constraints, SequenceDatabase
|
|
30
|
+
from .mining._common import resolve_min_support
|
|
31
|
+
from .patterns import PatternSet
|
|
32
|
+
|
|
33
|
+
__all__ = ["available", "run", "spmf_command"]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def available() -> dict:
|
|
37
|
+
"""Which external back ends can be used in this environment."""
|
|
38
|
+
out = {}
|
|
39
|
+
for name, mod in (("prefixspan-py", "prefixspan"), ("seq2pat", "sequential.seq2pat"), ("gsppy", "gsppy.gsp")):
|
|
40
|
+
try:
|
|
41
|
+
__import__(mod)
|
|
42
|
+
out[name] = True
|
|
43
|
+
except Exception:
|
|
44
|
+
out[name] = False
|
|
45
|
+
out["spmf"] = bool(shutil.which("java")) and bool(os.environ.get("SPMVIZ_SPMF_JAR"))
|
|
46
|
+
return out
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _sids(db: SequenceDatabase, patterns: list, con: Constraints) -> list:
|
|
50
|
+
return [np.flatnonzero(db.contains(p, con)) for p in patterns]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _finish(db, patterns, support, sids, params, min_length, max_length, minsup):
|
|
54
|
+
keep = [k for k, p in enumerate(patterns)
|
|
55
|
+
if min_length <= sum(len(e) for e in p) <= (max_length or 10**9) and support[k] >= minsup]
|
|
56
|
+
order = sorted(keep, key=lambda k: (sum(len(e) for e in patterns[k]), [str(i) for e in patterns[k] for i in e]))
|
|
57
|
+
return PatternSet([patterns[k] for k in order], [support[k] for k in order],
|
|
58
|
+
None if sids is None else [sids[k] for k in order], len(db), db, params)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def run(algorithm: str, db: SequenceDatabase, min_support=0.1, max_length=None, min_length=1, top_k=None,
|
|
62
|
+
min_gap=None, max_gap=None, max_span=None, gap_unit="index", **options) -> PatternSet:
|
|
63
|
+
"""Run an external miner and return a :class:`PatternSet` (called by :func:`spmviz.mine`)."""
|
|
64
|
+
con = Constraints(min_gap, max_gap, max_span, gap_unit)
|
|
65
|
+
n = len(db)
|
|
66
|
+
minsup = resolve_min_support(min_support, n)
|
|
67
|
+
enc = db._encoded()
|
|
68
|
+
items = enc.items
|
|
69
|
+
params = {"algorithm": algorithm, "min_support": min_support, "min_support_abs": minsup,
|
|
70
|
+
"max_length": max_length, "min_length": min_length, "constraints": con.as_dict(), **options}
|
|
71
|
+
if algorithm == "prefixspan-py":
|
|
72
|
+
from prefixspan import PrefixSpan
|
|
73
|
+
|
|
74
|
+
if not db.is_simple or not con.unconstrained:
|
|
75
|
+
raise ValueError("prefixspan-py mines sequences of single items without gap constraints")
|
|
76
|
+
seqs = [[e[0] for e in s] for s in enc.seqs]
|
|
77
|
+
ps_ = PrefixSpan(seqs)
|
|
78
|
+
ps_.minlen = min_length
|
|
79
|
+
ps_.maxlen = max_length or 10**6
|
|
80
|
+
flags = {"closed": options.get("closed", False), "generator": options.get("generator", False)}
|
|
81
|
+
res = ps_.topk(top_k, **flags) if top_k else ps_.frequent(minsup, **flags)
|
|
82
|
+
patterns = [tuple((items[c],) for c in pat) for _, pat in res]
|
|
83
|
+
support = [int(f) for f, _ in res]
|
|
84
|
+
return _finish(db, patterns, support, _sids(db, patterns, con), params, min_length, max_length,
|
|
85
|
+
0 if top_k else minsup)
|
|
86
|
+
if algorithm == "seq2pat":
|
|
87
|
+
from sequential.seq2pat import Seq2Pat
|
|
88
|
+
|
|
89
|
+
if not db.is_simple:
|
|
90
|
+
raise ValueError("seq2pat mines sequences of single items")
|
|
91
|
+
seqs = [[e[0] + 1 for e in s] for s in enc.seqs]
|
|
92
|
+
s2p = Seq2Pat(sequences=seqs, max_span=None)
|
|
93
|
+
res = s2p.get_patterns(min_frequency=minsup)
|
|
94
|
+
patterns = [tuple((items[c - 1],) for c in r[:-1]) for r in res]
|
|
95
|
+
support = [int(r[-1]) for r in res]
|
|
96
|
+
# seq2pat reports patterns of at least two items; add the frequent single items
|
|
97
|
+
counts = db.item_support()
|
|
98
|
+
for it, c in counts.items():
|
|
99
|
+
if c >= minsup and ((it,),) not in patterns:
|
|
100
|
+
patterns.append(((it,),))
|
|
101
|
+
support.append(int(c))
|
|
102
|
+
return _finish(db, patterns, support, _sids(db, patterns, con), params, min_length, max_length, minsup)
|
|
103
|
+
if algorithm == "gsppy":
|
|
104
|
+
from gsppy.gsp import GSP
|
|
105
|
+
|
|
106
|
+
if not db.is_simple:
|
|
107
|
+
raise ValueError("gsppy mines sequences of single items")
|
|
108
|
+
seqs = [[str(e[0]) for e in s] for s in db]
|
|
109
|
+
rev = {str(i): i for i in items}
|
|
110
|
+
levels = GSP(seqs).search(min_support=minsup / n, max_k=None if max_length is None else max_length + 1)
|
|
111
|
+
patterns, support = [], []
|
|
112
|
+
for lev in levels:
|
|
113
|
+
for pat, c in lev.items():
|
|
114
|
+
patterns.append(tuple((rev[x],) for x in pat))
|
|
115
|
+
support.append(int(c))
|
|
116
|
+
return _finish(db, patterns, support, _sids(db, patterns, con), params, min_length, max_length, minsup)
|
|
117
|
+
if algorithm == "spmf":
|
|
118
|
+
return _run_spmf(db, minsup, max_length, min_length, con, params, **options)
|
|
119
|
+
raise ValueError(f"unknown back end {algorithm!r}")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def spmf_command(jar: str, algorithm: str, infile: str, outfile: str, min_support_rel: float,
|
|
123
|
+
max_length: int | None = None, min_length: int = 1, max_gap: int | None = None,
|
|
124
|
+
args: list | None = None) -> list[str]:
|
|
125
|
+
"""The SPMF command line for an algorithm.
|
|
126
|
+
|
|
127
|
+
Parameter orders are those of the SPMF documentation: ``CM-SPAM`` (and
|
|
128
|
+
``SPAM``-like): ``minsup minlen maxlen required_items maxgap show_sids``;
|
|
129
|
+
``PrefixSpan``: ``minsup minlen maxlen show_sids``. Other algorithms need
|
|
130
|
+
explicit ``args`` (everything after the minimum support).
|
|
131
|
+
"""
|
|
132
|
+
ms = f"{100 * min_support_rel:.6g}%"
|
|
133
|
+
if args is not None:
|
|
134
|
+
tail = [str(a) for a in args]
|
|
135
|
+
elif algorithm == "CM-SPAM":
|
|
136
|
+
tail = [str(min_length), str(max_length or 1000), "", str(max_gap or 1000), "true"]
|
|
137
|
+
elif algorithm == "PrefixSpan":
|
|
138
|
+
if max_gap is not None:
|
|
139
|
+
raise ValueError("SPMF PrefixSpan has no gap constraint; use CM-SPAM")
|
|
140
|
+
tail = [str(min_length), str(max_length or 1000), "true"]
|
|
141
|
+
else:
|
|
142
|
+
raise ValueError(f"give the SPMF arguments of {algorithm!r} with spmf_args=[...]")
|
|
143
|
+
return ["java", "-jar", str(jar), "run", algorithm, str(infile), str(outfile), ms, *tail]
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _run_spmf(db, minsup, max_length, min_length, con, params, jar=None, spmf_algorithm="CM-SPAM", spmf_args=None,
|
|
147
|
+
timeout=None, **_):
|
|
148
|
+
from .io import read_patterns, write_spmf
|
|
149
|
+
|
|
150
|
+
jar = jar or os.environ.get("SPMVIZ_SPMF_JAR")
|
|
151
|
+
if not jar or not pathlib.Path(jar).exists():
|
|
152
|
+
raise FileNotFoundError("pass jar='path/to/spmf.jar' or set SPMVIZ_SPMF_JAR (download from the SPMF web site)")
|
|
153
|
+
if not con.unconstrained and con.max_span is not None:
|
|
154
|
+
raise ValueError("span constraints are not mapped to SPMF")
|
|
155
|
+
enc = db._encoded()
|
|
156
|
+
coded = SequenceDatabase([[tuple(c + 1 for c in e) for e in s] for s in enc.seqs])
|
|
157
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
158
|
+
fin, fout = pathlib.Path(tmp) / "in.txt", pathlib.Path(tmp) / "out.txt"
|
|
159
|
+
write_spmf(coded, fin)
|
|
160
|
+
cmd = spmf_command(jar, spmf_algorithm, fin, fout, minsup / len(db), max_length, min_length,
|
|
161
|
+
None if con.max_gap is None else int(con.max_gap), spmf_args)
|
|
162
|
+
subprocess.run(cmd, check=True, capture_output=True, timeout=timeout)
|
|
163
|
+
raw = read_patterns(fout)
|
|
164
|
+
patterns = [tuple(tuple(enc.items[c - 1] for c in e) for e in p) for p in raw.patterns]
|
|
165
|
+
sids = raw._sids if raw.has_sids else None
|
|
166
|
+
params = {**params, "spmf_algorithm": spmf_algorithm}
|
|
167
|
+
return _finish(db, patterns, list(raw.support), sids if sids is not None else _sids(db, patterns, con), params,
|
|
168
|
+
min_length, max_length, minsup)
|