Mining and Visualizing Frequent Sequences in PythonThe spmviz toolbox

Chapter 8
Sequence views and summaries

After the trees, flows and maps of aggregated data, this chapter returns to the sequences themselves. It presents the views of social-science sequence analysis (index plots, chronograms, sequence frequency plots), the dotted chart of process mining, the sequence logo of bioinformatics and the arc diagram of text visualization, each combined with the mined patterns. It then treats two kinds of summaries: episodes, the frequent patterns of one long stream without case boundaries, and pattern sets selected by the minimum description length principle.

8.1 Problem and idea

Every aggregation hides something, and a pattern found by mining is only trustworthy once it has been seen in the data. The views of this chapter keep every case visible, or nearly so, and use the patterns to organize the picture: to sort the cases, to mark the occurrences of a pattern, or to align the cases at an anchor. They come from several traditions. Social-science sequence analysis, with its R package TraMineR, developed index plots, chronograms and frequency plots for life courses and careers [18, 19, 39]. Process mining contributed the dotted chart [40], bioinformatics the sequence logo [41], and text visualization the arc diagram [42]. The second half of the chapter deals with two situations in which the usual pattern set is the wrong summary: a log without case boundaries, where episodes replace sequential patterns [38], and a pattern set too large to read, where a summary by the minimum description length principle replaces it [68, 69].

8.2 Theory

8.2.1 Index plots, chronograms and frequency plots

A sequence index plot draws sequence i as row i of colored cells, one cell per element [19]. What it shows depends on the order of the rows: sorting by length shows the distribution of lengths, sorting by the first events shows the beginnings, and sorting by a pattern puts the supporting sequences first. spmviz adds the patterns to the picture: the earliest occurrence of each highlighted pattern is marked in every sequence that contains it, so the plot answers where a frequent sequence occurs and what surrounds it.

The state distribution plot or chronogram stacks, at every position t, the shares of the events among the sequences that are still running at t [18]; a line adds the cross-sectional entropy −∑ ept(e)log⁡2pt(e), which is low where the cases are synchronized and high where they diverge. The sequence frequency plot draws the most frequent complete sequences as stacked rows with heights proportional to their frequency [18]. It is the right view when whole sequences repeat, as in short web sessions or standardized procedures, and an uninformative one when every case is unique.

8.2.2 Dotted charts

The dotted chart plots every event as a dot at its time and its case [40]. With relative times (time since the start of the case) it shows how long the cases take and when the events happen within them; with absolute times it shows bursts, shifts and seasonality. A highlighted pattern is drawn as a line through its earliest occurrence in each case, which shows its typical position and duration. The duration of the occurrences of several patterns is summarized in a box plot per pattern; with gap_unit="time" the same durations become span constraints for mining (section 2.2.1).

8.2.3 Sequence logos

Aligning the sequences at the first occurrence of an anchor α gives, at every relative position j (negative before α, positive after), a distribution pj(e) of the events found there. The sequence logo stacks the events of each column with heights pj(e)Rj, where

Rj = log⁡2K −Hj,Hj = −∑ epj(e)log⁡2pj(e), (8.1)

is the information content of the column in bits and K the size of the alphabet [41]. Conserved positions — steps that almost always come at that distance from the anchor — are tall, variable positions are low. The logo is the aligned counterpart of the continuation-entropy tree of section 5.2.3: the tree measures uncertainty given the whole prefix, the logo given only the distance from the anchor. Without an anchor the columns are the first positions of the sequences.

8.2.4 Arc diagrams

The arc diagram of Wattenberg draws one long sequence on a line and joins the consecutive non-overlapping occurrences of every maximal repeated contiguous subsequence by a semicircle, whose thickness is the length of the repeat [42]. Large arcs between distant parts reveal the form of a piece of music, a text or a long log: a refrain returns, a bridge stands apart. It complements the frequent sequences of a database: it finds what repeats within one sequence.

8.2.5 Episodes

Many alarm and event logs have no natural case identifier: they are one long stream of timestamped events. Mannila, Toivonen and Verkamo defined episodes for this setting [38]. A serial episode is an ordered sequence of events, a parallel episode a set of events in any order. Given a window width w, WINEPI slides a window [s,s + w) over the stream and defines the frequency of an episode as the share of the windows that contain it; MINEPI counts its minimal occurrences, time intervals [ts,te] of width below w that contain the episode and no shorter interval inside them does. A window [s,s + w) contains the occurrence [ts,te] exactly when te −w < s ≤ts, so the WINEPI frequency of a serial episode is the total length of the union of these intervals over its minimal occurrences, divided by the length T + w of the range of window starts; spmviz computes it this way, without materializing the windows. Serial episodes are grown one event at a time from the minimal occurrences of their prefixes, parallel episodes level by level, as in GSP. The episode timeline draws the minimal occurrences of the top episodes as segments on the time axis, one row per episode.

