1 | package de.ugoe.cs.eventbench.models;
|
---|
2 |
|
---|
3 | import java.util.LinkedList;
|
---|
4 | import java.util.List;
|
---|
5 | import java.util.Random;
|
---|
6 |
|
---|
7 | import de.ugoe.cs.eventbench.data.Event;
|
---|
8 | import de.ugoe.cs.eventbench.markov.IncompleteMemory;
|
---|
9 |
|
---|
10 | public abstract class TrieBasedModel {
|
---|
11 |
|
---|
12 | protected int maxOrder;
|
---|
13 |
|
---|
14 | protected abstract double getProbability(List<Event<?>> context, Event<?> symbol);
|
---|
15 |
|
---|
16 | protected Trie<Event<?>> trie;
|
---|
17 | protected final Random r;
|
---|
18 |
|
---|
19 |
|
---|
20 | public TrieBasedModel(int maxOrder, Random r) {
|
---|
21 | super();
|
---|
22 | this.maxOrder = maxOrder;
|
---|
23 | this.r = r;
|
---|
24 | }
|
---|
25 |
|
---|
26 | public void train(List<List<Event<?>>> sequences) {
|
---|
27 | trie = new Trie<Event<?>>();
|
---|
28 |
|
---|
29 | for(List<Event<?>> sequence : sequences) {
|
---|
30 | List<Event<?>> currentSequence = new LinkedList<Event<?>>(sequence); // defensive copy
|
---|
31 | currentSequence.add(0, Event.STARTEVENT);
|
---|
32 | currentSequence.add(Event.ENDEVENT);
|
---|
33 |
|
---|
34 | trie.train(currentSequence, maxOrder);
|
---|
35 | }
|
---|
36 | }
|
---|
37 |
|
---|
38 | public List<? extends Event<?>> randomSequence() {
|
---|
39 | List<Event<?>> sequence = new LinkedList<Event<?>>();
|
---|
40 |
|
---|
41 | IncompleteMemory<Event<?>> context = new IncompleteMemory<Event<?>>(maxOrder-1);
|
---|
42 | context.add(Event.STARTEVENT);
|
---|
43 |
|
---|
44 | Event<?> currentState = Event.STARTEVENT;
|
---|
45 |
|
---|
46 | boolean endFound = false;
|
---|
47 |
|
---|
48 | while(!endFound) {
|
---|
49 | double randVal = r.nextDouble();
|
---|
50 | double probSum = 0.0;
|
---|
51 | List<Event<?>> currentContext = context.getLast(maxOrder);
|
---|
52 | for( Event<?> symbol : trie.getKnownSymbols() ) {
|
---|
53 | probSum += getProbability(currentContext, symbol);
|
---|
54 | if( probSum>=randVal ) {
|
---|
55 | endFound = (symbol==Event.ENDEVENT);
|
---|
56 | if( !(symbol==Event.STARTEVENT || symbol==Event.ENDEVENT) ) {
|
---|
57 | // only add the symbol the sequence if it is not START or END
|
---|
58 | context.add(symbol);
|
---|
59 | currentState = symbol;
|
---|
60 | sequence.add(currentState);
|
---|
61 | }
|
---|
62 | break;
|
---|
63 | }
|
---|
64 | }
|
---|
65 | }
|
---|
66 | return sequence;
|
---|
67 | }
|
---|
68 |
|
---|
69 | @Override
|
---|
70 | public String toString() {
|
---|
71 | return trie.toString();
|
---|
72 | }
|
---|
73 |
|
---|
74 | } |
---|