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

Last change on this file since 1668 was 1668, 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                        IIteration iteration = taskFactory.createNewIteration();
333                        iterations.put(iteratedTask, iteration);
334                        iterationInstances.put(iteration,
335                                        new LinkedList<IIterationInstance>());
336                }
337
338                IIterationInstance iterationInstance;
339
340                for (IUserSession session : sessions) {
341                        int index = 0;
342                        iterationInstance = null;
343
344                        while (index < session.size()) {
345                                // we prepared the task instances to refer to unique tasks, if
346                                // they are treated
347                                // as equal. Therefore, we just compare the identity of the
348                                // tasks of the task
349                                // instances
350                                ITask currentTask = session.get(index).getTask();
351                                IIteration iteration = iterations.get(currentTask);
352                                if (iteration != null) {
353                                        if ((iterationInstance == null)
354                                                        || (iterationInstance.getTask() != iteration)) {
355                                                iterationInstance = taskFactory
356                                                                .createNewTaskInstance(iteration);
357                                                iterationInstances.get(iteration)
358                                                                .add(iterationInstance);
359                                                taskBuilder.addTaskInstance(session, index,
360                                                                iterationInstance);
361                                                index++;
362                                        }
363
364                                        taskBuilder.addChild(iterationInstance, session.get(index));
365                                        taskBuilder.removeTaskInstance(session, index);
366                                } else {
367                                        if (iterationInstance != null) {
368                                                iterationInstance = null;
369                                        }
370                                        index++;
371                                }
372                        }
373                }
374
375                for (Map.Entry<IIteration, List<IIterationInstance>> entry : iterationInstances
376                                .entrySet()) {
377                        harmonizeIterationInstancesModel(entry.getKey(), entry.getValue());
378                }
379        }
380
381        ISequence matchAsSequence(RuleApplicationData appData, Match m) {
382
383                ISequence sequence = taskFactory.createNewSequence();
384
385                int[] first = m.getFirstSequence().getSequence();
386                int[] second = m.getSecondSequence().getSequence();
387
388                // Both sequences of a match are equally long
389                for (int i = 0; i < m.getFirstSequence().size(); i++) {
390
391                        // Two gaps aligned to each other: Have not seen it happening so
392                        // far, just to handle it
393                        if (first[i] == -1 && second[i] == -1) {
394                                // TODO: Do nothing?
395                        }
396                        // Both events are equal, we can simply add the task referring to
397                        // the number
398                        else if (first[i] == second[i]) {
399                                taskBuilder.addChild(sequence,
400                                                appData.getNumber2Task().get(first[i]));
401                        }
402                        // We have a gap in the first sequence, we need to add the task of
403                        // the second sequence as optional
404                        else if (first[i] == -1 && second[i] != -1) {
405                                IOptional optional = taskFactory.createNewOptional();
406                                taskBuilder.setMarkedTask(optional, appData.getNumber2Task()
407                                                .get(second[i]));
408                                taskBuilder.addChild(sequence, optional);
409                        }
410                        // We have a gap in the second sequence, we need to add the task of
411                        // the first sequence as optional
412                        else if (first[i] != -1 && second[i] == -1) {
413                                IOptional optional = taskFactory.createNewOptional();
414                                taskBuilder.setMarkedTask(optional, appData.getNumber2Task()
415                                                .get(first[i]));
416                                taskBuilder.addChild(sequence, optional);
417                        }
418                        // Both tasks are unequal, we need to insert a selection here
419                        else {
420                                ISelection selection = taskFactory.createNewSelection();
421                                taskBuilder.addChild(selection,
422                                                appData.getNumber2Task().get(first[i]));
423                                taskBuilder.addChild(selection,
424                                                appData.getNumber2Task().get(second[i]));
425                                taskBuilder.addChild(sequence, selection);
426                        }
427                }
428
429                // TODO: Debug output
430                /*
431                 * for (int i =0;i<sequence.getChildren().size();i++) {
432                 * System.out.println(sequence.getChildren().get(i));
433                 *
434                 * if(sequence.getChildren().get(i).getType() == "selection") { for(int
435                 * j=0; j< ((ISelection)
436                 * sequence.getChildren().get(i)).getChildren().size();j++) {
437                 * System.out.println("\t" +((ISelection)
438                 * sequence.getChildren().get(i)).getChildren().get(j)); } } }
439                 */
440                return sequence;
441        }
442
443        /**
444         * <p>
445         * TODO clarify why this is done
446         * </p>
447         */
448        private void harmonizeIterationInstancesModel(IIteration iteration,
449                        List<IIterationInstance> iterationInstances) {
450                List<ITask> iteratedTaskVariants = new LinkedList<ITask>();
451                TaskInstanceComparator comparator = preparationTaskHandlingStrategy
452                                .getTaskComparator();
453
454                // merge the lexically different variants of iterated task to a unique
455                // list
456                for (IIterationInstance iterationInstance : iterationInstances) {
457                        for (ITaskInstance executionVariant : iterationInstance) {
458                                ITask candidate = executionVariant.getTask();
459
460                                boolean found = false;
461                                for (ITask taskVariant : iteratedTaskVariants) {
462                                        if (comparator.areLexicallyEqual(taskVariant, candidate)) {
463                                                taskBuilder.setTask(executionVariant, taskVariant);
464                                                found = true;
465                                                break;
466                                        }
467                                }
468
469                                if (!found) {
470                                        iteratedTaskVariants.add(candidate);
471                                }
472                        }
473                }
474
475                // if there are more than one lexically different variant of iterated
476                // tasks, adapt the
477                // iteration model to be a selection of different variants. In this case
478                // also adapt
479                // the generated iteration instances to correctly contain selection
480                // instances. If there
481                // is only one variant of an iterated task, simply set this as the
482                // marked task of the
483                // iteration. In this case, the instances can be preserved as is
484                if (iteratedTaskVariants.size() > 1) {
485                        ISelection selection = taskFactory.createNewSelection();
486
487                        for (ITask variant : iteratedTaskVariants) {
488                                taskBuilder.addChild(selection, variant);
489                        }
490
491                        taskBuilder.setMarkedTask(iteration, selection);
492
493                        for (IIterationInstance instance : iterationInstances) {
494                                for (int i = 0; i < instance.size(); i++) {
495                                        ISelectionInstance selectionInstance = taskFactory
496                                                        .createNewTaskInstance(selection);
497                                        taskBuilder.setChild(selectionInstance, instance.get(i));
498                                        taskBuilder.setTaskInstance(instance, i, selectionInstance);
499                                }
500                        }
501                } else {
502                        taskBuilder.setMarkedTask(iteration, iteratedTaskVariants.get(0));
503                }
504        }
505
506        /**
507         * TODO go on commenting
508         *
509         * @param appData
510         *            the rule application data combining all data used for applying
511         *            this rule
512         */
513        private void detectAndReplaceTasks(RuleApplicationData appData) {
514                Console.traceln(Level.FINE, "detecting and replacing tasks");
515                appData.getStopWatch().start("detecting tasks");
516
517               
518                // Generate a substitution matrix between all occurring events.
519                                Console.traceln(Level.INFO, "generating substitution matrix");
520                                ObjectDistanceSubstitionMatrix submat = new ObjectDistanceSubstitionMatrix(
521                                                appData.getUniqueTasks(), 6, -3);
522                                submat.generate();
523
524                                // Generate pairwise alignments
525                                Console.traceln(Level.INFO, "generating pairwise alignments");
526                                LinkedList<Match> matchseqs = new LinkedList<Match>();
527                                PairwiseAlignmentStorage alignments = PairwiseAlignmentGenerator
528                                                .generate(appData.getNumberSequences(), submat, 9);
529
530                                // Retrieve all matches reached a specific threshold
531                                Console.traceln(Level.INFO, "retrieving significant sequence pieces");
532                                for (int i = 0; i < appData.getNumberSequences().size(); i++) {
533                                        Console.traceln(
534                                                        Level.FINEST,
535                                                        "retrieving significant sequence pieces:  "
536                                                                        + Math.round((float) i
537                                                                                        / (float) appData.getNumberSequences()
538                                                                                                        .size() * 100) + "%");
539                                        for (int j = 0; j < appData.getNumberSequences().size(); j++) {
540                                                if (i != j) {
541                                                        matchseqs.addAll(alignments.get(i, j).getMatches());
542                                                }
543                                        }
544                                }
545                                Console.traceln(Level.FINEST,
546                                                "retrieving significant sequence pieces:  100%");
547                                Console.traceln(Level.INFO, "searching for patterns occuring most");
548
549                                // search each match in every other sequence
550                                for (Iterator<Match> it = matchseqs.iterator(); it.hasNext();) {
551                                        Match pattern = it.next();
552
553                                        // Skip sequences with more 0 events (scrolls) than other events.
554                                        // Both of the pattern sequences are equally long, so the zero
555                                        // counts just need to be smaller than the length of one sequence
556                                        if (pattern.getFirstSequence().eventCount(0)
557                                                        + pattern.getSecondSequence().eventCount(0) + 1 > pattern
558                                                        .getFirstSequence().size())
559                                                continue;
560
561                                        for (int j = 0; j < appData.getNumberSequences().size(); j++) {
562                                                LinkedList<Integer> startpositions = appData
563                                                                .getNumberSequences().get(j).containsPattern(pattern);
564                                                if (startpositions.size() > 0) {
565                                                        for (Iterator<Integer> jt = startpositions.iterator(); jt
566                                                                        .hasNext();) {
567                                                                int start = jt.next();
568                                                                pattern.addOccurence(new MatchOccurence(start, start
569                                                                                + pattern.size(), j));
570                                                        }
571
572                                                }
573                                        }
574                                }
575
576                                Console.traceln(Level.INFO, "sorting results");
577                                // Sort results to get the most occurring results
578                                Comparator<Match> comparator = new Comparator<Match>() {
579                                        public int compare(Match m1, Match m2) {
580                                                return m2.occurenceCount() - m1.occurenceCount();
581
582                                        }
583                                };
584                                Collections.sort(matchseqs, comparator);
585                                appData.getStopWatch().stop("detecting tasks");
586                               
587                                appData.getStopWatch().start("replacing tasks");
588                                HashMap<Integer, List<MatchOccurence>> replacedOccurences = new HashMap<Integer, List<MatchOccurence>>();
589                                // Replace matches in the sessions
590                                for (int i = 0; i < matchseqs.size(); i++) {
591                                        // Every pattern consists of 2 sequences, therefore the minimum
592                                        // occurrences here is 2.
593                                        // We just need the sequences also occurring in other sequences as
594                                        // well
595                                        if (matchseqs.get(i).occurenceCount() > 2) {
596
597                                                ISequence task = matchAsSequence(appData, matchseqs.get(i));
598                                                invalidOccurence: for (Iterator<MatchOccurence> it = matchseqs
599                                                                .get(i).getOccurences().iterator(); it.hasNext();) {
600                                                        MatchOccurence oc = it.next();
601                                                        /*
602                                                        System.out.println("Trying to replace sequence: ");
603                                                        matchseqs.get(i).getFirstSequence().printSequence();
604                                                        matchseqs.get(i).getSecondSequence().printSequence();
605                                                        System.out.println(" in session number: "
606                                                                        + (oc.getSequenceId() + 1)
607                                                                        + " at position "
608                                                                        + (oc.getStartindex())
609                                                                        + "-"
610                                                                        + oc.getEndindex());
611                                                        System.out.println();
612                                                        */
613                                                       
614                                                        // System.out.println("Printing session: ");
615                                                        //for (int j = 0; j < sessions.get(oc.getSequenceId()).size(); j++) {
616                                                        //      System.out.println(j + ": "
617                                                        //                      + sessions.get(oc.getSequenceId()).get(j));
618                                                        //}
619
620                                                        // Check if nothing has been replaced in the sequence we
621                                                        // want to replace
622                                                        if (replacedOccurences.get(oc.getSequenceId()) == null) {
623                                                                replacedOccurences.put(oc.getSequenceId(),
624                                                                                new LinkedList<MatchOccurence>());
625                                                        } else {
626                                                                // check if we have any replaced occurence with indexes
627                                                                // smaller than ours. If so, we need to adjust our start
628                                                                // and endpoints
629                                                                // of the replacement.
630                                                                // Also do a check if we have replaced this specific
631                                                                // MatchOccurence in this sequence already. Jump to the
632                                                                // next occurence if this is the case.
633                                                                // This is no more neccessary once the matches are
634                                                                // harmonized.
635                                                                for (Iterator<MatchOccurence> jt = replacedOccurences
636                                                                                .get(oc.getSequenceId()).iterator(); jt
637                                                                                .hasNext();) {
638                                                                        MatchOccurence tmpOC = jt.next();
639                                                                       
640                                                                        if (oc.getStartindex() >= tmpOC.getStartindex() && oc.getStartindex()<=tmpOC.getEndindex()) {
641                                                                                continue invalidOccurence;
642                                                                        }
643                                                                        if (oc.getEndindex()>=tmpOC.getStartindex()) {
644                                                                                continue invalidOccurence;
645                                                                               
646                                                                        }
647                                                                        else if (oc.getStartindex()>tmpOC.getEndindex()) {
648                                                                                int diff = tmpOC.getEndindex()
649                                                                                                - tmpOC.getStartindex();
650                                                                                // Just to be sure.
651                                                                                if (diff > 0) {
652                                                                                        oc.setStartindex(oc.getStartindex() - diff+1);
653                                                                                        oc.setEndindex(oc.getEndindex() - diff+1);
654                                                                                } else {
655                                                                                        Console.traceln(Level.WARNING,
656                                                                                                        "End index of a Match before start. This should never happen");
657                                                                                }
658                                                                        }
659                                                                }
660                                                        }
661                                                        ISequenceInstance sequenceInstances = RuleUtils
662                                                                        .createNewSubSequenceInRange(
663                                                                                        appData.getSessions().get(oc.getSequenceId()),
664                                                                                        oc.getStartindex(), oc.getEndindex(), task,
665                                                                                        taskFactory, taskBuilder);
666                                                        // Adjust the length of the match regarding to the length of
667                                                        // instance. (OptionalInstances may be shorter)
668                                                        oc.setEndindex(oc.getStartindex()
669                                                                        + sequenceInstances.size()
670                                                                        - RuleUtils.missedOptionals);
671                                                        replacedOccurences.get(oc.getSequenceId()).add(oc);
672                                                }
673                                        }
674                                }
675
676                                alignments = null;
677                appData.getStopWatch().stop("replacing tasks");
678        }
679
680
681        /**
682     *
683     */
684        private void harmonizeSequenceInstancesModel(ISequence sequence,
685                        List<ISequenceInstance> sequenceInstances, int sequenceLength) {
686                TaskInstanceComparator comparator = preparationTaskHandlingStrategy
687                                .getTaskComparator();
688
689                // ensure for each subtask that lexically different variants are
690                // preserved
691                for (int subTaskIndex = 0; subTaskIndex < sequenceLength; subTaskIndex++) {
692                        List<ITask> subTaskVariants = new LinkedList<ITask>();
693
694                        for (ISequenceInstance sequenceInstance : sequenceInstances) {
695                                ITask candidate = sequenceInstance.get(subTaskIndex).getTask();
696
697                                boolean found = false;
698
699                                for (int i = 0; i < subTaskVariants.size(); i++) {
700                                        if (comparator.areLexicallyEqual(subTaskVariants.get(i),
701                                                        candidate)) {
702                                                taskBuilder.setTask(sequenceInstance.get(subTaskIndex),
703                                                                subTaskVariants.get(i));
704
705                                                found = true;
706                                                break;
707                                        }
708                                }
709
710                                if (!found) {
711                                        subTaskVariants.add(candidate);
712                                }
713                        }
714
715                        // if there are more than one lexically different variant of the sub
716                        // task at
717                        // the considered position, adapt the sequence model at that
718                        // position to have
719                        // a selection of the different variants. In this case also adapt
720                        // the
721                        // generated sequence instances to correctly contain selection
722                        // instances. If
723                        // there is only one variant of sub tasks at the given position,
724                        // simply set
725                        // this variant as the sub task of the selection. In this case, the
726                        // instances
727                        // can be preserved as is
728                        if (subTaskVariants.size() > 1) {
729                                ISelection selection = taskFactory.createNewSelection();
730
731                                for (ITask variant : subTaskVariants) {
732                                        taskBuilder.addChild(selection, variant);
733                                }
734
735                                taskBuilder.addChild(sequence, selection);
736
737                                for (ISequenceInstance instance : sequenceInstances) {
738                                        ISelectionInstance selectionInstance = taskFactory
739                                                        .createNewTaskInstance(selection);
740                                        taskBuilder.setChild(selectionInstance,
741                                                        instance.get(subTaskIndex));
742                                        taskBuilder.setTaskInstance(instance, subTaskIndex,
743                                                        selectionInstance);
744                                }
745                        } else if (subTaskVariants.size() == 1) {
746                                taskBuilder.addChild(sequence, subTaskVariants.get(0));
747                        }
748                }
749        }
750
751       
752        /**
753     *
754     */
755        private static class RuleApplicationData {
756
757                private HashMap<Integer, ITask> number2task;
758               
759                private SymbolMap<ITaskInstance, ITask> uniqueTasks;
760
761                private ArrayList<NumberSequence> numberseqs;
762
763                /**
764         *
765         */
766                private List<IUserSession> sessions;
767
768                /**
769         *
770         */
771                private boolean detectedAndReplacedTasks;
772
773                /**
774         *
775         */
776                private RuleApplicationResult result;
777
778                /**
779         *
780         */
781                private StopWatch stopWatch;
782
783                /**
784         *
785         */
786                private RuleApplicationData(List<IUserSession> sessions) {
787                        this.sessions = sessions;
788                        numberseqs = new ArrayList<NumberSequence>();
789                        number2task = new HashMap<Integer, ITask>();
790                        stopWatch = new StopWatch();
791                        result = new RuleApplicationResult();
792                }
793
794                /**
795                 * @return the tree
796                 */
797                private List<IUserSession> getSessions() {
798                        return sessions;
799                }
800
801                private SymbolMap<ITaskInstance, ITask> getUniqueTasks() {
802                        return uniqueTasks;
803                }
804               
805                private void setUniqueTasks(SymbolMap<ITaskInstance, ITask> ut) {
806                        this.uniqueTasks = ut;
807                }
808               
809                private ArrayList<NumberSequence> getNumberSequences() {
810                        return numberseqs;
811                }
812
813
814                /**
815         *
816         */
817                private boolean detectedAndReplacedTasks() {
818                        return detectedAndReplacedTasks;
819                }
820
821                /**
822                 * @return the result
823                 */
824                private RuleApplicationResult getResult() {
825                        return result;
826                }
827
828                /**
829                 * @return the stopWatch
830                 */
831                private StopWatch getStopWatch() {
832                        return stopWatch;
833                }
834
835                private HashMap<Integer, ITask> getNumber2Task() {
836                        return number2task;
837                }
838
839        }
840
841}
Note: See TracBrowser for help on using the repository browser.