8.2.6 Summaries by minimum description length

The minimum description length (MDL) principle selects the set of patterns that compresses the data best: the best model is the one that minimizes the length of the model plus the length of the data encoded with it. Krimp applied the principle to itemsets [68], SQS [69] and SQUISH [70] to event sequences, and Sequence Synopsis to the visual summary of event data [71]. spmviz implements a transparent variant. A code table 𝒞𝒯 contains the single events and a set of contiguous patterns. Every sequence is covered greedily from left to right by the code table, longest patterns first; the usage u(X) of a code X is the number of times it is used in the covers, and its code length is the Shannon code length −log⁡2(u(X)∕∑ Y u(Y )). The total description length is

L(𝒞𝒯,𝒟) = L(𝒞𝒯)+L(𝒟∣𝒞𝒯),L(𝒟∣𝒞𝒯) = ∑ Xu(X)(−log⁡2 u(X) ∑ Y u(Y )), (8.2)

where L(𝒞𝒯) encodes every pattern of the table by the codes of its events in the singleton table and by its own code. Candidate patterns, the contiguous frequent sequences, are tried in order of decreasing σ(X)(|X|−1), the number of codes a pattern could save in the covers, and kept when they shorten L; a final pass removes patterns whose removal shortens it further. The result is a handful of patterns that together explain the data, with the compression ratio L(𝒞𝒯,𝒟)∕L(𝒞𝒯0,𝒟) against the singleton-only table 𝒞𝒯0 as a measure of how much structure they capture. The cover plot shows the sequences as rows and colors every run of elements by the pattern that covers it.

Algorithm\special {t4ht^+}

In a nutshell: Sequence views and summaries

  • Index plots show every case; sorted and annotated by patterns they show where a pattern occurs.
  • Chronograms show the distribution of events by position, frequency plots the most common complete sequences.
  • Dotted charts add time; sequence logos align the cases at an anchor and measure how conserved each step is.
  • Arc diagrams find the repeats within one long sequence.
  • Episodes are the patterns of a stream without cases; MDL summaries replace hundreds of patterns by a few that compress the data.

8.3 Using it in spmviz

plot_sequence_index(db, sort, highlight), plot_state_distribution, plot_sequence_frequency, plot_dotted_chart(db, highlight), plot_gap_distribution, plot_sequence_logo(db, anchor) and plot_arc_diagram(sequence) draw the sequence views. mine_episodes(events, times, window, ...) with min_frequency (WINEPI) or min_count (MINEPI) and kind returns an EpisodeSet (a PatternSet with frequencies and minimal occurrences), drawn by plot_episode_timeline. mdl_summary(db, min_support, max_length, max_patterns) returns an MDLSummary with the selected patterns, their usages, the covers and the description lengths, drawn by plot_cover.

8.4 Examples

Index plots. Figure 8.1 shows eighty synthetic alarm floods sorted by two patterns, the pump cascade ⟨𝖯-𝖫𝖮𝖶𝖥𝖫𝖮𝖶𝖯-𝖳𝖱𝖨𝖯𝖮𝖯-𝖯𝖴𝖬𝖯𝖲𝖳𝖠𝖱𝖳⟩and the cooling pair ⟨𝖢-𝖧𝖨𝖳𝖤𝖬𝖯𝖢-𝖵𝖠𝖫𝖵𝖤⟩; their earliest occurrences are marked, and the floods that contain them come first. Sorted by length (fig. 8.2), the same plot shows how long the floods are.

plot_sequence_index(db, max_sequences=80, sort="pattern", 
                    highlight=["P-LOWFLOW P-TRIP OP-PUMPSTART", "C-HITEMP C-VALVE"], max_length=14)
   

Figure 8.1

Figure 8.1. Index plot of eighty alarm floods sorted by two highlighted patterns, whose earliest occurrences are marked.

Open in ColabExample plot_01_index_plot.py in the gallery

Figure 8.2

Figure 8.2. The same floods sorted by length.

Chronogram and frequency plot. The chronogram of the daily routines (fig. 8.3) shows the day unfolding position by position: waking up and coffee at the start, work in the middle, dinner, television and sleep at the end; the entropy line is low at the ends of the day and high in its middle. The sequence frequency plot of the web shop (fig. 8.4) shows that the ten most frequent complete journeys make up 59% of all journeys.

