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

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

Changed index updating procedure.

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