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

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

Finally i can replace.

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