"""GSP: generalized sequential patterns, level-wise with time constraints.
Srikant, R., Agrawal, R. (1996). Mining sequential patterns: generalizations and
performance improvements. EDBT 1996, LNCS 1057, 1–17.
Candidates of length k+1 are joined from frequent k-patterns whose overlap
agrees, pruned by their (contiguous) k-subpatterns and counted by scanning only
the sequences that support both generating patterns.
"""
from __future__ import annotations
from collections import defaultdict
from ..data import Constraints, SequenceDatabase, find_occurrence
from ..patterns import PatternSet
from ._common import build_patternset, make_constraints, resolve_min_support
__all__ = ["gsp"]
def _drop_first(p: tuple) -> tuple:
first = p[0]
return p[1:] if len(first) == 1 else (first[1:],) + p[1:]
def _drop_last(p: tuple) -> tuple:
last = p[-1]
return p[:-1] if len(last) == 1 else p[:-1] + (last[:-1],)
def _deletions(p: tuple, contiguous: bool):
for k, e in enumerate(p):
if contiguous and 0 < k < len(p) - 1 and len(e) == 1:
continue
for j in range(len(e)):
rest = e[:j] + e[j + 1:]
yield p[:k] + ((rest,) if rest else ()) + p[k + 1:]
[docs]
def gsp(
db: SequenceDatabase,
min_support: float | int = 0.1,
max_length: int | None = None,
min_length: int = 1,
min_gap: float | None = None,
max_gap: float | None = None,
max_span: float | None = None,
gap_unit: str = "index",
) -> PatternSet:
"""Mine frequent sequential patterns with GSP (Apriori-style, any constraint).
Examples
--------
>>> import spmviz as sv
>>> db = sv.SequenceDatabase(["abc", "acb", "abd"])
>>> gsp(db, 2).support_of("a b")
3
"""
con: Constraints = make_constraints(min_gap, max_gap, max_span, gap_unit)
if con.gap_unit == "time" and not db.has_times:
raise ValueError("gap_unit='time' needs a database with timestamps")
n = len(db)
minsup = resolve_min_support(min_support, n) if n else 1
maxlen = max_length if max_length is not None else 10**9
enc = db._encoded().seqs
times = db.times if con.gap_unit == "time" else None
contiguous = con.max_gap is not None
sid_of: dict = defaultdict(set)
for sid, s in enumerate(enc):
for it in {i for e in s for i in e}:
sid_of[it].add(sid)
level = {((it,),): frozenset(s) for it, s in sid_of.items() if len(s) >= minsup}
results = [(p, sorted(s)) for p, s in level.items()]
k = 1
while level and k < maxlen:
if k == 1:
items = sorted(p[0][0] for p in level)
cands = {}
for a in items:
for b in items:
cands[((a,), (b,))] = (((a,),), ((b,),))
if a < b:
cands[((a, b),)] = (((a,),), ((b,),))
else:
by_head = defaultdict(list)
for p in level:
by_head[_drop_first(p)].append(p)
cands = {}
for p2 in level:
tail = _drop_last(p2)
last_e = p2[-1]
for p1 in by_head.get(tail, ()):
if len(last_e) == 1:
c = p1 + ((last_e[0],),)
else:
if last_e[-1] <= p1[-1][-1]:
continue
c = p1[:-1] + (p1[-1] + (last_e[-1],),)
if all(q in level for q in _deletions(c, contiguous)):
cands[c] = (p1, p2)
new = {}
for c, (p1, p2) in cands.items():
pool = level[p1] & level[p2]
if len(pool) < minsup:
continue
sup = [sid for sid in pool
if find_occurrence(enc[sid], c, con, None if times is None else times[sid]) is not None]
if len(sup) >= minsup:
new[c] = frozenset(sup)
results.extend((p, sorted(s)) for p, s in new.items())
level = new
k += 1
params = {"algorithm": "gsp", "min_support": min_support, "min_support_abs": minsup,
"max_length": max_length, "min_length": min_length, "constraints": con.as_dict()}
return build_patternset(results, db, params, min_length)