source: branches/autoquest-core-tasktrees-alignment/src/main/java/de/ugoe/cs/autoquest/tasktrees/temporalrelation/SequenceForTaskDetectionRuleAlignment.java @ 1693

Last change on this file since 1693 was 1693, checked in by rkrimmel, 10 years ago

Creating more complex models...

File size: 27.1 KB
Line 
1//   Copyright 2012 Georg-August-Universität Göttingen, Germany
2//
3//   Licensed under the Apache License, Version 2.0 (the "License");
4//   you may not use this file except in compliance with the License.
5//   You may obtain a copy of the License at
6//
7//       http://www.apache.org/licenses/LICENSE-2.0
8//
9//   Unless required by applicable law or agreed to in writing, software
10//   distributed under the License is distributed on an "AS IS" BASIS,
11//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//   See the License for the specific language governing permissions and
13//   limitations under the License.
14
15package de.ugoe.cs.autoquest.tasktrees.temporalrelation;
16
17import java.util.ArrayList;
18import java.util.Collections;
19import java.util.Comparator;
20import java.util.HashMap;
21import java.util.HashSet;
22import java.util.Iterator;
23import java.util.LinkedList;
24import java.util.List;
25import java.util.Map;
26import java.util.Set;
27import java.util.logging.Level;
28
29import de.ugoe.cs.autoquest.tasktrees.alignment.algorithms.Match;
30import de.ugoe.cs.autoquest.tasktrees.alignment.algorithms.MatchOccurence;
31import de.ugoe.cs.autoquest.tasktrees.alignment.algorithms.NumberSequence;
32import de.ugoe.cs.autoquest.tasktrees.alignment.matrix.PairwiseAlignmentGenerator;
33import de.ugoe.cs.autoquest.tasktrees.alignment.matrix.PairwiseAlignmentStorage;
34import de.ugoe.cs.autoquest.tasktrees.alignment.matrix.ObjectDistanceSubstitionMatrix;
35import de.ugoe.cs.autoquest.tasktrees.taskequality.TaskEquality;
36import de.ugoe.cs.autoquest.tasktrees.treeifc.IIteration;
37import de.ugoe.cs.autoquest.tasktrees.treeifc.IIterationInstance;
38import de.ugoe.cs.autoquest.tasktrees.treeifc.IOptional;
39import de.ugoe.cs.autoquest.tasktrees.treeifc.ISelection;
40import de.ugoe.cs.autoquest.tasktrees.treeifc.ISelectionInstance;
41import de.ugoe.cs.autoquest.tasktrees.treeifc.ISequence;
42import de.ugoe.cs.autoquest.tasktrees.treeifc.ISequenceInstance;
43import de.ugoe.cs.autoquest.tasktrees.treeifc.ITask;
44import de.ugoe.cs.autoquest.tasktrees.treeifc.ITaskBuilder;
45import de.ugoe.cs.autoquest.tasktrees.treeifc.ITaskFactory;
46import de.ugoe.cs.autoquest.tasktrees.treeifc.ITaskInstance;
47import de.ugoe.cs.autoquest.tasktrees.treeifc.IUserSession;
48import de.ugoe.cs.autoquest.usageprofiles.SymbolMap;
49import de.ugoe.cs.util.StopWatch;
50import de.ugoe.cs.util.console.Console;
51
52/**
53 * <p>
54 * This class implements the major rule for creating task trees based on a set
55 * of recorded user sessions. For this, it first harmonizes all tasks. This
56 * eases later comparison. Then it searches the sessions for iterations and
57 * replaces them accordingly. Then it searches for sub sequences being the
58 * longest and occurring most often. For each found sub sequence, it replaces
59 * the occurrences by creating appropriate {@link ISequence}s. Afterwards, again
60 * searches for iterations and then again for sub sequences until no more
61 * replacements are done.
62 * </p>
63 * <p>
64 *
65 *
66 * @author Patrick Harms
67 */
68class SequenceForTaskDetectionRuleAlignment implements ISessionScopeRule {
69
70        private int iteration = 0;
71        /**
72         * <p>
73         * the task factory to be used for creating substructures for the temporal
74         * relationships identified during rul application
75         * </p>
76         */
77        private ITaskFactory taskFactory;
78        /**
79         * <p>
80         * the task builder to be used for creating substructures for the temporal
81         * relationships identified during rule application
82         * </p>
83         */
84        private ITaskBuilder taskBuilder;
85
86        /**
87         * <p>
88         * the task handling strategy to be used for comparing tasks for
89         * preparation, i.e., before the tasks are harmonized
90         * </p>
91         */
92        private TaskHandlingStrategy preparationTaskHandlingStrategy;
93
94        /**
95         * <p>
96         * instantiates the rule and initializes it with a task equality to be
97         * considered when comparing tasks as well as a task factory and builder to
98         * be used for creating task structures.
99         * </p>
100         *
101         * @param minimalTaskEquality
102         *            the task equality to be considered when comparing tasks
103         * @param taskFactory
104         *            the task factory to be used for creating substructures
105         * @param taskBuilder
106         *            the task builder to be used for creating substructures
107         */
108
109        SequenceForTaskDetectionRuleAlignment(TaskEquality minimalTaskEquality,
110                        ITaskFactory taskFactory, ITaskBuilder taskBuilder) {
111                this.taskFactory = taskFactory;
112                this.taskBuilder = taskBuilder;
113
114                this.preparationTaskHandlingStrategy = new TaskHandlingStrategy(
115                                minimalTaskEquality);
116
117        }
118
119        /*
120         * (non-Javadoc)
121         *
122         * @see java.lang.Object#toString()
123         */
124        @Override
125        public String toString() {
126                return "SequenceForTaskDetectionRuleAlignment";
127        }
128
129        /*
130         * (non-Javadoc)
131         *
132         * @see
133         * de.ugoe.cs.autoquest.tasktrees.temporalrelation.ISessionScopeRule#apply
134         * (java.util.List)
135         */
136        @Override
137        public RuleApplicationResult apply(List<IUserSession> sessions) {
138                RuleApplicationData appData = new RuleApplicationData(sessions);
139
140                harmonizeEventTaskInstancesModel(appData);
141                do {
142                        iteration++;
143
144                        appData.detectedAndReplacedTasks = false;
145                        appData.getStopWatch().start("whole loop");
146                        detectAndReplaceIterations(appData);
147                        appData.getStopWatch().start("task replacement");
148                        detectAndReplaceTasks(appData); //
149                        appData.getStopWatch().stop("task replacement");
150                        appData.getStopWatch().stop("whole loop");
151                        appData.getStopWatch().dumpStatistics(System.out);
152                        appData.getStopWatch().reset();
153
154                } while (appData.detectedAndReplacedTasks());
155
156                Console.println("created "
157                                + appData.getResult().getNewlyCreatedTasks().size()
158                                + " new tasks and "
159                                + appData.getResult().getNewlyCreatedTaskInstances().size()
160                                + " appropriate instances\n");
161
162                if ((appData.getResult().getNewlyCreatedTasks().size() > 0)
163                                || (appData.getResult().getNewlyCreatedTaskInstances().size() > 0)) {
164                        appData.getResult().setRuleApplicationStatus(
165                                        RuleApplicationStatus.FINISHED);
166                }
167
168                return appData.getResult();
169        }
170
171        private ArrayList<NumberSequence> createNumberSequences(
172                        RuleApplicationData appData) {
173                ArrayList<NumberSequence> result = new ArrayList<NumberSequence>();
174                for (int i = 0; i < appData.getSessions().size(); i++) {
175                        IUserSession session = appData.getSessions().get(i);
176                        NumberSequence templist = new NumberSequence(session.size());
177                        for (int j = 0; j < session.size(); j++) {
178                                ITaskInstance taskInstance = session.get(j);
179                                templist.getSequence()[j] = taskInstance.getTask().getId();
180                        }
181                        // Each NumberSequence is identified by its id, beginning to count
182                        // at zero
183                        templist.setId(i);
184                        result.add(templist);
185                }
186                return result;
187        }
188
189        /**
190         * <p>
191         * harmonizes the event task instances by unifying tasks. This is done, as
192         * initially the event tasks being equal with respect to the considered task
193         * equality are distinct objects. The comparison of these distinct objects
194         * is more time consuming than comparing the object references.
195         * </p>
196         *
197         * @param appData
198         *            the rule application data combining all data used for applying
199         *            this rule
200         * @return Returns the unique tasks symbol map
201         */
202        private void harmonizeEventTaskInstancesModel(RuleApplicationData appData) {
203                Console.traceln(Level.INFO,
204                                "harmonizing task model of event task instances");
205                appData.getStopWatch().start("harmonizing event tasks");
206                SymbolMap<ITaskInstance, ITask> uniqueTasks = preparationTaskHandlingStrategy
207                                .createSymbolMap();
208
209                TaskInstanceComparator comparator = preparationTaskHandlingStrategy
210                                .getTaskComparator();
211
212                int unifiedTasks = 0;
213                ITask task;
214                List<IUserSession> sessions = appData.getSessions();
215                for (int j = 0; j < sessions.size(); j++) {
216                        IUserSession session = sessions.get(j);
217
218                        for (int i = 0; i < session.size(); i++) {
219                                ITaskInstance taskInstance = session.get(i);
220                                task = uniqueTasks.getValue(taskInstance);
221
222                                if (task == null) {
223                                        uniqueTasks.addSymbol(taskInstance, taskInstance.getTask());
224                                        appData.getUniqueTasks().add(taskInstance.getTask());
225                                        appData.getNumber2Task().put(
226                                                        taskInstance.getTask().getId(),
227                                                        taskInstance.getTask());
228                                } else {
229                                        taskBuilder.setTask(taskInstance, task);
230                                        unifiedTasks++;
231                                }
232                        }
233                        comparator.clearBuffers();
234                }
235
236                appData.getStopWatch().stop("harmonizing event tasks");
237                Console.traceln(Level.INFO, "harmonized " + unifiedTasks
238                                + " task occurrences (still " + appData.getUniqueTasks().size()
239                                + " different tasks)");
240
241                appData.getStopWatch().dumpStatistics(System.out);
242                appData.getStopWatch().reset();
243        }
244
245        /**
246         * <p>
247         * searches for direct iterations of single tasks in all sequences and
248         * replaces them with {@link IIteration}s, respectively appropriate
249         * instances. Also all single occurrences of a task that is iterated
250         * somewhen are replaced with iterations to have again an efficient way for
251         * task comparisons.
252         * </p>
253         *
254         * @param appData
255         *            the rule application data combining all data used for applying
256         *            this rule
257         */
258        private void detectAndReplaceIterations(RuleApplicationData appData) {
259                Console.traceln(Level.FINE, "detecting iterations");
260                appData.getStopWatch().start("detecting iterations");
261
262                List<IUserSession> sessions = appData.getSessions();
263
264                Set<ITask> iteratedTasks = searchIteratedTasks(sessions);
265
266                if (iteratedTasks.size() > 0) {
267                        replaceIterationsOf(iteratedTasks, sessions, appData);
268                }
269
270                appData.getStopWatch().stop("detecting iterations");
271                Console.traceln(Level.INFO, "replaced " + iteratedTasks.size()
272                                + " iterated tasks");
273        }
274
275        /**
276         * <p>
277         * searches the provided sessions for task iterations. If a task is
278         * iterated, it is added to the returned set.
279         * </p>
280         *
281         * @param the
282         *            session to search for iterations in
283         *
284         * @return a set of tasks being iterated somewhere
285         */
286        private Set<ITask> searchIteratedTasks(List<IUserSession> sessions) {
287                Set<ITask> iteratedTasks = new HashSet<ITask>();
288                for (IUserSession session : sessions) {
289                        for (int i = 0; i < (session.size() - 1); i++) {
290                                // we prepared the task instances to refer to unique tasks, if
291                                // they are treated
292                                // as equal. Therefore, we just compare the identity of the
293                                // tasks of the task
294                                // instances
295                                if (session.get(i).getTask() == session.get(i + 1).getTask()) {
296                                        iteratedTasks.add(session.get(i).getTask());
297                                }
298                        }
299                }
300                return iteratedTasks;
301        }
302
303        /**
304         * <p>
305         * replaces all occurrences of all tasks provided in the set with iterations
306         * </p>
307         *
308         * @param iteratedTasks
309         *            the tasks to be replaced with iterations
310         * @param sessions
311         *            the sessions in which the tasks are to be replaced
312         * @param appData
313         *            the rule application data combining all data used for applying
314         *            this rule
315         */
316        private void replaceIterationsOf(Set<ITask> iteratedTasks,
317                        List<IUserSession> sessions, RuleApplicationData appData) {
318                Map<ITask, IIteration> iterations = new HashMap<ITask, IIteration>();
319                Map<IIteration, List<IIterationInstance>> iterationInstances = new HashMap<IIteration, List<IIterationInstance>>();
320
321                for (ITask iteratedTask : iteratedTasks) {
322
323                        IIteration iteration = taskFactory.createNewIteration();
324                        appData.getUniqueTasks().add(iteration);
325                        appData.getNumber2Task().put(iteration.getId(), iteration);
326                        iterations.put(iteratedTask, iteration);
327                        iterationInstances.put(iteration,
328                                        new LinkedList<IIterationInstance>());
329                }
330
331                IIterationInstance iterationInstance;
332
333                for (IUserSession session : sessions) {
334                        int index = 0;
335                        iterationInstance = null;
336
337                        while (index < session.size()) {
338                                // we prepared the task instances to refer to unique tasks, if
339                                // they are treated
340                                // as equal. Therefore, we just compare the identity of the
341                                // tasks of the task
342                                // instances
343                                ITask currentTask = session.get(index).getTask();
344                                IIteration iteration = iterations.get(currentTask);
345                                if (iteration != null) {
346                                        if ((iterationInstance == null)
347                                                        || (iterationInstance.getTask() != iteration)) {
348                                                iterationInstance = taskFactory
349                                                                .createNewTaskInstance(iteration);
350                                                iterationInstances.get(iteration)
351                                                                .add(iterationInstance);// TODO:: Don't create
352                                                                                                                // TaskInstances here,
353                                                                                                                // use a set of tasks
354                                                                                                                // instead
355                                                taskBuilder.addTaskInstance(session, index,
356                                                                iterationInstance);
357                                                index++;
358                                        }
359
360                                        taskBuilder.addChild(iterationInstance, session.get(index));
361                                        taskBuilder.removeTaskInstance(session, index);
362                                } else {
363                                        if (iterationInstance != null) {
364                                                iterationInstance = null;
365                                        }
366                                        index++;
367                                }
368                        }
369                }
370
371                for (Map.Entry<IIteration, List<IIterationInstance>> entry : iterationInstances
372                                .entrySet()) {
373                        harmonizeIterationInstancesModel(entry.getKey(), entry.getValue());
374                }
375        }
376
377        /**
378         * <p>
379         * TODO clarify why this is done
380         * </p>
381         */
382        private void harmonizeIterationInstancesModel(IIteration iteration,
383                        List<IIterationInstance> iterationInstances) {
384                List<ITask> iteratedTaskVariants = new LinkedList<ITask>();
385                TaskInstanceComparator comparator = preparationTaskHandlingStrategy
386                                .getTaskComparator();
387
388                // merge the lexically different variants of iterated task to a unique
389                // list
390                for (IIterationInstance iterationInstance : iterationInstances) {
391                        for (ITaskInstance executionVariant : iterationInstance) {
392                                ITask candidate = executionVariant.getTask();
393
394                                boolean found = false;
395                                for (ITask taskVariant : iteratedTaskVariants) {
396                                        if (comparator.areLexicallyEqual(taskVariant, candidate)) {
397                                                taskBuilder.setTask(executionVariant, taskVariant);
398                                                found = true;
399                                                break;
400                                        }
401                                }
402
403                                if (!found) {
404                                        iteratedTaskVariants.add(candidate);
405                                }
406                        }
407                }
408
409                // if there are more than one lexically different variant of iterated
410                // tasks, adapt the
411                // iteration model to be a selection of different variants. In this case
412                // also adapt
413                // the generated iteration instances to correctly contain selection
414                // instances. If there
415                // is only one variant of an iterated task, simply set this as the
416                // marked task of the
417                // iteration. In this case, the instances can be preserved as is
418                if (iteratedTaskVariants.size() > 1) {
419                        ISelection selection = taskFactory.createNewSelection();
420
421                        for (ITask variant : iteratedTaskVariants) {
422                                taskBuilder.addChild(selection, variant);
423                        }
424
425                        taskBuilder.setMarkedTask(iteration, selection);
426
427                        for (IIterationInstance instance : iterationInstances) {
428                                for (int i = 0; i < instance.size(); i++) {
429                                        ISelectionInstance selectionInstance = taskFactory
430                                                        .createNewTaskInstance(selection);
431                                        taskBuilder.setChild(selectionInstance, instance.get(i));
432                                        taskBuilder.setTaskInstance(instance, i, selectionInstance);
433                                }
434                        }
435                } else {
436                        taskBuilder.setMarkedTask(iteration, iteratedTaskVariants.get(0));
437                }
438        }
439
440        /**
441         * @param appData
442         * @param m
443         * @return
444         */
445        public ISequence matchAsSequence(RuleApplicationData appData, Match m) {
446               
447                System.out.println("DEBUGGING MODEL GENERATION");
448                System.out.println();
449               
450                ISequence sequence = taskFactory.createNewSequence();
451                appData.uniqueTasks.add(sequence);
452                appData.number2task.put(sequence.getId(), sequence);
453
454                int[] first = m.getFirstSequence().getSequence();
455                int[] second = m.getSecondSequence().getSequence();
456
457                // Both sequences of a match are equally long
458                for (int i = 0; i < m.getFirstSequence().size(); i++) {
459
460                        // Two gaps aligned to each other: Have not seen it happening so
461                        // far, just to handle it
462                        if (first[i] == -1 && second[i] == -1) {
463                                // Do nothing here.
464                        }
465                        // Both events are equal, we can simply add the task referring to
466                        // the number
467                        else if (first[i] == second[i]) {
468                                taskBuilder.addChild(sequence,
469                                                appData.getNumber2Task().get(first[i]));
470                        }
471                        // We have a gap in the first sequence, we need to add the task of
472                        // the second sequence as optional
473                        else if (first[i] == -1 && second[i] != -1) {
474                                IOptional optional = taskFactory.createNewOptional();
475                                appData.uniqueTasks.add(optional);
476                                appData.number2task.put(optional.getId(), optional);
477                                taskBuilder.setMarkedTask(optional, appData.getNumber2Task()
478                                                .get(second[i]));
479                                taskBuilder.addChild(sequence, optional);
480                        }
481                        // We have a gap in the second sequence, we need to add the task of
482                        // the first sequence as optional
483                        else if (first[i] != -1 && second[i] == -1) {
484                                IOptional optional = taskFactory.createNewOptional();
485                                appData.uniqueTasks.add(optional);
486                                appData.number2task.put(optional.getId(), optional);
487                                taskBuilder.setMarkedTask(optional, appData.getNumber2Task()
488                                                .get(first[i]));
489                                taskBuilder.addChild(sequence, optional);
490                        }
491                        // Both tasks are not equal, we need to insert a selection here.
492                        // Check if the next position is not a selection
493                        else if (i < first.length - 1) {
494
495                                if ((first[i] != second[i])
496                                                && ((first[i + 1] == second[i + 1]
497                                                                || first[i + 1] == -1 || second[i + 1] == -1))) {
498
499                                        ISelection selection = taskFactory.createNewSelection();
500                                        appData.getUniqueTasks().add(selection);
501                                        appData.number2task.put(selection.getId(), selection);
502                                        taskBuilder.addChild(selection, appData.getNumber2Task()
503                                                        .get(first[i]));
504                                        taskBuilder.addChild(selection, appData.getNumber2Task()
505                                                        .get(second[i]));
506                                        taskBuilder.addChild(sequence, selection);
507                                } else {
508                                        System.out.println("SELECTION OF SEQUENCES FOUND!");
509                                        boolean selectionfound = true;
510                                        ISelection selection = taskFactory.createNewSelection();
511                                        appData.getUniqueTasks().add(selection);
512                                        appData.number2task.put(selection.getId(), selection);
513
514                                        ISequence subsequence1 = taskFactory.createNewSequence();
515                                        appData.uniqueTasks.add(subsequence1);
516                                        appData.number2task.put(subsequence1.getId(), subsequence1);
517
518                                        ISequence subsequence2 = taskFactory.createNewSequence();
519                                        appData.uniqueTasks.add(subsequence2);
520                                        appData.number2task.put(subsequence2.getId(), subsequence2);
521
522                                        taskBuilder.addChild(selection, subsequence1);
523                                        taskBuilder.addChild(selection, subsequence2);
524                                        taskBuilder.addChild(sequence,selection);
525                                        while (i < first.length - 1 && selectionfound) {
526                                                selectionfound = false;
527                                                taskBuilder.addChild(subsequence1, appData
528                                                                .getNumber2Task().get(first[i]));
529                                                taskBuilder.addChild(subsequence2, appData
530                                                                .getNumber2Task().get(second[i]));
531                                                if (first[i + 1] != second[i + 1] && first[i + 1] != -1
532                                                                && second[i + 1] != -1) {
533                                                        selectionfound = true;
534                                                }
535                                                i++;
536                                        }
537                                        if(i==first.length-1 && selectionfound) {
538                                                taskBuilder.addChild(subsequence1, appData
539                                                                .getNumber2Task().get(first[i]));
540                                                taskBuilder.addChild(subsequence2, appData
541                                                                .getNumber2Task().get(second[i]));
542                                        }
543                                }
544                        }
545
546                        else {
547                                if ((first[i] != second[i])) {
548
549                                        ISelection selection = taskFactory.createNewSelection();
550                                        appData.getUniqueTasks().add(selection);
551                                        appData.number2task.put(selection.getId(), selection);
552                                        taskBuilder.addChild(selection, appData.getNumber2Task()
553                                                        .get(first[i]));
554                                        taskBuilder.addChild(selection, appData.getNumber2Task()
555                                                        .get(second[i]));
556                                        taskBuilder.addChild(sequence, selection);
557                                }
558                        }
559
560                }
561                return sequence;
562        }
563
564        /**
565         *
566         * @param appData
567         *            the rule application data combining all data used for applying
568         *            this rule
569         */
570        private void detectAndReplaceTasks(RuleApplicationData appData) {
571                Console.traceln(Level.FINE, "detecting and replacing tasks");
572                appData.getStopWatch().start("detecting tasks");
573
574                // Create NumberSequences
575                appData.setNumberSequences(this.createNumberSequences(appData));
576
577                // Generate a substitution matrix between all occurring events.
578                Console.traceln(Level.INFO, "generating substitution matrix");
579                ObjectDistanceSubstitionMatrix submat = new ObjectDistanceSubstitionMatrix(
580                                appData.getUniqueTasks(), 6, -3);
581                submat.generate();
582
583                // Generate pairwise alignments
584                Console.traceln(Level.INFO, "generating pairwise alignments");
585                LinkedList<Match> matchseqs = new LinkedList<Match>();
586                PairwiseAlignmentStorage alignments = PairwiseAlignmentGenerator
587                                .generate(appData.getNumberSequences(), submat, 9);
588
589                // Retrieve all matches reached a specific threshold
590                Console.traceln(Level.INFO, "retrieving significant sequence pieces");
591                for (int i = 0; i < appData.getNumberSequences().size(); i++) {
592                        Console.traceln(
593                                        Level.FINEST,
594                                        "retrieving significant sequence pieces:  "
595                                                        + Math.round((float) i
596                                                                        / (float) appData.getNumberSequences()
597                                                                                        .size() * 100) + "%");
598                        for (int j = 0; j < appData.getNumberSequences().size(); j++) {
599                                if (i != j) {
600                                        matchseqs.addAll(alignments.get(i, j).getMatches());
601                                }
602                        }
603                }
604
605                Console.traceln(Level.FINEST,
606                                "retrieving significant sequence pieces:  100%");
607                Console.traceln(Level.INFO, "searching for patterns occuring most");
608
609                // search each match in every other sequence
610                for (Iterator<Match> it = matchseqs.iterator(); it.hasNext();) {
611                        Match pattern = it.next();
612
613                        // Skip sequences with more 0 events (scrolls) than other events.
614                        // Both of the pattern sequences are equally long, so the zero
615                        // counts just need to be smaller than the length of one sequence
616                        if (pattern.getFirstSequence().eventCount(0)
617                                        + pattern.getSecondSequence().eventCount(0) + 1 > pattern
618                                        .getFirstSequence().size())
619                                continue;
620
621                        for (int j = 0; j < appData.getNumberSequences().size(); j++) {
622                                LinkedList<Integer> startpositions = appData
623                                                .getNumberSequences().get(j).containsPattern(pattern);
624                                if (startpositions.size() > 0) {
625                                        for (Iterator<Integer> jt = startpositions.iterator(); jt
626                                                        .hasNext();) {
627                                                int start = jt.next();
628                                                pattern.addOccurence(new MatchOccurence(start, start
629                                                                + pattern.size(), j));
630                                        }
631
632                                }
633                        }
634                }
635
636                Console.traceln(Level.INFO, "sorting results");
637                // Sort results to get the most occurring results
638                Comparator<Match> comparator = new Comparator<Match>() {
639                        public int compare(Match m1, Match m2) {
640                                return m2.occurenceCount() - m1.occurenceCount();
641
642                        }
643                };
644                Collections.sort(matchseqs, comparator);
645                appData.getStopWatch().stop("detecting tasks");
646
647                appData.getStopWatch().start("replacing tasks");
648                HashMap<Integer, List<MatchOccurence>> replacedOccurences = new HashMap<Integer, List<MatchOccurence>>();
649                // Replace matches in the sessions
650                for (int i = 0; i < matchseqs.size(); i++) {
651                        // Every pattern consists of 2 sequences, therefore the minimum
652                        // occurrences here is 2.
653                        // We just need the sequences also occurring in other sequences as
654                        // well
655                        if (matchseqs.get(i).occurenceCount() > 2) {
656
657                                appData.detectedAndReplacedTasks = true;
658                                ISequence task = matchAsSequence(appData, matchseqs.get(i));
659                                invalidOccurence: for (Iterator<MatchOccurence> it = matchseqs
660                                                .get(i).getOccurences().iterator(); it.hasNext();) {
661                                        MatchOccurence oc = it.next();
662                                       
663                                        if (iteration > 0) {
664                                         
665                                        System.out.println("Trying to replace sequence: ");
666                                        matchseqs.get(i).getFirstSequence().printSequence();
667                                        matchseqs.get(i).getSecondSequence().printSequence();
668                                        System.out.println(" in session number: "
669                                                        + (oc.getSequenceId() + 1) + " at position "
670                                                        + (oc.getStartindex()) + "-" + oc.getEndindex());
671                                        System.out.println();
672
673                                        System.out.println("Printing session: ");
674                                        for (int j = 0; j < appData.getSessions()
675                                                        .get(oc.getSequenceId()).size(); j++) {
676                                                System.out.println(j
677                                                                + ": "
678                                                                + appData.getSessions().get(oc.getSequenceId())
679                                                                                .get(j));
680                                        }
681                                        }
682                                        // Check if nothing has been replaced in the sequence we
683                                        // want to replace
684                                        if (replacedOccurences.get(oc.getSequenceId()) == null) {
685                                                replacedOccurences.put(oc.getSequenceId(),
686                                                                new LinkedList<MatchOccurence>());
687                                        } else {
688                                                // check if we have any replaced occurence with indexes
689                                                // smaller than ours. If so, we need to adjust our start
690                                                // and endpoints
691                                                // of the replacement.
692                                                // Also do a check if we have replaced this specific
693                                                // MatchOccurence in this sequence already. Jump to the
694                                                // next occurence if this is the case.
695                                                // This is no more neccessary once the matches are
696                                                // harmonized.
697                                                for (Iterator<MatchOccurence> jt = replacedOccurences
698                                                                .get(oc.getSequenceId()).iterator(); jt
699                                                                .hasNext();) {
700                                                        MatchOccurence tmpOC = jt.next();
701
702                                                        if (oc.getStartindex() >= tmpOC.getStartindex()
703                                                                        && oc.getStartindex() <= tmpOC
704                                                                                        .getEndindex()) {
705                                                                continue invalidOccurence;
706                                                        }
707                                                        if (oc.getEndindex() >= tmpOC.getStartindex()) {
708                                                                continue invalidOccurence;
709
710                                                        } else if (oc.getStartindex() > tmpOC.getEndindex()) {
711                                                                int diff = tmpOC.getEndindex()
712                                                                                - tmpOC.getStartindex();
713                                                                // Just to be sure.
714                                                                if (diff > 0) {
715                                                                        oc.setStartindex(oc.getStartindex() - diff
716                                                                                        + 1);
717                                                                        oc.setEndindex(oc.getEndindex() - diff + 1);
718                                                                } else {
719                                                                        Console.traceln(Level.WARNING,
720                                                                                        "End index of a Match before start. This should never happen");
721                                                                }
722                                                        }
723                                                }
724                                        }
725                                        ISequenceInstance sequenceInstances = RuleUtils
726                                                        .createNewSubSequenceInRange(appData.getSessions()
727                                                                        .get(oc.getSequenceId()), oc
728                                                                        .getStartindex(), oc.getEndindex(), task,
729                                                                        taskFactory, taskBuilder);
730                                        // Adjust the length of the match regarding to the length of
731                                        // instance. (OptionalInstances may be shorter)
732                                        oc.setEndindex(oc.getStartindex()
733                                                        + sequenceInstances.size()
734                                                        - RuleUtils.missedOptionals);
735                                        replacedOccurences.get(oc.getSequenceId()).add(oc);
736                                }
737                        }
738                }
739
740                alignments = null;
741                matchseqs = null;
742                appData.getStopWatch().stop("replacing tasks");
743        }
744
745        /**
746     *
747     */
748        private static class RuleApplicationData {
749
750                private HashMap<Integer, ITask> number2task;
751
752                // TODO: We Actually just need number2task here
753                private HashSet<ITask> uniqueTasks;
754
755                private ArrayList<NumberSequence> numberseqs;
756
757                /**
758         *
759         */
760                private List<IUserSession> sessions;
761
762                /**
763         *
764         */
765                private boolean detectedAndReplacedTasks;
766
767                /**
768         *
769         */
770                private RuleApplicationResult result;
771
772                /**
773         *
774         */
775                private StopWatch stopWatch;
776
777                /**
778         *
779         */
780                private RuleApplicationData(List<IUserSession> sessions) {
781                        this.sessions = sessions;
782                        numberseqs = new ArrayList<NumberSequence>();
783                        uniqueTasks = new HashSet<ITask>();
784                        number2task = new HashMap<Integer, ITask>();
785                        stopWatch = new StopWatch();
786                        result = new RuleApplicationResult();
787                }
788
789                /**
790                 * @return the tree
791                 */
792                private List<IUserSession> getSessions() {
793                        return sessions;
794                }
795
796                private HashSet<ITask> getUniqueTasks() {
797                        return uniqueTasks;
798                }
799
800                // private void setUniqueTasks(SymbolMap<ITaskInstance, ITask> ut) {
801                // this.uniqueTasks = ut;
802                // }
803
804                private void setNumberSequences(ArrayList<NumberSequence> numberseqs) {
805                        this.numberseqs = numberseqs;
806                }
807
808                private ArrayList<NumberSequence> getNumberSequences() {
809                        return numberseqs;
810                }
811
812                /**
813         *
814         */
815                private boolean detectedAndReplacedTasks() {
816                        return detectedAndReplacedTasks;
817                }
818
819                /**
820                 * @return the result
821                 */
822                private RuleApplicationResult getResult() {
823                        return result;
824                }
825
826                /**
827                 * @return the stopWatch
828                 */
829                private StopWatch getStopWatch() {
830                        return stopWatch;
831                }
832
833                private HashMap<Integer, ITask> getNumber2Task() {
834                        return number2task;
835                }
836
837        }
838
839}
Note: See TracBrowser for help on using the repository browser.