source: branches/ralph/src/main/java/de/ugoe/cs/autoquest/tasktrees/temporalrelation/SequenceForTaskDetectionRuleAlignment.java @ 1630

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

Generated Model of matches.

File size: 27.4 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.ITaskInstanceList;
48import de.ugoe.cs.autoquest.tasktrees.treeifc.IUserSession;
49import de.ugoe.cs.autoquest.usageprofiles.SymbolMap;
50import de.ugoe.cs.util.StopWatch;
51import de.ugoe.cs.util.console.Console;
52
53/**
54 * <p>
55 * This class implements the major rule for creating task trees based on a set
56 * of recorded user sessions. For this, it first harmonizes all tasks. This
57 * eases later comparison. Then it searches the sessions for iterations and
58 * replaces them accordingly. Then it searches for sub sequences being the
59 * longest and occurring most often. For each found sub sequence, it replaces
60 * the occurrences by creating appropriate {@link ISequence}s. Afterwards, again
61 * searches for iterations and then again for sub sequences until no more
62 * replacements are done.
63 * </p>
64 * <p>
65 *
66 *
67 * @author Patrick Harms
68 */
69class SequenceForTaskDetectionRuleAlignment implements ISessionScopeRule {
70
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         * the task handling strategy to be used for comparing tasks during
97         * iteration detection i.e., after the tasks are
98         * harmonized
99         * </p>
100         */
101        private TaskHandlingStrategy identityTaskHandlingStrategy;
102
103
104
105        /**
106         * <p>
107         * instantiates the rule and initializes it with a task equality to be
108         * considered when comparing tasks as well as a task factory and builder to
109         * be used for creating task structures.
110         * </p>
111         *
112         * @param minimalTaskEquality
113         *            the task equality to be considered when comparing tasks
114         * @param taskFactory
115         *            the task factory to be used for creating substructures
116         * @param taskBuilder
117         *            the task builder to be used for creating substructures
118         */
119
120        SequenceForTaskDetectionRuleAlignment(TaskEquality minimalTaskEquality,
121                        ITaskFactory taskFactory, ITaskBuilder taskBuilder) {
122                this.taskFactory = taskFactory;
123                this.taskBuilder = taskBuilder;
124
125                this.preparationTaskHandlingStrategy = new TaskHandlingStrategy(
126                                minimalTaskEquality);
127                this.identityTaskHandlingStrategy = new TaskHandlingStrategy(
128                                TaskEquality.IDENTICAL);
129
130        }
131
132        /*
133         * (non-Javadoc)
134         *
135         * @see java.lang.Object#toString()
136         */
137        @Override
138        public String toString() {
139                return "SequenceForTaskDetectionRuleAlignment";
140        }
141
142        /*
143         * (non-Javadoc)
144         *
145         * @see
146         * de.ugoe.cs.autoquest.tasktrees.temporalrelation.ISessionScopeRule#apply
147         * (java.util.List)
148         */
149        @Override
150        public RuleApplicationResult apply(List<IUserSession> sessions) {
151                RuleApplicationData appData = new RuleApplicationData(sessions);
152
153                // this is the real rule application. Loop while something is replaced.
154                SymbolMap<ITaskInstance, ITask> uniqueTasks = harmonizeEventTaskInstancesModel(appData);
155
156                // Generate a substitution matrix between all occurring events.
157                Console.traceln(Level.INFO, "generating substitution matrix");
158                ObjectDistanceSubstitionMatrix submat = new ObjectDistanceSubstitionMatrix(
159                                uniqueTasks, 6, -3);
160                submat.generate();
161
162                // Generate pairwise alignments
163                Console.traceln(Level.INFO, "generating pairwise alignments");
164                LinkedList<Match> matchseqs = new LinkedList<Match>();
165                PairwiseAlignmentStorage alignments = PairwiseAlignmentGenerator
166                                .generate(appData.getNumberSequences(), submat, 9);
167
168                // Retrieve all matches reached a specific threshold
169                Console.traceln(Level.INFO, "retrieving significant sequence pieces");
170                for (int i = 0; i < appData.getNumberSequences().size(); i++) {
171                        Console.traceln(
172                                        Level.FINEST,
173                                        "retrieving significant sequence pieces:  "
174                                                        + Math.round((float) i / (float) appData.getNumberSequences().size()
175                                                                        * 100) + "%");
176                        for (int j = 0; j < appData.getNumberSequences().size(); j++) {
177                                if (i != j) {
178                                        matchseqs.addAll(alignments.get(i, j).getMatches());
179                                }
180                        }
181                }
182                Console.traceln(Level.FINEST,
183                                "retrieving significant sequence pieces:  100%");
184                Console.traceln(Level.INFO, "searching for patterns occuring most");
185
186                // search each match in every other sequence
187                for (Iterator<Match> it = matchseqs.iterator(); it.hasNext();) {
188                        Match pattern = it.next();
189
190                        // Skip sequences with more 0 events (scrolls) than other events.
191                        // Both of the pattern sequences are equally long, so the added 0
192                        // counts
193                        // just need to be smaller than the length of one sequence
194                        if (pattern.getFirstSequence().eventCount(0)
195                                        + pattern.getSecondSequence().eventCount(0) + 1 > pattern
196                                        .getFirstSequence().size())
197                                continue;
198       
199                        for (int j = 0; j < appData.getNumberSequences().size(); j++) {
200                                LinkedList<Integer> startpositions = appData.getNumberSequences().get(j)
201                                                .containsPattern(pattern);
202                                if (startpositions.size() > 0) {
203                                       
204                                        for (Iterator<Integer> jt = startpositions.iterator(); jt
205                                                        .hasNext();) {
206                                                pattern.addOccurence(
207                                                                new MatchOccurence(jt.next(), j));
208                                        }
209
210                                }
211                        }
212                }
213
214                Console.traceln(Level.INFO, "sorting results");
215                // Sort results to get the most occurring results
216                Comparator<Match> comparator = new Comparator<Match>() {
217                        public int compare(Match m1, Match m2) {
218                                return m2.occurenceCount() - m1.occurenceCount(); // use your
219                                                                                                                                        // logic
220                        }
221                };
222                Collections.sort(matchseqs, comparator);
223               
224
225                // TODO: Harmonize matches: finding double matches and merge them
226                /*
227                Console.traceln(Level.INFO, "harmonizing matches");
228                int i=0;
229               
230                while(i<matchseqs.size()) {
231                        int j=i;
232                        while(j<matchseqs.size()) {
233                                if(i!=j) {
234                                        if(matchseqs.get(i).equals(matchseqs.get(j))) {
235                                                //matchseqs.get(i).addOccurencesOf(matchseqs.get(j));
236                                                matchseqs.remove(j);
237                                       
238                                                //System.out.println("Sequence " + i);
239                                                //matchseqs.get(i).getFirstSequence().printSequence();
240                                                //matchseqs.get(i).getSecondSequence().printSequence();
241                                                //System.out.println("is equal to sequence " + j);
242                                                //matchseqs.get(j).getFirstSequence().printSequence();
243                                                //matchseqs.get(j).getSecondSequence().printSequence();
244                                                continue;
245                                        }
246                                }
247                                j++;
248                        }
249                        i++;
250                }
251                Collections.sort(matchseqs, comparator);
252                */
253               
254               
255                // Just printing the results out
256                for (int i = 0; i < matchseqs.size(); i++) {
257                        // Every pattern consists of 2 sequences, therefore the minimum
258                        // occurrences here is 2.
259                        // We just need the sequences also occurring in other sequences as
260                        // well
261                        if (matchseqs.get(i).occurenceCount() > 2) {
262                               
263                                ITask task = matchAsTask(appData,matchseqs.get(i));
264                                System.out.println(task);
265                                //matchseqs.get(i).getFirstSequence().printSequence();
266                                //matchseqs.get(i).getSecondSequence().printSequence();
267                                //System.out.println("Found pattern "
268                                //              + matchseqs.get(i).occurenceCount() + " times");
269                                System.out.println();
270                        }
271                }
272               
273
274                alignments = null;
275
276                do {
277                 
278                  appData.getStopWatch().start("whole loop"); //
279                  detectAndReplaceIterations(appData);
280                 
281                  appData.getStopWatch().start("task replacement"); //
282                  //detectAndReplaceTasks(appData); //
283                  appData.getStopWatch().stop("task replacement"); //
284                  appData.getStopWatch().stop("whole loop");
285                 
286                  appData.getStopWatch().dumpStatistics(System.out); //
287                  appData.getStopWatch().reset();
288                 
289                  } while (appData.detectedAndReplacedTasks());
290                 
291
292                Console.println("created "
293                                + appData.getResult().getNewlyCreatedTasks().size()
294                                + " new tasks and "
295                                + appData.getResult().getNewlyCreatedTaskInstances().size()
296                                + " appropriate instances\n");
297
298                if ((appData.getResult().getNewlyCreatedTasks().size() > 0)
299                                || (appData.getResult().getNewlyCreatedTaskInstances().size() > 0)) {
300                        appData.getResult().setRuleApplicationStatus(
301                                        RuleApplicationStatus.FINISHED);
302                }
303
304                return appData.getResult();
305        }
306
307       
308       
309        /**
310         * <p>
311         * harmonizes the event task instances by unifying tasks. This is done, as
312         * initially the event tasks being equal with respect to the considered task
313         * equality are distinct objects. The comparison of these distinct objects
314         * is more time consuming than comparing the object references.
315         * </p>
316         *
317         * @param appData
318         *            the rule application data combining all data used for applying
319         *            this rule
320         * @return Returns the unique tasks symbol map
321         */
322        private SymbolMap<ITaskInstance, ITask> harmonizeEventTaskInstancesModel(
323                        RuleApplicationData appData) {
324                Console.traceln(Level.INFO,
325                                "harmonizing task model of event task instances");
326                appData.getStopWatch().start("harmonizing event tasks");
327
328                SymbolMap<ITaskInstance, ITask> uniqueTasks = preparationTaskHandlingStrategy
329                                .createSymbolMap();
330                TaskInstanceComparator comparator = preparationTaskHandlingStrategy
331                                .getTaskComparator();
332
333                int unifiedTasks = 0;
334                ITask task;
335                List<IUserSession> sessions = appData.getSessions();
336                int sessionNo = 0;
337                for (IUserSession session : sessions) {
338                        Console.traceln(Level.FINE, "handling " + (++sessionNo) + ". "
339                                        + session);
340                        NumberSequence templist = new NumberSequence(session.size());
341
342                        for (int i = 0; i < session.size(); i++) {
343                                ITaskInstance taskInstance = session.get(i);
344                                task = uniqueTasks.getValue(taskInstance);
345
346                                if (task == null) {
347                                        uniqueTasks.addSymbol(taskInstance, taskInstance.getTask());
348                                        templist.getSequence()[i] = taskInstance.getTask().getId();
349               
350                                } else {
351                                        taskBuilder.setTask(taskInstance, task);
352                                        templist.getSequence()[i] = task.getId();
353                                        unifiedTasks++;
354                                }
355                                appData.getNumber2Task().put(templist.getSequence()[i], taskInstance.getTask());
356                        }
357                        templist.setId(appData.getNumberSequences().size());
358                        appData.getNumberSequences().add(templist);
359                        comparator.clearBuffers();
360                }
361
362                appData.getStopWatch().stop("harmonizing event tasks");
363                Console.traceln(Level.INFO, "harmonized " + unifiedTasks
364                                + " task occurrences (still " + uniqueTasks.size()
365                                + " different tasks)");
366
367                appData.getStopWatch().dumpStatistics(System.out);
368                appData.getStopWatch().reset();
369                return uniqueTasks;
370        }
371
372        /**
373         * <p>
374         * searches for direct iterations of single tasks in all sequences and
375         * replaces them with {@link IIteration}s, respectively appropriate
376         * instances. Also all single occurrences of a task that is iterated
377         * somewhen are replaced with iterations to have again an efficient way for
378         * task comparisons.
379         * </p>
380         *
381         * @param appData
382         *            the rule application data combining all data used for applying
383         *            this rule
384         */
385        private void detectAndReplaceIterations(RuleApplicationData appData) {
386                Console.traceln(Level.FINE, "detecting iterations");
387                appData.getStopWatch().start("detecting iterations");
388
389                List<IUserSession> sessions = appData.getSessions();
390
391                Set<ITask> iteratedTasks = searchIteratedTasks(sessions);
392
393                if (iteratedTasks.size() > 0) {
394                        replaceIterationsOf(iteratedTasks, sessions, appData);
395                }
396
397                appData.getStopWatch().stop("detecting iterations");
398                Console.traceln(Level.INFO, "replaced " + iteratedTasks.size()
399                                + " iterated tasks");
400        }
401
402        /**
403         * <p>
404         * searches the provided sessions for task iterations. If a task is
405         * iterated, it is added to the returned set.
406         * </p>
407         *
408         * @param the
409         *            session to search for iterations in
410         *
411         * @return a set of tasks being iterated somewhere
412         */
413        private Set<ITask> searchIteratedTasks(List<IUserSession> sessions) {
414                Set<ITask> iteratedTasks = new HashSet<ITask>();
415                for (IUserSession session : sessions) {
416                        for (int i = 0; i < (session.size() - 1); i++) {
417                                // we prepared the task instances to refer to unique tasks, if
418                                // they are treated
419                                // as equal. Therefore, we just compare the identity of the
420                                // tasks of the task
421                                // instances
422                                if (session.get(i).getTask() == session.get(i + 1).getTask()) {
423                                        iteratedTasks.add(session.get(i).getTask());
424                                }
425                        }
426                }
427
428                return iteratedTasks;
429        }
430
431        /**
432         * <p>
433         * replaces all occurrences of all tasks provided in the set with iterations
434         * </p>
435         *
436         * @param iteratedTasks
437         *            the tasks to be replaced with iterations
438         * @param sessions
439         *            the sessions in which the tasks are to be replaced
440         * @param appData
441         *            the rule application data combining all data used for applying
442         *            this rule
443         */
444        private void replaceIterationsOf(Set<ITask> iteratedTasks,
445                        List<IUserSession> sessions, RuleApplicationData appData) {
446                Map<ITask, IIteration> iterations = new HashMap<ITask, IIteration>();
447                Map<IIteration, List<IIterationInstance>> iterationInstances = new HashMap<IIteration, List<IIterationInstance>>();
448
449                for (ITask iteratedTask : iteratedTasks) {
450                        IIteration iteration = taskFactory.createNewIteration();
451                        iterations.put(iteratedTask, iteration);
452                        iterationInstances.put(iteration,
453                                        new LinkedList<IIterationInstance>());
454                }
455
456                IIterationInstance iterationInstance;
457
458                for (IUserSession session : sessions) {
459                        int index = 0;
460                        iterationInstance = null;
461
462                        while (index < session.size()) {
463                                // we prepared the task instances to refer to unique tasks, if
464                                // they are treated
465                                // as equal. Therefore, we just compare the identity of the
466                                // tasks of the task
467                                // instances
468                                ITask currentTask = session.get(index).getTask();
469                                IIteration iteration = iterations.get(currentTask);
470                                if (iteration != null) {
471                                        if ((iterationInstance == null)
472                                                        || (iterationInstance.getTask() != iteration)) {
473                                                iterationInstance = taskFactory
474                                                                .createNewTaskInstance(iteration);
475                                                iterationInstances.get(iteration)
476                                                                .add(iterationInstance);
477                                                taskBuilder.addTaskInstance(session, index,
478                                                                iterationInstance);
479                                                index++;
480                                        }
481
482                                        taskBuilder.addChild(iterationInstance, session.get(index));
483                                        taskBuilder.removeTaskInstance(session, index);
484                                } else {
485                                        if (iterationInstance != null) {
486                                                iterationInstance = null;
487                                        }
488                                        index++;
489                                }
490                        }
491                }
492
493                for (Map.Entry<IIteration, List<IIterationInstance>> entry : iterationInstances
494                                .entrySet()) {
495                        harmonizeIterationInstancesModel(entry.getKey(), entry.getValue());
496                }
497        }
498
499       
500         ITask matchAsTask(RuleApplicationData appData,Match m) {
501               
502                ISequence sequence = taskFactory.createNewSequence();
503               
504                int[] first = m.getFirstSequence().getSequence();
505                int[] second = m.getSecondSequence().getSequence();
506                System.out.println("Number2Task size: " +appData.getNumber2Task().size());
507               
508                //Both sequences of a match are equally long
509                for(int i=0;i<m.getFirstSequence().size();i++) {
510                        System.out.println("First:" + first[i]);
511                        System.out.println("Second:" + second[i]);
512                        System.out.println();
513                        //Two gaps aligned to each other: Have not seen it happening so far, just to handle it
514                        if(first[i]==-1 && second[i]==-1) {
515                                //TODO: Do nothing?
516                        }
517                        //Both events are equal, we can simply add the task referring to the number
518                        else if(first[i]==second[i]) {
519                                taskBuilder.addChild(sequence, appData.getNumber2Task().get(first[i]));
520                        }
521                        //We have a gap in the first sequence, we need to add the task of the second sequence as optional
522                        else if(first[i]==-1 && second[i]!=-1) {
523                                IOptional optional = taskFactory.createNewOptional();
524                                taskBuilder.setMarkedTask(optional, appData.getNumber2Task().get(second[i]));
525                                taskBuilder.addChild(sequence,optional);
526                        }
527                        //We have a gap in the second sequence, we need to add the task of the first sequence as optional
528                        else if(first[i]!=-1 && second[i]==-1) {
529                                IOptional optional = taskFactory.createNewOptional();
530                                taskBuilder.setMarkedTask(optional, appData.getNumber2Task().get(first[i]));
531                                taskBuilder.addChild(sequence,optional);
532                        }
533                        //Both tasks are unequal, we need to insert a selection here
534                        else {
535                                ISelection selection = taskFactory.createNewSelection();
536                                taskBuilder.addChild(selection, appData.getNumber2Task().get(first[i]));
537                                taskBuilder.addChild(selection, appData.getNumber2Task().get(second[i]));
538                                taskBuilder.addChild(sequence,selection);
539                        }
540                }
541                        return sequence;
542                }
543       
544       
545        /**
546         * <p>
547         * TODO clarify why this is done
548         * </p>
549         */
550        private void harmonizeIterationInstancesModel(IIteration iteration,
551                        List<IIterationInstance> iterationInstances) {
552                List<ITask> iteratedTaskVariants = new LinkedList<ITask>();
553                TaskInstanceComparator comparator = preparationTaskHandlingStrategy
554                                .getTaskComparator();
555
556                // merge the lexically different variants of iterated task to a unique
557                // list
558                for (IIterationInstance iterationInstance : iterationInstances) {
559                        for (ITaskInstance executionVariant : iterationInstance) {
560                                ITask candidate = executionVariant.getTask();
561
562                                boolean found = false;
563                                for (ITask taskVariant : iteratedTaskVariants) {
564                                        if (comparator.areLexicallyEqual(taskVariant, candidate)) {
565                                                taskBuilder.setTask(executionVariant, taskVariant);
566                                                found = true;
567                                                break;
568                                        }
569                                }
570
571                                if (!found) {
572                                        iteratedTaskVariants.add(candidate);
573                                }
574                        }
575                }
576
577                // if there are more than one lexically different variant of iterated
578                // tasks, adapt the
579                // iteration model to be a selection of different variants. In this case
580                // also adapt
581                // the generated iteration instances to correctly contain selection
582                // instances. If there
583                // is only one variant of an iterated task, simply set this as the
584                // marked task of the
585                // iteration. In this case, the instances can be preserved as is
586                if (iteratedTaskVariants.size() > 1) {
587                        ISelection selection = taskFactory.createNewSelection();
588
589                        for (ITask variant : iteratedTaskVariants) {
590                                taskBuilder.addChild(selection, variant);
591                        }
592
593                        taskBuilder.setMarkedTask(iteration, selection);
594
595                        for (IIterationInstance instance : iterationInstances) {
596                                for (int i = 0; i < instance.size(); i++) {
597                                        ISelectionInstance selectionInstance = taskFactory
598                                                        .createNewTaskInstance(selection);
599                                        taskBuilder.setChild(selectionInstance, instance.get(i));
600                                        taskBuilder.setTaskInstance(instance, i, selectionInstance);
601                                }
602                        }
603                } else {
604                        taskBuilder.setMarkedTask(iteration, iteratedTaskVariants.get(0));
605                }
606        }
607
608        /**
609         * TODO go on commenting
610         *
611         * @param appData
612         *            the rule application data combining all data used for applying
613         *            this rule
614         */
615        private void detectAndReplaceTasks(RuleApplicationData appData) {
616                Console.traceln(Level.FINE, "detecting and replacing tasks");
617                appData.getStopWatch().start("detecting tasks");
618
619                //getSequencesOccuringMostOften(appData);
620
621                appData.getStopWatch().stop("detecting tasks");
622                appData.getStopWatch().start("replacing tasks");
623
624                replaceSequencesOccurringMostOften(appData);
625
626                appData.getStopWatch().stop("replacing tasks");
627               
628                //Console.traceln(Level.INFO, "detected and replaced "
629                //              + appData.getLastFoundTasks().size() + " tasks occuring "
630                //              + appData.getLastFoundTasks().getOccurrenceCount() + " times");
631        }
632
633       
634
635
636        /**
637         * @param appData
638         *            the rule application data combining all data used for applying
639         *            this rule
640         */
641        private void replaceSequencesOccurringMostOften(RuleApplicationData appData) {
642                appData.detectedAndReplacedTasks(false);
643
644       
645                        Console.traceln(Level.FINER, "replacing tasks occurrences");
646                        /*
647                        for (List<ITaskInstance> task : appData.getLastFoundTasks()) {
648                                ISequence sequence = taskFactory.createNewSequence();
649
650                                Console.traceln(Level.FINEST, "replacing " + sequence.getId()
651                                                + ": " + task);
652
653                                List<ISequenceInstance> sequenceInstances = replaceTaskOccurrences(
654                                                task, appData.getSessions(), sequence);
655
656                                harmonizeSequenceInstancesModel(sequence, sequenceInstances,
657                                                task.size());
658                                appData.detectedAndReplacedTasks(appData
659                                                .detectedAndReplacedTasks()
660                                                || (sequenceInstances.size() > 0));
661
662                                if (sequenceInstances.size() < appData.getLastFoundTasks()
663                                                .getOccurrenceCount()) {
664                                        Console.traceln(Level.FINE,
665                                                        sequence.getId()
666                                                                        + ": replaced task only "
667                                                                        + sequenceInstances.size()
668                                                                        + " times instead of expected "
669                                                                        + appData.getLastFoundTasks()
670                                                                                        .getOccurrenceCount());
671                                }
672                        }
673                        */
674        }
675
676
677        /**
678     *
679     */
680        private void harmonizeSequenceInstancesModel(ISequence sequence,
681                        List<ISequenceInstance> sequenceInstances, int sequenceLength) {
682                TaskInstanceComparator comparator = preparationTaskHandlingStrategy
683                                .getTaskComparator();
684
685                // ensure for each subtask that lexically different variants are
686                // preserved
687                for (int subTaskIndex = 0; subTaskIndex < sequenceLength; subTaskIndex++) {
688                        List<ITask> subTaskVariants = new LinkedList<ITask>();
689
690                        for (ISequenceInstance sequenceInstance : sequenceInstances) {
691                                ITask candidate = sequenceInstance.get(subTaskIndex).getTask();
692
693                                boolean found = false;
694
695                                for (int i = 0; i < subTaskVariants.size(); i++) {
696                                        if (comparator.areLexicallyEqual(subTaskVariants.get(i),
697                                                        candidate)) {
698                                                taskBuilder.setTask(sequenceInstance.get(subTaskIndex),
699                                                                subTaskVariants.get(i));
700
701                                                found = true;
702                                                break;
703                                        }
704                                }
705
706                                if (!found) {
707                                        subTaskVariants.add(candidate);
708                                }
709                        }
710
711                        // if there are more than one lexically different variant of the sub
712                        // task at
713                        // the considered position, adapt the sequence model at that
714                        // position to have
715                        // a selection of the different variants. In this case also adapt
716                        // the
717                        // generated sequence instances to correctly contain selection
718                        // instances. If
719                        // there is only one variant of sub tasks at the given position,
720                        // simply set
721                        // this variant as the sub task of the selection. In this case, the
722                        // instances
723                        // can be preserved as is
724                        if (subTaskVariants.size() > 1) {
725                                ISelection selection = taskFactory.createNewSelection();
726
727                                for (ITask variant : subTaskVariants) {
728                                        taskBuilder.addChild(selection, variant);
729                                }
730
731                                taskBuilder.addChild(sequence, selection);
732
733                                for (ISequenceInstance instance : sequenceInstances) {
734                                        ISelectionInstance selectionInstance = taskFactory
735                                                        .createNewTaskInstance(selection);
736                                        taskBuilder.setChild(selectionInstance,
737                                                        instance.get(subTaskIndex));
738                                        taskBuilder.setTaskInstance(instance, subTaskIndex,
739                                                        selectionInstance);
740                                }
741                        } else if (subTaskVariants.size() == 1) {
742                                taskBuilder.addChild(sequence, subTaskVariants.get(0));
743                        }
744                }
745        }
746
747        /**
748         * @param tree
749         */
750        private List<ISequenceInstance> replaceTaskOccurrences(
751                        List<ITaskInstance> task, List<IUserSession> sessions,
752                        ISequence temporalTaskModel) {
753                List<ISequenceInstance> sequenceInstances = new LinkedList<ISequenceInstance>();
754
755                for (IUserSession session : sessions) {
756                        int index = -1;
757
758                        do {
759                                index = getSubListIndex(session, task, ++index);
760
761                                if (index > -1) {
762                                        sequenceInstances.add(RuleUtils
763                                                        .createNewSubSequenceInRange(session, index, index
764                                                                        + task.size() - 1, temporalTaskModel,
765                                                                        taskFactory, taskBuilder));
766                                }
767                        } while (index > -1);
768                }
769
770                return sequenceInstances;
771        }
772
773        /**
774         * @param trie
775         * @param object
776         * @return
777         */
778        private int getSubListIndex(ITaskInstanceList list,
779                        List<ITaskInstance> subList, int startIndex) {
780                boolean matchFound;
781                int result = -1;
782
783                for (int i = startIndex; i <= list.size() - subList.size(); i++) {
784                        matchFound = true;
785
786                        for (int j = 0; j < subList.size(); j++) {
787                                // we prepared the task instances to refer to unique tasks, if
788                                // they are treated
789                                // as equal. Therefore, we just compare the identity of the
790                                // tasks of the task
791                                // instances
792                                if (list.get(i + j).getTask() != subList.get(j).getTask()) {
793                                        matchFound = false;
794                                        break;
795                                }
796                        }
797
798                        if (matchFound) {
799                                result = i;
800                                break;
801                        }
802                }
803
804                return result;
805        }
806
807
808        /**
809     *
810     */
811        private static class RuleApplicationData {
812
813               
814                private HashMap<Integer,ITask> number2task;
815               
816               
817                private ArrayList<NumberSequence> numberseqs;
818               
819                /**
820         *
821         */
822                private List<IUserSession> sessions;
823
824
825
826                /**
827         *
828         */
829                private boolean detectedAndReplacedTasks;
830
831                /**
832         *
833         */
834                private RuleApplicationResult result;
835
836                /**
837         *
838         */
839                private StopWatch stopWatch;
840
841                /**
842         *
843         */
844                private RuleApplicationData(List<IUserSession> sessions) {
845                        this.sessions = sessions;
846                        numberseqs = new ArrayList<NumberSequence>();
847                        number2task = new HashMap<Integer,ITask>();
848                        stopWatch= new StopWatch();
849                        result =  new RuleApplicationResult();
850                }
851
852                /**
853                 * @return the tree
854                 */
855                private List<IUserSession> getSessions() {
856                        return sessions;
857                }
858
859               
860                private ArrayList<NumberSequence> getNumberSequences() {
861                        return numberseqs;
862                }
863
864       
865
866                /**
867         *
868         */
869                private void detectedAndReplacedTasks(boolean detectedAndReplacedTasks) {
870                        this.detectedAndReplacedTasks = detectedAndReplacedTasks;
871                }
872
873                /**
874         *
875         */
876                private boolean detectedAndReplacedTasks() {
877                        return detectedAndReplacedTasks;
878                }
879
880                /**
881                 * @return the result
882                 */
883                private RuleApplicationResult getResult() {
884                        return result;
885                }
886
887                /**
888                 * @return the stopWatch
889                 */
890                private StopWatch getStopWatch() {
891                        return stopWatch;
892                }
893
894                private HashMap<Integer,ITask> getNumber2Task() {
895                        return number2task;
896                }
897
898        }
899
900       
901
902
903}
Note: See TracBrowser for help on using the repository browser.