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