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

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

Adding tests to some classes.

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