Import and export: pandas, SPMF, networkx, Gephi, Cytoscape#

Event logs usually arrive as long tables (case, activity, timestamp). They become a SequenceDatabase; results go to pandas tables, SPMF files, JSON, and every graph to networkx and on to GraphML, GEXF (Gephi, with positions and colors), Cytoscape JSON or igraph — node attributes included.

import tempfile
from pathlib import Path

import pandas as pd

import spmviz as sv

tmp = Path(tempfile.mkdtemp())

From an event table#

log = pd.DataFrame({
    "case":     [1, 1, 1, 2, 2, 3, 3, 3],
    "activity": ["login", "search", "buy", "login", "search", "login", "search", "buy"],
    "time":     pd.to_datetime(["2026-01-01 10:00", "2026-01-01 10:02", "2026-01-01 10:09",
                                "2026-01-02 09:00", "2026-01-02 09:01",
                                "2026-01-03 18:00", "2026-01-03 18:05", "2026-01-03 18:06"]),
})
db = sv.SequenceDatabase.from_event_log(log, case="case", activity="activity", timestamp="time")
ps = sv.mine(db, min_support=2)
print(ps.to_frame()[["pattern", "support", "confidence"]])
                pattern  support  confidence
0                   buy        2    1.000000
1                 login        3    1.000000
2                search        3    1.000000
3           login → buy        2    0.666667
4        login → search        3    1.000000
5          search → buy        2    0.666667
6  login → search → buy        2    0.666667

Files#

sv.io.write_spmf(db, tmp / "db.txt")                 # SPMF input format (text items coded)
ps.write(tmp / "patterns.txt")                       # SPMF output: #SUP and #SID
ps.write(tmp / "patterns.json")
back = sv.io.read_patterns(tmp / "patterns.json", db)
print((tmp / "patterns.txt").read_text())
@CONVERTED_FROM_TEXT
@ITEM=1=buy
@ITEM=2=login
@ITEM=3=search
1 -1 #SUP: 2 #SID: 0 2
2 -1 #SUP: 3 #SID: 0 1 2
3 -1 #SUP: 3 #SID: 0 1 2
2 -1 1 -1 #SUP: 2 #SID: 0 2
2 -1 3 -1 #SUP: 3 #SID: 0 1 2
3 -1 1 -1 #SUP: 2 #SID: 0 2
2 -1 3 -1 1 -1 #SUP: 2 #SID: 0 2

Graphs#

G = ps.to_networkx("extension")                      # a networkx.DiGraph
print(G.nodes["login → search"])
wn = sv.NBVFS("wn").fit(ps)
for ext in ("gexf", "graphml", "cyjs", "json"):
    wn.write(tmp / f"network.{ext}")                 # with x, y, support, confidence, ...
H = sv.io.read_graph(tmp / "network.graphml")
print(sorted(H.nodes(data=True))[0])
{'label': 'login → search', 'support': 3, 'rel_support': 1.0, 'length': 2, 'confidence': 1.0, 'cum_confidence': 1.0, 'start': 'login', 'added': 'search', 'index': 4}
('buy', {'label': 'buy', 'support': 2, 'rel_support': 0.6666666666666666, 'length': 1, 'confidence': 1.0, 'cum_confidence': 1.0, 'start': 'buy', 'added': 'buy', 'index': 0, 'x': -0.7071067811865475, 'y': -0.7071067811865476})

Total running time of the script: (0 minutes 0.014 seconds)

Gallery generated by Sphinx-Gallery