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

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

Fixed replacment loop, but it's still endless

File size: 27.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.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               
150                appData.detectedAndReplacedTasks = false;
151                do {
152                        harmonizeEventTaskInstancesModel(appData);
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                                System.out.print(taskInstance.getTask().getId() + " ");
188                                templist.getSequence()[j] = taskInstance.getTask().getId();
189                                appData.getNumber2Task().put(templist.getSequence()[j],
190                                                taskInstance.getTask());
191                        }
192                        System.out.println();
193                        // Each NumberSequence is identified by its id, beginning to count
194                        // at zero
195                        templist.setId(i);
196                        result.add(templist);
197                }
198                return result;
199        }
200
201        /**
202         * <p>
203         * harmonizes the event task instances by unifying tasks. This is done, as
204         * initially the event tasks being equal with respect to the considered task
205         * equality are distinct objects. The comparison of these distinct objects
206         * is more time consuming than comparing the object references.
207         * </p>
208         *
209         * @param appData
210         *            the rule application data combining all data used for applying
211         *            this rule
212         * @return Returns the unique tasks symbol map
213         */
214        private void harmonizeEventTaskInstancesModel(RuleApplicationData appData) {
215                Console.traceln(Level.INFO,
216                                "harmonizing task model of event task instances");
217                appData.getStopWatch().start("harmonizing event tasks");
218
219                appData.uniqueTasks = preparationTaskHandlingStrategy.createSymbolMap();
220
221                TaskInstanceComparator comparator = preparationTaskHandlingStrategy
222                                .getTaskComparator();
223
224                int unifiedTasks = 0;
225                ITask task;
226                List<IUserSession> sessions = appData.getSessions();
227                for (int j = 0; j < sessions.size(); j++) {
228                        IUserSession session = sessions.get(j);
229
230                        for (int i = 0; i < session.size(); i++) {
231                                ITaskInstance taskInstance = session.get(i);
232                                task = appData.getUniqueTasks().getValue(taskInstance);
233
234                                if (task == null) {
235                                        appData.getUniqueTasks().addSymbol(taskInstance,
236                                                        taskInstance.getTask());
237                                } else {
238                                        taskBuilder.setTask(taskInstance, task);
239                                        unifiedTasks++;
240                                }
241                        }
242                        comparator.clearBuffers();
243                }
244
245                appData.getStopWatch().stop("harmonizing event tasks");
246                Console.traceln(Level.INFO, "harmonized " + unifiedTasks
247                                + " task occurrences (still " + appData.getUniqueTasks().size()
248                                + " different tasks)");
249
250                appData.getStopWatch().dumpStatistics(System.out);
251                appData.getStopWatch().reset();
252        }
253
254        /**
255         * <p>
256         * searches for direct iterations of single tasks in all sequences and
257         * replaces them with {@link IIteration}s, respectively appropriate
258         * instances. Also all single occurrences of a task that is iterated
259         * somewhen are replaced with iterations to have again an efficient way for
260         * task comparisons.
261         * </p>
262         *
263         * @param appData
264         *            the rule application data combining all data used for applying
265         *            this rule
266         */
267        private void detectAndReplaceIterations(RuleApplicationData appData) {
268                Console.traceln(Level.FINE, "detecting iterations");
269                appData.getStopWatch().start("detecting iterations");
270
271                List<IUserSession> sessions = appData.getSessions();
272
273                Set<ITask> iteratedTasks = searchIteratedTasks(sessions);
274
275                if (iteratedTasks.size() > 0) {
276                        replaceIterationsOf(iteratedTasks, sessions, appData);
277                }
278
279                appData.getStopWatch().stop("detecting iterations");
280                Console.traceln(Level.INFO, "replaced " + iteratedTasks.size()
281                                + " iterated tasks");
282        }
283
284        /**
285         * <p>
286         * searches the provided sessions for task iterations. If a task is
287         * iterated, it is added to the returned set.
288         * </p>
289         *
290         * @param the
291         *            session to search for iterations in
292         *
293         * @return a set of tasks being iterated somewhere
294         */
295        private Set<ITask> searchIteratedTasks(List<IUserSession> sessions) {
296                Set<ITask> iteratedTasks = new HashSet<ITask>();
297                for (IUserSession session : sessions) {
298                        for (int i = 0; i < (session.size() - 1); i++) {
299                                // we prepared the task instances to refer to unique tasks, if
300                                // they are treated
301                                // as equal. Therefore, we just compare the identity of the
302                                // tasks of the task
303                                // instances
304                                if (session.get(i).getTask() == session.get(i + 1).getTask()) {
305                                        iteratedTasks.add(session.get(i).getTask());
306                                }
307                        }
308                }
309
310                return iteratedTasks;
311        }
312
313        /**
314         * <p>
315         * replaces all occurrences of all tasks provided in the set with iterations
316         * </p>
317         *
318         * @param iteratedTasks
319         *            the tasks to be replaced with iterations
320         * @param sessions
321         *            the sessions in which the tasks are to be replaced
322         * @param appData
323         *            the rule application data combining all data used for applying
324         *            this rule
325         */
326        private void replaceIterationsOf(Set<ITask> iteratedTasks,
327                        List<IUserSession> sessions, RuleApplicationData appData) {
328                Map<ITask, IIteration> iterations = new HashMap<ITask, IIteration>();
329                Map<IIteration, List<IIterationInstance>> iterationInstances = new HashMap<IIteration, List<IIterationInstance>>();
330
331                for (ITask iteratedTask : iteratedTasks) {
332
333                        // TODO: Check if this is correct
334                        IIteration iteration = taskFactory.createNewIteration();
335                        appData.getUniqueTasks().addSymbol(
336                                        taskFactory.createNewTaskInstance(iteration), iteration);
337                        appData.getNumber2Task().put(iteration.getId(), iteration);
338                        iterations.put(iteratedTask, iteration);
339                        iterationInstances.put(iteration,
340                                        new LinkedList<IIterationInstance>());
341                }
342
343                IIterationInstance iterationInstance;
344
345                for (IUserSession session : sessions) {
346                        int index = 0;
347                        iterationInstance = null;
348
349                        while (index < session.size()) {
350                                // we prepared the task instances to refer to unique tasks, if
351                                // they are treated
352                                // as equal. Therefore, we just compare the identity of the
353                                // tasks of the task
354                                // instances
355                                ITask currentTask = session.get(index).getTask();
356                                IIteration iteration = iterations.get(currentTask);
357                                if (iteration != null) {
358                                        if ((iterationInstance == null)
359                                                        || (iterationInstance.getTask() != iteration)) {
360                                                iterationInstance = taskFactory
361                                                                .createNewTaskInstance(iteration);
362                                                iterationInstances.get(iteration)
363                                                                .add(iterationInstance);
364                                                taskBuilder.addTaskInstance(session, index,
365                                                                iterationInstance);
366                                                index++;
367                                        }
368
369                                        taskBuilder.addChild(iterationInstance, session.get(index));
370                                        taskBuilder.removeTaskInstance(session, index);
371                                } else {
372                                        if (iterationInstance != null) {
373                                                iterationInstance = null;
374                                        }
375                                        index++;
376                                }
377                        }
378                }
379
380                for (Map.Entry<IIteration, List<IIterationInstance>> entry : iterationInstances
381                                .entrySet()) {
382                        harmonizeIterationInstancesModel(entry.getKey(), entry.getValue());
383                }
384        }
385
386        ISequence matchAsSequence(RuleApplicationData appData, Match m) {
387
388                ISequence sequence = taskFactory.createNewSequence();
389
390                int[] first = m.getFirstSequence().getSequence();
391                int[] second = m.getSecondSequence().getSequence();
392
393                // Both sequences of a match are equally long
394                for (int i = 0; i < m.getFirstSequence().size(); i++) {
395
396                        // Two gaps aligned to each other: Have not seen it happening so
397                        // far, just to handle it
398                        if (first[i] == -1 && second[i] == -1) {
399                                // TODO: Do nothing?
400                        }
401                        // Both events are equal, we can simply add the task referring to
402                        // the number
403                        else if (first[i] == second[i]) {
404                                taskBuilder.addChild(sequence,
405                                                appData.getNumber2Task().get(first[i]));
406                        }
407                        // We have a gap in the first sequence, we need to add the task of
408                        // the second sequence as optional
409                        else if (first[i] == -1 && second[i] != -1) {
410                                IOptional optional = taskFactory.createNewOptional();
411                                appData.uniqueTasks.addSymbol(
412                                                taskFactory.createNewTaskInstance(optional), optional);
413                                appData.number2task.put(optional.getId(), optional);
414                                taskBuilder.setMarkedTask(optional, appData.getNumber2Task()
415                                                .get(second[i]));
416                                taskBuilder.addChild(sequence, optional);
417                        }
418                        // We have a gap in the second sequence, we need to add the task of
419                        // the first sequence as optional
420                        else if (first[i] != -1 && second[i] == -1) {
421                                IOptional optional = taskFactory.createNewOptional();
422                                appData.uniqueTasks.addSymbol(
423                                                taskFactory.createNewTaskInstance(optional), optional);
424                                appData.number2task.put(optional.getId(), optional);
425                                taskBuilder.setMarkedTask(optional, appData.getNumber2Task()
426                                                .get(first[i]));
427                                taskBuilder.addChild(sequence, optional);
428                        }
429                        // Both tasks are not equal, we need to insert a selection here
430                        else {
431                                //TODO: Debug output
432                                //System.out.println("First: " + first[i] + " Second: " + second[i]);
433                                ISelection selection = taskFactory.createNewSelection();
434                                ISelectionInstance temp = taskFactory.createNewTaskInstance(selection);
435                                appData.uniqueTasks
436                                                .addSymbol(temp,selection);
437                                appData.number2task.put(selection.getId(), selection);
438                                taskBuilder.addChild(selection,
439                                                appData.getNumber2Task().get(first[i]));
440                                taskBuilder.addChild(selection,
441                                                appData.getNumber2Task().get(second[i]));
442                                taskBuilder.addChild(sequence, selection);
443                        }
444                }
445
446                // TODO: Debug output
447                /*
448                 * for (int i =0;i<sequence.getChildren().size();i++) {
449                 * System.out.println(sequence.getChildren().get(i));
450                 *
451                 * if(sequence.getChildren().get(i).getType() == "selection") { for(int
452                 * j=0; j< ((ISelection)
453                 * sequence.getChildren().get(i)).getChildren().size();j++) {
454                 * System.out.println("\t" +((ISelection)
455                 * sequence.getChildren().get(i)).getChildren().get(j)); } } }
456                 */
457                return sequence;
458        }
459
460        /**
461         * <p>
462         * TODO clarify why this is done
463         * </p>
464         */
465        private void harmonizeIterationInstancesModel(IIteration iteration,
466                        List<IIterationInstance> iterationInstances) {
467                List<ITask> iteratedTaskVariants = new LinkedList<ITask>();
468                TaskInstanceComparator comparator = preparationTaskHandlingStrategy
469                                .getTaskComparator();
470
471                // merge the lexically different variants of iterated task to a unique
472                // list
473                for (IIterationInstance iterationInstance : iterationInstances) {
474                        for (ITaskInstance executionVariant : iterationInstance) {
475                                ITask candidate = executionVariant.getTask();
476
477                                boolean found = false;
478                                for (ITask taskVariant : iteratedTaskVariants) {
479                                        if (comparator.areLexicallyEqual(taskVariant, candidate)) {
480                                                taskBuilder.setTask(executionVariant, taskVariant);
481                                                found = true;
482                                                break;
483                                        }
484                                }
485
486                                if (!found) {
487                                        iteratedTaskVariants.add(candidate);
488                                }
489                        }
490                }
491
492                // if there are more than one lexically different variant of iterated
493                // tasks, adapt the
494                // iteration model to be a selection of different variants. In this case
495                // also adapt
496                // the generated iteration instances to correctly contain selection
497                // instances. If there
498                // is only one variant of an iterated task, simply set this as the
499                // marked task of the
500                // iteration. In this case, the instances can be preserved as is
501                if (iteratedTaskVariants.size() > 1) {
502                        ISelection selection = taskFactory.createNewSelection();
503
504                        for (ITask variant : iteratedTaskVariants) {
505                                taskBuilder.addChild(selection, variant);
506                        }
507
508                        taskBuilder.setMarkedTask(iteration, selection);
509
510                        for (IIterationInstance instance : iterationInstances) {
511                                for (int i = 0; i < instance.size(); i++) {
512                                        ISelectionInstance selectionInstance = taskFactory
513                                                        .createNewTaskInstance(selection);
514                                        taskBuilder.setChild(selectionInstance, instance.get(i));
515                                        taskBuilder.setTaskInstance(instance, i, selectionInstance);
516                                }
517                        }
518                } else {
519                        taskBuilder.setMarkedTask(iteration, iteratedTaskVariants.get(0));
520                }
521        }
522
523        /**
524         * TODO go on commenting
525         *
526         * @param appData
527         *            the rule application data combining all data used for applying
528         *            this rule
529         */
530        private void detectAndReplaceTasks(RuleApplicationData appData) {
531                Console.traceln(Level.FINE, "detecting and replacing tasks");
532                appData.getStopWatch().start("detecting tasks");
533
534                // Create NumberSequences
535                appData.setNumberSequences(this.createNumberSequences(appData));
536
537                // Generate a substitution matrix between all occurring events.
538                Console.traceln(Level.INFO, "generating substitution matrix");
539                ObjectDistanceSubstitionMatrix submat = new ObjectDistanceSubstitionMatrix(
540                                appData.getUniqueTasks(), 6, -3);
541                submat.generate();
542
543                // Generate pairwise alignments
544                Console.traceln(Level.INFO, "generating pairwise alignments");
545                LinkedList<Match> matchseqs = new LinkedList<Match>();
546                PairwiseAlignmentStorage alignments = PairwiseAlignmentGenerator
547                                .generate(appData.getNumberSequences(), submat, 9);
548
549                // Retrieve all matches reached a specific threshold
550                Console.traceln(Level.INFO, "retrieving significant sequence pieces");
551                for (int i = 0; i < appData.getNumberSequences().size(); i++) {
552                        Console.traceln(
553                                        Level.FINEST,
554                                        "retrieving significant sequence pieces:  "
555                                                        + Math.round((float) i
556                                                                        / (float) appData.getNumberSequences()
557                                                                                        .size() * 100) + "%");
558                        for (int j = 0; j < appData.getNumberSequences().size(); j++) {
559                                if (i != j) {
560                                        matchseqs.addAll(alignments.get(i, j).getMatches());
561                                }
562                        }
563                }
564               
565                Console.traceln(Level.FINEST,
566                                "retrieving significant sequence pieces:  100%");
567                Console.traceln(Level.INFO, "searching for patterns occuring most");
568
569                // search each match in every other sequence
570                for (Iterator<Match> it = matchseqs.iterator(); it.hasNext();) {
571                        Match pattern = it.next();
572
573                        // Skip sequences with more 0 events (scrolls) than other events.
574                        // Both of the pattern sequences are equally long, so the zero
575                        // counts just need to be smaller than the length of one sequence
576                        if (pattern.getFirstSequence().eventCount(0)
577                                        + pattern.getSecondSequence().eventCount(0) + 1 > pattern
578                                        .getFirstSequence().size())
579                                continue;
580
581                        for (int j = 0; j < appData.getNumberSequences().size(); j++) {
582                                LinkedList<Integer> startpositions = appData
583                                                .getNumberSequences().get(j).containsPattern(pattern);
584                                if (startpositions.size() > 0) {
585                                        for (Iterator<Integer> jt = startpositions.iterator(); jt
586                                                        .hasNext();) {
587                                                int start = jt.next();
588                                                pattern.addOccurence(new MatchOccurence(start, start
589                                                                + pattern.size(), j));
590                                        }
591
592                                }
593                        }
594                }
595
596                Console.traceln(Level.INFO, "sorting results");
597                // Sort results to get the most occurring results
598                Comparator<Match> comparator = new Comparator<Match>() {
599                        public int compare(Match m1, Match m2) {
600                                return m2.occurenceCount() - m1.occurenceCount();
601
602                        }
603                };
604                Collections.sort(matchseqs, comparator);
605                appData.getStopWatch().stop("detecting tasks");
606
607                appData.getStopWatch().start("replacing tasks");
608                HashMap<Integer, List<MatchOccurence>> replacedOccurences = new HashMap<Integer, List<MatchOccurence>>();
609                // Replace matches in the sessions
610                for (int i = 0; i < matchseqs.size(); i++) {
611                        // Every pattern consists of 2 sequences, therefore the minimum
612                        // occurrences here is 2.
613                        // We just need the sequences also occurring in other sequences as
614                        // well
615                        if (matchseqs.get(i).occurenceCount() > 2) {
616                               
617                                appData.detectedAndReplacedTasks = true;
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.