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

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

Fixed first iteration of sequence detection and replacement

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                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                        NumberSequence templist = new NumberSequence(session.size());
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                                System.out.println("First: " + first[i] + " Second: " + second[i]);
432                                ISelection selection = taskFactory.createNewSelection();
433                                appData.uniqueTasks
434                                                .addSymbol(
435                                                                taskFactory.createNewTaskInstance(selection),
436                                                                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                if (matchseqs.size() > 0) {
565                        appData.detectedAndReplacedTasks = true;
566                }
567                Console.traceln(Level.FINEST,
568                                "retrieving significant sequence pieces:  100%");
569                Console.traceln(Level.INFO, "searching for patterns occuring most");
570
571                // search each match in every other sequence
572                for (Iterator<Match> it = matchseqs.iterator(); it.hasNext();) {
573                        Match pattern = it.next();
574
575                        // Skip sequences with more 0 events (scrolls) than other events.
576                        // Both of the pattern sequences are equally long, so the zero
577                        // counts just need to be smaller than the length of one sequence
578                        if (pattern.getFirstSequence().eventCount(0)
579                                        + pattern.getSecondSequence().eventCount(0) + 1 > pattern
580                                        .getFirstSequence().size())
581                                continue;
582
583                        for (int j = 0; j < appData.getNumberSequences().size(); j++) {
584                                LinkedList<Integer> startpositions = appData
585                                                .getNumberSequences().get(j).containsPattern(pattern);
586                                if (startpositions.size() > 0) {
587                                        for (Iterator<Integer> jt = startpositions.iterator(); jt
588                                                        .hasNext();) {
589                                                int start = jt.next();
590                                                pattern.addOccurence(new MatchOccurence(start, start
591                                                                + pattern.size(), j));
592                                        }
593
594                                }
595                        }
596                }
597
598                Console.traceln(Level.INFO, "sorting results");
599                // Sort results to get the most occurring results
600                Comparator<Match> comparator = new Comparator<Match>() {
601                        public int compare(Match m1, Match m2) {
602                                return m2.occurenceCount() - m1.occurenceCount();
603
604                        }
605                };
606                Collections.sort(matchseqs, comparator);
607                appData.getStopWatch().stop("detecting tasks");
608
609                appData.getStopWatch().start("replacing tasks");
610                HashMap<Integer, List<MatchOccurence>> replacedOccurences = new HashMap<Integer, List<MatchOccurence>>();
611                // Replace matches in the sessions
612                for (int i = 0; i < matchseqs.size(); i++) {
613                        // Every pattern consists of 2 sequences, therefore the minimum
614                        // occurrences here is 2.
615                        // We just need the sequences also occurring in other sequences as
616                        // well
617                        if (matchseqs.get(i).occurenceCount() > 2) {
618
619                                ISequence task = matchAsSequence(appData, matchseqs.get(i));
620                                invalidOccurence: for (Iterator<MatchOccurence> it = matchseqs
621                                                .get(i).getOccurences().iterator(); it.hasNext();) {
622                                        MatchOccurence oc = it.next();
623
624                                        /*
625                                         * System.out.println("Trying to replace sequence: ");
626                                         * matchseqs.get(i).getFirstSequence().printSequence();
627                                         * matchseqs.get(i).getSecondSequence().printSequence();
628                                         * System.out.println(" in session number: " +
629                                         * (oc.getSequenceId() + 1) + " at position " +
630                                         * (oc.getStartindex()) + "-" + oc.getEndindex());
631                                         * System.out.println();
632                                         */
633
634                                        // System.out.println("Printing session: ");
635                                        // for (int j = 0; j <
636                                        // appData.getSessions().get(oc.getSequenceId()).size();
637                                        // j++) {
638                                        // System.out.println(j + ": "
639                                        // + appData.getSessions().get(oc.getSequenceId()).get(j));
640                                        // }
641
642                                        // Check if nothing has been replaced in the sequence we
643                                        // want to replace
644                                        if (replacedOccurences.get(oc.getSequenceId()) == null) {
645                                                replacedOccurences.put(oc.getSequenceId(),
646                                                                new LinkedList<MatchOccurence>());
647                                        } else {
648                                                // check if we have any replaced occurence with indexes
649                                                // smaller than ours. If so, we need to adjust our start
650                                                // and endpoints
651                                                // of the replacement.
652                                                // Also do a check if we have replaced this specific
653                                                // MatchOccurence in this sequence already. Jump to the
654                                                // next occurence if this is the case.
655                                                // This is no more neccessary once the matches are
656                                                // harmonized.
657                                                for (Iterator<MatchOccurence> jt = replacedOccurences
658                                                                .get(oc.getSequenceId()).iterator(); jt
659                                                                .hasNext();) {
660                                                        MatchOccurence tmpOC = jt.next();
661
662                                                        if (oc.getStartindex() >= tmpOC.getStartindex()
663                                                                        && oc.getStartindex() <= tmpOC
664                                                                                        .getEndindex()) {
665                                                                continue invalidOccurence;
666                                                        }
667                                                        if (oc.getEndindex() >= tmpOC.getStartindex()) {
668                                                                continue invalidOccurence;
669
670                                                        } else if (oc.getStartindex() > tmpOC.getEndindex()) {
671                                                                int diff = tmpOC.getEndindex()
672                                                                                - tmpOC.getStartindex();
673                                                                // Just to be sure.
674                                                                if (diff > 0) {
675                                                                        oc.setStartindex(oc.getStartindex() - diff
676                                                                                        + 1);
677                                                                        oc.setEndindex(oc.getEndindex() - diff + 1);
678                                                                } else {
679                                                                        Console.traceln(Level.WARNING,
680                                                                                        "End index of a Match before start. This should never happen");
681                                                                }
682                                                        }
683                                                }
684                                        }
685                                        ISequenceInstance sequenceInstances = RuleUtils
686                                                        .createNewSubSequenceInRange(appData.getSessions()
687                                                                        .get(oc.getSequenceId()), oc
688                                                                        .getStartindex(), oc.getEndindex(), task,
689                                                                        taskFactory, taskBuilder);
690                                        // Adjust the length of the match regarding to the length of
691                                        // instance. (OptionalInstances may be shorter)
692                                        oc.setEndindex(oc.getStartindex()
693                                                        + sequenceInstances.size()
694                                                        - RuleUtils.missedOptionals);
695                                        replacedOccurences.get(oc.getSequenceId()).add(oc);
696                                }
697                        }
698                }
699
700                alignments = null;
701                matchseqs = null;
702                appData.getStopWatch().stop("replacing tasks");
703        }
704
705        /**
706     *
707     */
708        private void harmonizeSequenceInstancesModel(ISequence sequence,
709                        List<ISequenceInstance> sequenceInstances, int sequenceLength) {
710                TaskInstanceComparator comparator = preparationTaskHandlingStrategy
711                                .getTaskComparator();
712
713                // ensure for each subtask that lexically different variants are
714                // preserved
715                for (int subTaskIndex = 0; subTaskIndex < sequenceLength; subTaskIndex++) {
716                        List<ITask> subTaskVariants = new LinkedList<ITask>();
717
718                        for (ISequenceInstance sequenceInstance : sequenceInstances) {
719                                ITask candidate = sequenceInstance.get(subTaskIndex).getTask();
720
721                                boolean found = false;
722
723                                for (int i = 0; i < subTaskVariants.size(); i++) {
724                                        if (comparator.areLexicallyEqual(subTaskVariants.get(i),
725                                                        candidate)) {
726                                                taskBuilder.setTask(sequenceInstance.get(subTaskIndex),
727                                                                subTaskVariants.get(i));
728
729                                                found = true;
730                                                break;
731                                        }
732                                }
733
734                                if (!found) {
735                                        subTaskVariants.add(candidate);
736                                }
737                        }
738
739                        // if there are more than one lexically different variant of the sub
740                        // task at
741                        // the considered position, adapt the sequence model at that
742                        // position to have
743                        // a selection of the different variants. In this case also adapt
744                        // the
745                        // generated sequence instances to correctly contain selection
746                        // instances. If
747                        // there is only one variant of sub tasks at the given position,
748                        // simply set
749                        // this variant as the sub task of the selection. In this case, the
750                        // instances
751                        // can be preserved as is
752                        if (subTaskVariants.size() > 1) {
753                                ISelection selection = taskFactory.createNewSelection();
754
755                                for (ITask variant : subTaskVariants) {
756                                        taskBuilder.addChild(selection, variant);
757                                }
758
759                                taskBuilder.addChild(sequence, selection);
760
761                                for (ISequenceInstance instance : sequenceInstances) {
762                                        ISelectionInstance selectionInstance = taskFactory
763                                                        .createNewTaskInstance(selection);
764                                        taskBuilder.setChild(selectionInstance,
765                                                        instance.get(subTaskIndex));
766                                        taskBuilder.setTaskInstance(instance, subTaskIndex,
767                                                        selectionInstance);
768                                }
769                        } else if (subTaskVariants.size() == 1) {
770                                taskBuilder.addChild(sequence, subTaskVariants.get(0));
771                        }
772                }
773        }
774
775        /**
776     *
777     */
778        private static class RuleApplicationData {
779
780                private HashMap<Integer, ITask> number2task;
781
782                private SymbolMap<ITaskInstance, ITask> uniqueTasks;
783
784                private ArrayList<NumberSequence> numberseqs;
785
786                /**
787         *
788         */
789                private List<IUserSession> sessions;
790
791                /**
792         *
793         */
794                private boolean detectedAndReplacedTasks;
795
796                /**
797         *
798         */
799                private RuleApplicationResult result;
800
801                /**
802         *
803         */
804                private StopWatch stopWatch;
805
806                /**
807         *
808         */
809                private RuleApplicationData(List<IUserSession> sessions) {
810                        this.sessions = sessions;
811                        numberseqs = new ArrayList<NumberSequence>();
812                        number2task = new HashMap<Integer, ITask>();
813                        stopWatch = new StopWatch();
814                        result = new RuleApplicationResult();
815                }
816
817                /**
818                 * @return the tree
819                 */
820                private List<IUserSession> getSessions() {
821                        return sessions;
822                }
823
824                private SymbolMap<ITaskInstance, ITask> getUniqueTasks() {
825                        return uniqueTasks;
826                }
827
828                // private void setUniqueTasks(SymbolMap<ITaskInstance, ITask> ut) {
829                // this.uniqueTasks = ut;
830                // }
831
832                private void setNumberSequences(ArrayList<NumberSequence> numberseqs) {
833                        this.numberseqs = numberseqs;
834                }
835
836                private ArrayList<NumberSequence> getNumberSequences() {
837                        return numberseqs;
838                }
839
840                /**
841         *
842         */
843                private boolean detectedAndReplacedTasks() {
844                        return detectedAndReplacedTasks;
845                }
846
847                /**
848                 * @return the result
849                 */
850                private RuleApplicationResult getResult() {
851                        return result;
852                }
853
854                /**
855                 * @return the stopWatch
856                 */
857                private StopWatch getStopWatch() {
858                        return stopWatch;
859                }
860
861                private HashMap<Integer, ITask> getNumber2Task() {
862                        return number2task;
863                }
864
865        }
866
867}
Note: See TracBrowser for help on using the repository browser.