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

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

Trying to fix bug in ObjectDistanceSUbstitutionMatrix

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