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

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

Cleanup up the debubbing output

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