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

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

Small changes

File size: 27.7 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                                for(Iterator<MatchOccurence> it = matchseqs.get(i).getOccurences().iterator();it.hasNext();) {
265                                        MatchOccurence oc = it.next();
266                                        //RuleUtils.createNewSubSequenceInRange(oc.getSequenceId(), oc.getStartindex(), oc.getStartindex()+task
267                                        //      + task.size() - 1, temporalTaskModel,
268                                        //      taskFactory, taskBuilder));
269        }
270                                System.out.println(task);
271                                //matchseqs.get(i).getFirstSequence().printSequence();
272                                //matchseqs.get(i).getSecondSequence().printSequence();
273                                //System.out.println("Found pattern "
274                                //              + matchseqs.get(i).occurenceCount() + " times");
275                                System.out.println();
276                        }
277                }
278               
279
280                alignments = null;
281
282                do {
283                 
284                  appData.getStopWatch().start("whole loop"); //
285                  detectAndReplaceIterations(appData);
286                 
287                  appData.getStopWatch().start("task replacement"); //
288                  //detectAndReplaceTasks(appData); //
289                  appData.getStopWatch().stop("task replacement"); //
290                  appData.getStopWatch().stop("whole loop");
291                 
292                  appData.getStopWatch().dumpStatistics(System.out); //
293                  appData.getStopWatch().reset();
294                 
295                  } while (appData.detectedAndReplacedTasks());
296                 
297
298                Console.println("created "
299                                + appData.getResult().getNewlyCreatedTasks().size()
300                                + " new tasks and "
301                                + appData.getResult().getNewlyCreatedTaskInstances().size()
302                                + " appropriate instances\n");
303
304                if ((appData.getResult().getNewlyCreatedTasks().size() > 0)
305                                || (appData.getResult().getNewlyCreatedTaskInstances().size() > 0)) {
306                        appData.getResult().setRuleApplicationStatus(
307                                        RuleApplicationStatus.FINISHED);
308                }
309
310                return appData.getResult();
311        }
312
313       
314       
315        /**
316         * <p>
317         * harmonizes the event task instances by unifying tasks. This is done, as
318         * initially the event tasks being equal with respect to the considered task
319         * equality are distinct objects. The comparison of these distinct objects
320         * is more time consuming than comparing the object references.
321         * </p>
322         *
323         * @param appData
324         *            the rule application data combining all data used for applying
325         *            this rule
326         * @return Returns the unique tasks symbol map
327         */
328        private SymbolMap<ITaskInstance, ITask> harmonizeEventTaskInstancesModel(
329                        RuleApplicationData appData) {
330                Console.traceln(Level.INFO,
331                                "harmonizing task model of event task instances");
332                appData.getStopWatch().start("harmonizing event tasks");
333
334                SymbolMap<ITaskInstance, ITask> uniqueTasks = preparationTaskHandlingStrategy
335                                .createSymbolMap();
336                TaskInstanceComparator comparator = preparationTaskHandlingStrategy
337                                .getTaskComparator();
338
339                int unifiedTasks = 0;
340                ITask task;
341                List<IUserSession> sessions = appData.getSessions();
342                int sessionNo = 0;
343                for (IUserSession session : sessions) {
344                        Console.traceln(Level.FINE, "handling " + (++sessionNo) + ". "
345                                        + session);
346                        NumberSequence templist = new NumberSequence(session.size());
347
348                        for (int i = 0; i < session.size(); i++) {
349                                ITaskInstance taskInstance = session.get(i);
350                                task = uniqueTasks.getValue(taskInstance);
351
352                                if (task == null) {
353                                        uniqueTasks.addSymbol(taskInstance, taskInstance.getTask());
354                                        templist.getSequence()[i] = taskInstance.getTask().getId();
355               
356                                } else {
357                                        taskBuilder.setTask(taskInstance, task);
358                                        templist.getSequence()[i] = task.getId();
359                                        unifiedTasks++;
360                                }
361                                appData.getNumber2Task().put(templist.getSequence()[i], taskInstance.getTask());
362                        }
363                        templist.setId(appData.getNumberSequences().size());
364                        appData.getNumberSequences().add(templist);
365                        comparator.clearBuffers();
366                }
367
368                appData.getStopWatch().stop("harmonizing event tasks");
369                Console.traceln(Level.INFO, "harmonized " + unifiedTasks
370                                + " task occurrences (still " + uniqueTasks.size()
371                                + " different tasks)");
372
373                appData.getStopWatch().dumpStatistics(System.out);
374                appData.getStopWatch().reset();
375                return uniqueTasks;
376        }
377
378        /**
379         * <p>
380         * searches for direct iterations of single tasks in all sequences and
381         * replaces them with {@link IIteration}s, respectively appropriate
382         * instances. Also all single occurrences of a task that is iterated
383         * somewhen are replaced with iterations to have again an efficient way for
384         * task comparisons.
385         * </p>
386         *
387         * @param appData
388         *            the rule application data combining all data used for applying
389         *            this rule
390         */
391        private void detectAndReplaceIterations(RuleApplicationData appData) {
392                Console.traceln(Level.FINE, "detecting iterations");
393                appData.getStopWatch().start("detecting iterations");
394
395                List<IUserSession> sessions = appData.getSessions();
396
397                Set<ITask> iteratedTasks = searchIteratedTasks(sessions);
398
399                if (iteratedTasks.size() > 0) {
400                        replaceIterationsOf(iteratedTasks, sessions, appData);
401                }
402
403                appData.getStopWatch().stop("detecting iterations");
404                Console.traceln(Level.INFO, "replaced " + iteratedTasks.size()
405                                + " iterated tasks");
406        }
407
408        /**
409         * <p>
410         * searches the provided sessions for task iterations. If a task is
411         * iterated, it is added to the returned set.
412         * </p>
413         *
414         * @param the
415         *            session to search for iterations in
416         *
417         * @return a set of tasks being iterated somewhere
418         */
419        private Set<ITask> searchIteratedTasks(List<IUserSession> sessions) {
420                Set<ITask> iteratedTasks = new HashSet<ITask>();
421                for (IUserSession session : sessions) {
422                        for (int i = 0; i < (session.size() - 1); i++) {
423                                // we prepared the task instances to refer to unique tasks, if
424                                // they are treated
425                                // as equal. Therefore, we just compare the identity of the
426                                // tasks of the task
427                                // instances
428                                if (session.get(i).getTask() == session.get(i + 1).getTask()) {
429                                        iteratedTasks.add(session.get(i).getTask());
430                                }
431                        }
432                }
433
434                return iteratedTasks;
435        }
436
437        /**
438         * <p>
439         * replaces all occurrences of all tasks provided in the set with iterations
440         * </p>
441         *
442         * @param iteratedTasks
443         *            the tasks to be replaced with iterations
444         * @param sessions
445         *            the sessions in which the tasks are to be replaced
446         * @param appData
447         *            the rule application data combining all data used for applying
448         *            this rule
449         */
450        private void replaceIterationsOf(Set<ITask> iteratedTasks,
451                        List<IUserSession> sessions, RuleApplicationData appData) {
452                Map<ITask, IIteration> iterations = new HashMap<ITask, IIteration>();
453                Map<IIteration, List<IIterationInstance>> iterationInstances = new HashMap<IIteration, List<IIterationInstance>>();
454
455                for (ITask iteratedTask : iteratedTasks) {
456                        IIteration iteration = taskFactory.createNewIteration();
457                        iterations.put(iteratedTask, iteration);
458                        iterationInstances.put(iteration,
459                                        new LinkedList<IIterationInstance>());
460                }
461
462                IIterationInstance iterationInstance;
463
464                for (IUserSession session : sessions) {
465                        int index = 0;
466                        iterationInstance = null;
467
468                        while (index < session.size()) {
469                                // we prepared the task instances to refer to unique tasks, if
470                                // they are treated
471                                // as equal. Therefore, we just compare the identity of the
472                                // tasks of the task
473                                // instances
474                                ITask currentTask = session.get(index).getTask();
475                                IIteration iteration = iterations.get(currentTask);
476                                if (iteration != null) {
477                                        if ((iterationInstance == null)
478                                                        || (iterationInstance.getTask() != iteration)) {
479                                                iterationInstance = taskFactory
480                                                                .createNewTaskInstance(iteration);
481                                                iterationInstances.get(iteration)
482                                                                .add(iterationInstance);
483                                                taskBuilder.addTaskInstance(session, index,
484                                                                iterationInstance);
485                                                index++;
486                                        }
487
488                                        taskBuilder.addChild(iterationInstance, session.get(index));
489                                        taskBuilder.removeTaskInstance(session, index);
490                                } else {
491                                        if (iterationInstance != null) {
492                                                iterationInstance = null;
493                                        }
494                                        index++;
495                                }
496                        }
497                }
498
499                for (Map.Entry<IIteration, List<IIterationInstance>> entry : iterationInstances
500                                .entrySet()) {
501                        harmonizeIterationInstancesModel(entry.getKey(), entry.getValue());
502                }
503        }
504
505       
506         ITask matchAsTask(RuleApplicationData appData,Match m) {
507               
508                ISequence sequence = taskFactory.createNewSequence();
509               
510                int[] first = m.getFirstSequence().getSequence();
511                int[] second = m.getSecondSequence().getSequence();
512                System.out.println("Number2Task size: " +appData.getNumber2Task().size());
513               
514                //Both sequences of a match are equally long
515                for(int i=0;i<m.getFirstSequence().size();i++) {
516                        System.out.println("First:" + first[i]);
517                        System.out.println("Second:" + second[i]);
518                        System.out.println();
519                        //Two gaps aligned to each other: Have not seen it happening so far, just to handle it
520                        if(first[i]==-1 && second[i]==-1) {
521                                //TODO: Do nothing?
522                        }
523                        //Both events are equal, we can simply add the task referring to the number
524                        else if(first[i]==second[i]) {
525                                taskBuilder.addChild(sequence, appData.getNumber2Task().get(first[i]));
526                        }
527                        //We have a gap in the first sequence, we need to add the task of the second sequence as optional
528                        else if(first[i]==-1 && second[i]!=-1) {
529                                IOptional optional = taskFactory.createNewOptional();
530                                taskBuilder.setMarkedTask(optional, appData.getNumber2Task().get(second[i]));
531                                taskBuilder.addChild(sequence,optional);
532                        }
533                        //We have a gap in the second sequence, we need to add the task of the first sequence as optional
534                        else if(first[i]!=-1 && second[i]==-1) {
535                                IOptional optional = taskFactory.createNewOptional();
536                                taskBuilder.setMarkedTask(optional, appData.getNumber2Task().get(first[i]));
537                                taskBuilder.addChild(sequence,optional);
538                        }
539                        //Both tasks are unequal, we need to insert a selection here
540                        else {
541                                ISelection selection = taskFactory.createNewSelection();
542                                taskBuilder.addChild(selection, appData.getNumber2Task().get(first[i]));
543                                taskBuilder.addChild(selection, appData.getNumber2Task().get(second[i]));
544                                taskBuilder.addChild(sequence,selection);
545                        }
546                }
547                        return sequence;
548                }
549       
550       
551        /**
552         * <p>
553         * TODO clarify why this is done
554         * </p>
555         */
556        private void harmonizeIterationInstancesModel(IIteration iteration,
557                        List<IIterationInstance> iterationInstances) {
558                List<ITask> iteratedTaskVariants = new LinkedList<ITask>();
559                TaskInstanceComparator comparator = preparationTaskHandlingStrategy
560                                .getTaskComparator();
561
562                // merge the lexically different variants of iterated task to a unique
563                // list
564                for (IIterationInstance iterationInstance : iterationInstances) {
565                        for (ITaskInstance executionVariant : iterationInstance) {
566                                ITask candidate = executionVariant.getTask();
567
568                                boolean found = false;
569                                for (ITask taskVariant : iteratedTaskVariants) {
570                                        if (comparator.areLexicallyEqual(taskVariant, candidate)) {
571                                                taskBuilder.setTask(executionVariant, taskVariant);
572                                                found = true;
573                                                break;
574                                        }
575                                }
576
577                                if (!found) {
578                                        iteratedTaskVariants.add(candidate);
579                                }
580                        }
581                }
582
583                // if there are more than one lexically different variant of iterated
584                // tasks, adapt the
585                // iteration model to be a selection of different variants. In this case
586                // also adapt
587                // the generated iteration instances to correctly contain selection
588                // instances. If there
589                // is only one variant of an iterated task, simply set this as the
590                // marked task of the
591                // iteration. In this case, the instances can be preserved as is
592                if (iteratedTaskVariants.size() > 1) {
593                        ISelection selection = taskFactory.createNewSelection();
594
595                        for (ITask variant : iteratedTaskVariants) {
596                                taskBuilder.addChild(selection, variant);
597                        }
598
599                        taskBuilder.setMarkedTask(iteration, selection);
600
601                        for (IIterationInstance instance : iterationInstances) {
602                                for (int i = 0; i < instance.size(); i++) {
603                                        ISelectionInstance selectionInstance = taskFactory
604                                                        .createNewTaskInstance(selection);
605                                        taskBuilder.setChild(selectionInstance, instance.get(i));
606                                        taskBuilder.setTaskInstance(instance, i, selectionInstance);
607                                }
608                        }
609                } else {
610                        taskBuilder.setMarkedTask(iteration, iteratedTaskVariants.get(0));
611                }
612        }
613
614        /**
615         * TODO go on commenting
616         *
617         * @param appData
618         *            the rule application data combining all data used for applying
619         *            this rule
620         */
621        private void detectAndReplaceTasks(RuleApplicationData appData) {
622                Console.traceln(Level.FINE, "detecting and replacing tasks");
623                appData.getStopWatch().start("detecting tasks");
624
625                //getSequencesOccuringMostOften(appData);
626
627                appData.getStopWatch().stop("detecting tasks");
628                appData.getStopWatch().start("replacing tasks");
629
630                replaceSequencesOccurringMostOften(appData);
631
632                appData.getStopWatch().stop("replacing tasks");
633               
634                //Console.traceln(Level.INFO, "detected and replaced "
635                //              + appData.getLastFoundTasks().size() + " tasks occuring "
636                //              + appData.getLastFoundTasks().getOccurrenceCount() + " times");
637        }
638
639       
640
641
642        /**
643         * @param appData
644         *            the rule application data combining all data used for applying
645         *            this rule
646         */
647        private void replaceSequencesOccurringMostOften(RuleApplicationData appData) {
648                appData.detectedAndReplacedTasks(false);
649
650       
651                        Console.traceln(Level.FINER, "replacing tasks occurrences");
652                        /*
653                        for (List<ITaskInstance> task : appData.getLastFoundTasks()) {
654                                ISequence sequence = taskFactory.createNewSequence();
655
656                                Console.traceln(Level.FINEST, "replacing " + sequence.getId()
657                                                + ": " + task);
658
659                                List<ISequenceInstance> sequenceInstances = replaceTaskOccurrences(
660                                                task, appData.getSessions(), sequence);
661
662                                harmonizeSequenceInstancesModel(sequence, sequenceInstances,
663                                                task.size());
664                                appData.detectedAndReplacedTasks(appData
665                                                .detectedAndReplacedTasks()
666                                                || (sequenceInstances.size() > 0));
667
668                                if (sequenceInstances.size() < appData.getLastFoundTasks()
669                                                .getOccurrenceCount()) {
670                                        Console.traceln(Level.FINE,
671                                                        sequence.getId()
672                                                                        + ": replaced task only "
673                                                                        + sequenceInstances.size()
674                                                                        + " times instead of expected "
675                                                                        + appData.getLastFoundTasks()
676                                                                                        .getOccurrenceCount());
677                                }
678                        }
679                        */
680        }
681
682
683        /**
684     *
685     */
686        private void harmonizeSequenceInstancesModel(ISequence sequence,
687                        List<ISequenceInstance> sequenceInstances, int sequenceLength) {
688                TaskInstanceComparator comparator = preparationTaskHandlingStrategy
689                                .getTaskComparator();
690
691                // ensure for each subtask that lexically different variants are
692                // preserved
693                for (int subTaskIndex = 0; subTaskIndex < sequenceLength; subTaskIndex++) {
694                        List<ITask> subTaskVariants = new LinkedList<ITask>();
695
696                        for (ISequenceInstance sequenceInstance : sequenceInstances) {
697                                ITask candidate = sequenceInstance.get(subTaskIndex).getTask();
698
699                                boolean found = false;
700
701                                for (int i = 0; i < subTaskVariants.size(); i++) {
702                                        if (comparator.areLexicallyEqual(subTaskVariants.get(i),
703                                                        candidate)) {
704                                                taskBuilder.setTask(sequenceInstance.get(subTaskIndex),
705                                                                subTaskVariants.get(i));
706
707                                                found = true;
708                                                break;
709                                        }
710                                }
711
712                                if (!found) {
713                                        subTaskVariants.add(candidate);
714                                }
715                        }
716
717                        // if there are more than one lexically different variant of the sub
718                        // task at
719                        // the considered position, adapt the sequence model at that
720                        // position to have
721                        // a selection of the different variants. In this case also adapt
722                        // the
723                        // generated sequence instances to correctly contain selection
724                        // instances. If
725                        // there is only one variant of sub tasks at the given position,
726                        // simply set
727                        // this variant as the sub task of the selection. In this case, the
728                        // instances
729                        // can be preserved as is
730                        if (subTaskVariants.size() > 1) {
731                                ISelection selection = taskFactory.createNewSelection();
732
733                                for (ITask variant : subTaskVariants) {
734                                        taskBuilder.addChild(selection, variant);
735                                }
736
737                                taskBuilder.addChild(sequence, selection);
738
739                                for (ISequenceInstance instance : sequenceInstances) {
740                                        ISelectionInstance selectionInstance = taskFactory
741                                                        .createNewTaskInstance(selection);
742                                        taskBuilder.setChild(selectionInstance,
743                                                        instance.get(subTaskIndex));
744                                        taskBuilder.setTaskInstance(instance, subTaskIndex,
745                                                        selectionInstance);
746                                }
747                        } else if (subTaskVariants.size() == 1) {
748                                taskBuilder.addChild(sequence, subTaskVariants.get(0));
749                        }
750                }
751        }
752
753        /**
754         * @param tree
755         */
756        private List<ISequenceInstance> replaceTaskOccurrences(
757                        List<ITaskInstance> task, List<IUserSession> sessions,
758                        ISequence temporalTaskModel) {
759                List<ISequenceInstance> sequenceInstances = new LinkedList<ISequenceInstance>();
760
761                for (IUserSession session : sessions) {
762                        int index = -1;
763
764                        do {
765                                index = getSubListIndex(session, task, ++index);
766
767                                if (index > -1) {
768                                        sequenceInstances.add(RuleUtils
769                                                        .createNewSubSequenceInRange(session, index, index
770                                                                        + task.size() - 1, temporalTaskModel,
771                                                                        taskFactory, taskBuilder));
772                                }
773                        } while (index > -1);
774                }
775
776                return sequenceInstances;
777        }
778
779        /**
780         * @param trie
781         * @param object
782         * @return
783         */
784        private int getSubListIndex(ITaskInstanceList list,
785                        List<ITaskInstance> subList, int startIndex) {
786                boolean matchFound;
787                int result = -1;
788
789                for (int i = startIndex; i <= list.size() - subList.size(); i++) {
790                        matchFound = true;
791
792                        for (int j = 0; j < subList.size(); j++) {
793                                // we prepared the task instances to refer to unique tasks, if
794                                // they are treated
795                                // as equal. Therefore, we just compare the identity of the
796                                // tasks of the task
797                                // instances
798                                if (list.get(i + j).getTask() != subList.get(j).getTask()) {
799                                        matchFound = false;
800                                        break;
801                                }
802                        }
803
804                        if (matchFound) {
805                                result = i;
806                                break;
807                        }
808                }
809
810                return result;
811        }
812
813
814        /**
815     *
816     */
817        private static class RuleApplicationData {
818
819               
820                private HashMap<Integer,ITask> number2task;
821               
822               
823                private ArrayList<NumberSequence> numberseqs;
824               
825                /**
826         *
827         */
828                private List<IUserSession> sessions;
829
830
831
832                /**
833         *
834         */
835                private boolean detectedAndReplacedTasks;
836
837                /**
838         *
839         */
840                private RuleApplicationResult result;
841
842                /**
843         *
844         */
845                private StopWatch stopWatch;
846
847                /**
848         *
849         */
850                private RuleApplicationData(List<IUserSession> sessions) {
851                        this.sessions = sessions;
852                        numberseqs = new ArrayList<NumberSequence>();
853                        number2task = new HashMap<Integer,ITask>();
854                        stopWatch= new StopWatch();
855                        result =  new RuleApplicationResult();
856                }
857
858                /**
859                 * @return the tree
860                 */
861                private List<IUserSession> getSessions() {
862                        return sessions;
863                }
864
865               
866                private ArrayList<NumberSequence> getNumberSequences() {
867                        return numberseqs;
868                }
869
870       
871
872                /**
873         *
874         */
875                private void detectedAndReplacedTasks(boolean detectedAndReplacedTasks) {
876                        this.detectedAndReplacedTasks = detectedAndReplacedTasks;
877                }
878
879                /**
880         *
881         */
882                private boolean detectedAndReplacedTasks() {
883                        return detectedAndReplacedTasks;
884                }
885
886                /**
887                 * @return the result
888                 */
889                private RuleApplicationResult getResult() {
890                        return result;
891                }
892
893                /**
894                 * @return the stopWatch
895                 */
896                private StopWatch getStopWatch() {
897                        return stopWatch;
898                }
899
900                private HashMap<Integer,ITask> getNumber2Task() {
901                        return number2task;
902                }
903
904        }
905
906       
907
908
909}
Note: See TracBrowser for help on using the repository browser.