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

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

Fixed Loop \o/

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