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

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

About to fix bug in containsPattern

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