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

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

Fixed model replacment, index updates still to go.

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