plot_state_distribution(days, max_steps=15) 
plot_sequence_frequency(shop, top=10)
   

Figure 8.3

Figure 8.3. The state distribution plot (chronogram) of the daily routines, with the cross-sectional entropy (line, right axis).

Open in ColabExample plot_02_chronogram_frequency.py in the gallery

Figure 8.4

Figure 8.4. The ten most frequent complete web-shop journeys, bar heights proportional to their frequency.

Dotted chart. Figure 8.5 plots the events of 120 synthetic alarm floods against the time since the start of the flood; the line through the pump cascade shows where in the flood it happens and how long it takes. Figure 8.6 summarizes the time spans of the occurrences of the most frequent patterns as box plots.

plot_dotted_chart(db, max_sequences=120, highlight="P-LOWFLOW P-TRIP OP-PUMPSTART")
   

Figure 8.5

Figure 8.5. Dotted chart of 120 alarm floods (time since the start of each flood); the line follows the pump cascade.

Open in ColabExample plot_03_dotted_chart.py in the gallery

Figure 8.6

Figure 8.6. Time spans of the occurrences of the most frequent patterns.

Sequence logos. Around the first visit to the cart (fig. 8.7) the logo is tallest at the cart itself and at the position just before it, mostly a product page; the positions further away are more variable. The logo of the first notes of the melody phrases (fig. 8.8) shows the probabilities of the notes, without information weighting.

plot_sequence_logo(shop, anchor="cart", before=3, after=4)
   

Figure 8.7

Figure 8.7. Sequence logo of the web-shop journeys around the first visit to the cart; heights in bits.

Open in ColabExample plot_04_sequence_logo.py in the gallery

Figure 8.8

Figure 8.8. The first notes of the phrases of thirteen songs (probabilities).

Arc diagrams of melodies. The arc diagram of Beethoven’s Ode to Joy (fig. 8.9) shows its form at once: the opening phrase returns, joined by the largest arcs, while the bridge stands apart. Twinkle, Twinkle, Little Star (fig. 8.10) repeats its first phrase at the end and its middle phrase twice.

ode = songs[titles.index("Ode to Joy")] 
plot_arc_diagram([e[0] for e in ode], min_length=3, title="Ode to Joy: repeats of at least three notes")
   

Figure 8.9

Figure 8.9. Arc diagram of Ode to Joy: repeats of at least three notes.

Open in ColabExample plot_05_arc_diagram.py in the gallery

Figure 8.10

Figure 8.10. Arc diagram of Twinkle, Twinkle, Little Star.

Episodes of an alarm stream. The busiest day of the alkylation plant, 1,150 events, is treated as one stream with times in minutes. With a ten-minute window, the most frequent serial episode of two events is ⟨𝖮1132𝖮1136⟩, contained in 8% of the windows, with 12 minimal occurrences; fig. 8.11 draws the minimal occurrences of the eight most frequent serial episodes.

ep = sv.mine_episodes(events, times=minutes, window=10, min_frequency=0.02, max_length=3) 
multi = ep.filter(min_length=2) 
print(multi.to_frame().sort_values("frequency", ascending=False).head(8)[["pattern", "frequency", "minimal_occurrences"]]) 
plot_episode_timeline(ep, top=8)
   

Figure 8.11

Figure 8.11. Minimal occurrences of the eight most frequent serial episodes of the busiest day of the alarm log (window ten minutes); the numbers are WINEPI frequencies.

Open in ColabExample plot_06_episodes.py in the gallery

A summary in a few patterns. From the contiguous frequent sequences of the daily routines, the MDL summary keeps eight patterns that shorten the description to 76% of the singleton code (fig. 8.12); among them are the three persona-specific mornings and the evenings ⟨𝗐𝗈𝗋𝗄𝖼𝗈𝗆𝗆𝗎𝗍𝖾𝗀𝗒𝗆𝖽𝗂𝗇𝗇𝖾𝗋𝗍𝗏𝗌𝗅𝖾𝖾𝗉⟩. Allowing 2, 5, 10 or 20 patterns gives compression ratios of 0.93, 0.90, 0.77 and 0.73: the first patterns explain most of the structure.

summary = sv.mdl_summary(db, min_support=0.1, max_length=8, max_patterns=12) 
print(f"{len(summary.patterns)} patterns, description length {summary.compression:.0%} of the singleton code") 
print(summary.to_frame()) 
plot_cover(db, summary, max_sequences=40, max_length=15)
   

Figure 8.12

Figure 8.12. The MDL cover of forty days: every run of activities is colored by the summary pattern that covers it.

Open in ColabExample plot_07_mdl_summary.py in the gallery