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

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

Cleaning up

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