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

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

Debugging containsPattern

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