diff options
Diffstat (limited to 'Solvers/VIATRA-Solver')
38 files changed, 2171 insertions, 501 deletions
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationMethodProvider.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationMethodProvider.xtend index e45ec1c8..6fbbc779 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationMethodProvider.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationMethodProvider.xtend | |||
@@ -27,6 +27,7 @@ import java.util.Set | |||
27 | import org.eclipse.viatra.query.runtime.api.IPatternMatch | 27 | import org.eclipse.viatra.query.runtime.api.IPatternMatch |
28 | import org.eclipse.viatra.query.runtime.api.IQuerySpecification | 28 | import org.eclipse.viatra.query.runtime.api.IQuerySpecification |
29 | import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher | 29 | import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher |
30 | import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint | ||
30 | import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery | 31 | import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery |
31 | import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRule | 32 | import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRule |
32 | import org.eclipse.xtend.lib.annotations.Data | 33 | import org.eclipse.xtend.lib.annotations.Data |
@@ -83,6 +84,9 @@ class ModelGenerationStatistics { | |||
83 | 84 | ||
84 | Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> invalidWF | 85 | Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> invalidWF |
85 | 86 | ||
87 | Map<PConstraint, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> mustUnitPropagationPreconditions | ||
88 | Map<PConstraint, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> currentUnitPropagationPreconditions | ||
89 | |||
86 | Map<String, ModalPatternQueries> modalRelationQueries | 90 | Map<String, ModalPatternQueries> modalRelationQueries |
87 | 91 | ||
88 | Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> allPatterns | 92 | Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> allPatterns |
@@ -120,12 +124,13 @@ class ModelGenerationMethodProvider { | |||
120 | workspace, typeInferenceMethod, scopePropagatorStrategy, relationConstraints, hints, writeFiles) | 124 | workspace, typeInferenceMethod, scopePropagatorStrategy, relationConstraints, hints, writeFiles) |
121 | val scopePropagator = createScopePropagator(scopePropagatorStrategy, emptySolution, hints, queries, statistics) | 125 | val scopePropagator = createScopePropagator(scopePropagatorStrategy, emptySolution, hints, queries, statistics) |
122 | scopePropagator.propagateAllScopeConstraints | 126 | scopePropagator.propagateAllScopeConstraints |
123 | val objectRefinementRules = refinementRuleProvider.createObjectRefinementRules(queries, scopePropagator, | 127 | val objectRefinementRules = refinementRuleProvider.createObjectRefinementRules(logicProblem, emptySolution, |
124 | nameNewElements, statistics) | 128 | queries, scopePropagator, nameNewElements, statistics) |
125 | val relationRefinementRules = refinementRuleProvider.createRelationRefinementRules(queries, scopePropagator, | 129 | val relationRefinementRules = refinementRuleProvider.createRelationRefinementRules(queries, scopePropagator, |
126 | statistics) | 130 | statistics) |
127 | 131 | ||
128 | val unfinishedMultiplicities = goalConstraintProvider.getUnfinishedMultiplicityQueries(queries) | 132 | val unfinishedMultiplicities = goalConstraintProvider.getUnfinishedMultiplicityQueries(logicProblem,queries) |
133 | |||
129 | val unfinishedWF = queries.getUnfinishedWFQueries.values | 134 | val unfinishedWF = queries.getUnfinishedWFQueries.values |
130 | 135 | ||
131 | val modalRelationQueriesBuilder = ImmutableMap.builder | 136 | val modalRelationQueriesBuilder = ImmutableMap.builder |
@@ -138,6 +143,9 @@ class ModelGenerationMethodProvider { | |||
138 | val modalRelationQueries = modalRelationQueriesBuilder.build | 143 | val modalRelationQueries = modalRelationQueriesBuilder.build |
139 | 144 | ||
140 | val invalidWF = queries.getInvalidWFQueries.values | 145 | val invalidWF = queries.getInvalidWFQueries.values |
146 | |||
147 | val mustUnitPropagationPreconditions = queries.getMustUnitPropagationPreconditionPatterns | ||
148 | val currentUnitPropagationPreconditions = queries.getCurrentUnitPropagationPreconditionPatterns | ||
141 | 149 | ||
142 | return new ModelGenerationMethod( | 150 | return new ModelGenerationMethod( |
143 | statistics, | 151 | statistics, |
@@ -146,6 +154,8 @@ class ModelGenerationMethodProvider { | |||
146 | unfinishedMultiplicities, | 154 | unfinishedMultiplicities, |
147 | unfinishedWF, | 155 | unfinishedWF, |
148 | invalidWF, | 156 | invalidWF, |
157 | mustUnitPropagationPreconditions, | ||
158 | currentUnitPropagationPreconditions, | ||
149 | modalRelationQueries, | 159 | modalRelationQueries, |
150 | queries.allQueries | 160 | queries.allQueries |
151 | ) | 161 | ) |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/PropagationModality.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/PropagationModality.java new file mode 100644 index 00000000..2288ad7e --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/PropagationModality.java | |||
@@ -0,0 +1,8 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra; | ||
2 | |||
3 | public enum PropagationModality { | ||
4 | /**The value was originally ? and set to 1 */ | ||
5 | UP, | ||
6 | /**The value was originally ? and set to 0 */ | ||
7 | DOWN | ||
8 | } | ||
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/MultiplicityGoalConstraintCalculator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/MultiplicityGoalConstraintCalculator.xtend index 86a59aa1..034420d6 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/MultiplicityGoalConstraintCalculator.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/MultiplicityGoalConstraintCalculator.xtend | |||
@@ -7,26 +7,39 @@ import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher | |||
7 | import org.eclipse.viatra.query.runtime.emf.EMFScope | 7 | import org.eclipse.viatra.query.runtime.emf.EMFScope |
8 | 8 | ||
9 | class MultiplicityGoalConstraintCalculator { | 9 | class MultiplicityGoalConstraintCalculator { |
10 | val String targetRelationName; | 10 | val String targetRelationName |
11 | val IQuerySpecification<?> querySpecification; | 11 | val IQuerySpecification<?> querySpecification |
12 | var ViatraQueryMatcher<?> matcher; | 12 | var ViatraQueryMatcher<?> matcher |
13 | val int minValue | ||
14 | val boolean containment | ||
15 | val int cost | ||
13 | 16 | ||
14 | new(String targetRelationName, IQuerySpecification<?> querySpecification) { | 17 | public new(String targetRelationName, IQuerySpecification<?> querySpecification, int minValue, boolean containment, int cost) { |
15 | this.targetRelationName = targetRelationName | 18 | this.targetRelationName = targetRelationName |
16 | this.querySpecification = querySpecification | 19 | this.querySpecification = querySpecification |
17 | this.matcher = null | 20 | this.matcher = null |
21 | this.minValue = minValue | ||
22 | this.containment = containment | ||
23 | this.cost = cost | ||
18 | } | 24 | } |
19 | 25 | ||
20 | new(MultiplicityGoalConstraintCalculator other) { | 26 | new(MultiplicityGoalConstraintCalculator other) { |
21 | this.targetRelationName = other.targetRelationName | 27 | this.targetRelationName = other.targetRelationName |
22 | this.querySpecification = other.querySpecification | 28 | this.querySpecification = other.querySpecification |
23 | this.matcher = null | 29 | this.matcher = null |
30 | this.minValue = other.minValue | ||
31 | this.containment = other.containment | ||
32 | this.cost = other.cost | ||
24 | } | 33 | } |
25 | 34 | ||
26 | def getName() { | 35 | def getName() { |
27 | targetRelationName | 36 | targetRelationName |
28 | } | 37 | } |
29 | 38 | ||
39 | def isContainment() { | ||
40 | return containment | ||
41 | } | ||
42 | |||
30 | def init(Notifier notifier) { | 43 | def init(Notifier notifier) { |
31 | val engine = ViatraQueryEngine.on(new EMFScope(notifier)) | 44 | val engine = ViatraQueryEngine.on(new EMFScope(notifier)) |
32 | matcher = querySpecification.getMatcher(engine) | 45 | matcher = querySpecification.getMatcher(engine) |
@@ -36,11 +49,17 @@ class MultiplicityGoalConstraintCalculator { | |||
36 | var res = 0 | 49 | var res = 0 |
37 | val allMatches = this.matcher.allMatches | 50 | val allMatches = this.matcher.allMatches |
38 | for(match : allMatches) { | 51 | for(match : allMatches) { |
39 | //println(targetRelationName+ " missing multiplicity: "+match.get(3)) | 52 | val existingMultiplicity = match.get(4) as Integer |
40 | val missingMultiplicity = match.get(2) as Integer | 53 | if(existingMultiplicity < this.minValue) { |
41 | res += missingMultiplicity | 54 | val missingMultiplicity = this.minValue-existingMultiplicity |
55 | res += missingMultiplicity | ||
56 | } | ||
57 | // if(missingMultiplicity!=0) { | ||
58 | // println(targetRelationName+ " missing multiplicity: "+missingMultiplicity) | ||
59 | // } | ||
42 | } | 60 | } |
43 | //println(targetRelationName+ " all missing multiplicities: "+res) | 61 | // if(res>0) |
44 | return res | 62 | // println(targetRelationName+ " all missing multiplicities: "+res + "*"+cost+"="+res*cost) |
63 | return res*cost | ||
45 | } | 64 | } |
46 | } | 65 | } |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagator.xtend index 51dba244..120fb18a 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagator.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagator.xtend | |||
@@ -187,16 +187,7 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { | |||
187 | if (bounds.upperBound !== null && bounds.upperBound < 0) { | 187 | if (bounds.upperBound !== null && bounds.upperBound < 0) { |
188 | throw new IllegalArgumentException("Negative upper bound: " + bounds) | 188 | throw new IllegalArgumentException("Negative upper bound: " + bounds) |
189 | } | 189 | } |
190 | } | 190 | } |
191 | |||
192 | private def setScopesInvalid() { | ||
193 | partialInterpretation.minNewElements = Integer.MAX_VALUE | ||
194 | partialInterpretation.maxNewElements = 0 | ||
195 | for (scope : partialInterpretation.scopes) { | ||
196 | scope.minNewElements = Integer.MAX_VALUE | ||
197 | scope.maxNewElements = 0 | ||
198 | } | ||
199 | } | ||
200 | 191 | ||
201 | private static def <T extends IPatternMatch> getCalculatedMultiplicity(ViatraQueryMatcher<T> matcher, | 192 | private static def <T extends IPatternMatch> getCalculatedMultiplicity(ViatraQueryMatcher<T> matcher, |
202 | PartialInterpretation p) { | 193 | PartialInterpretation p) { |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ScopePropagator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ScopePropagator.xtend index 2376fb38..8f3a5bb0 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ScopePropagator.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ScopePropagator.xtend | |||
@@ -79,7 +79,7 @@ class ScopePropagator { | |||
79 | // Nothing to propagate. | 79 | // Nothing to propagate. |
80 | } | 80 | } |
81 | 81 | ||
82 | def propagateAdditionToType(PartialTypeInterpratation t) { | 82 | def decrementTypeScope(PartialTypeInterpratation t) { |
83 | // println('''Adding to «(t as PartialComplexTypeInterpretation).interpretationOf.name»''') | 83 | // println('''Adding to «(t as PartialComplexTypeInterpretation).interpretationOf.name»''') |
84 | val targetScope = type2Scope.get(t) | 84 | val targetScope = type2Scope.get(t) |
85 | if (targetScope !== null) { | 85 | if (targetScope !== null) { |
@@ -96,15 +96,23 @@ class ScopePropagator { | |||
96 | if (this.partialInterpretation.maxNewElements > 0) { | 96 | if (this.partialInterpretation.maxNewElements > 0) { |
97 | this.partialInterpretation.maxNewElements = this.partialInterpretation.maxNewElements - 1 | 97 | this.partialInterpretation.maxNewElements = this.partialInterpretation.maxNewElements - 1 |
98 | } else if (this.partialInterpretation.maxNewElements === 0) { | 98 | } else if (this.partialInterpretation.maxNewElements === 0) { |
99 | throw new IllegalArgumentException('''Inconsistent object creation: lower node limit is 0!''') | 99 | setScopesInvalid() |
100 | } | 100 | } |
101 | propagateAllScopeConstraints | ||
102 | 101 | ||
103 | // println('''Target Scope: «targetScope.minNewElements» - «targetScope.maxNewElements»''') | 102 | // println('''Target Scope: «targetScope.minNewElements» - «targetScope.maxNewElements»''') |
104 | // println(''' «this.partialInterpretation.minNewElements» - «this.partialInterpretation.maxNewElements»''') | 103 | // println(''' «this.partialInterpretation.minNewElements» - «this.partialInterpretation.maxNewElements»''') |
105 | // this.partialInterpretation.scopes.forEach[println(''' «(it.targetTypeInterpretation as PartialComplexTypeInterpretation).interpretationOf.name»: «it.minNewElements»-«it.maxNewElements»''')] | 104 | // this.partialInterpretation.scopes.forEach[println(''' «(it.targetTypeInterpretation as PartialComplexTypeInterpretation).interpretationOf.name»: «it.minNewElements»-«it.maxNewElements»''')] |
106 | // println('''All constraints are propagated upon increasing «(t as PartialComplexTypeInterpretation).interpretationOf.name»''') | 105 | // println('''All constraints are propagated upon increasing «(t as PartialComplexTypeInterpretation).interpretationOf.name»''') |
107 | } | 106 | } |
107 | |||
108 | protected def setScopesInvalid() { | ||
109 | partialInterpretation.minNewElements = Integer.MAX_VALUE | ||
110 | partialInterpretation.maxNewElements = 0 | ||
111 | for (scope : partialInterpretation.scopes) { | ||
112 | scope.minNewElements = Integer.MAX_VALUE | ||
113 | scope.maxNewElements = 0 | ||
114 | } | ||
115 | } | ||
108 | 116 | ||
109 | def void propagateAdditionToRelation(Relation r) { | 117 | def void propagateAdditionToRelation(Relation r) { |
110 | // Nothing to propagate. | 118 | // Nothing to propagate. |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/formulacanonization/CanonisedFormulae.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/formulacanonization/CanonisedFormulae.xtend index e511a961..fd4374f5 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/formulacanonization/CanonisedFormulae.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/formulacanonization/CanonisedFormulae.xtend | |||
@@ -11,7 +11,5 @@ import org.eclipse.xtend.lib.annotations.Data | |||
11 | class CanonisedFormulae { | 11 | class CanonisedFormulae { |
12 | CharSequence viatraCode | 12 | CharSequence viatraCode |
13 | Map<Assertion,String> assertion2ConstraintPattern | 13 | Map<Assertion,String> assertion2ConstraintPattern |
14 | Map<ConstantDefinition,String> constant2ValuePattern | ||
15 | Map<RelationDefinition,String> relation2ValuePattern | 14 | Map<RelationDefinition,String> relation2ValuePattern |
16 | Map<FunctionDefinition,String> function2ValuePattern | ||
17 | } \ No newline at end of file | 15 | } \ No newline at end of file |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/formulacanonization/FormulaCanoniser.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/formulacanonization/FormulaCanoniser.xtend index 0af0b36a..182f3a3a 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/formulacanonization/FormulaCanoniser.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/formulacanonization/FormulaCanoniser.xtend | |||
@@ -5,17 +5,35 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.ConstantDefinition | |||
5 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.FunctionDefinition | 5 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.FunctionDefinition |
6 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RelationDefinition | 6 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RelationDefinition |
7 | import java.util.List | 7 | import java.util.List |
8 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Term | ||
9 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.SymbolicValue | ||
10 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Variable | ||
8 | 11 | ||
9 | /** | 12 | /** |
10 | * Translates a set of assertions and definitions to viatra patterns. | 13 | * Translates a Terms into format |
14 | * <P(x1,...,xn)> := Bodies(x1,...,xn) | ||
15 | * <Bodies(x1,...,xn)> := <Body(x1,...,xn)> | <Body(x1,...,xn)> or <Bodies(x1,...,xn)> | ||
16 | * <Body(x1,...,xn)> := Exists y1,...,ym : <Constraints(x1,...,xn,y1,....,ym)> | ||
17 | * <Constraints(x1,...,xn)> := Constraint(x1,...xn) | Constraint(x1,...,xn) and <Constraints(x1,...,xn)> | ||
11 | */ | 18 | */ |
12 | class FormulaCanoniser { | 19 | class FormulaCanoniser { |
13 | def canonise( | 20 | // def canonise( |
14 | List<Assertion> assertions, | 21 | // List<Assertion> assertions, |
15 | List<RelationDefinition> relations, | 22 | // List<RelationDefinition> relations) |
16 | List<ConstantDefinition> constants, | 23 | // { |
17 | List<FunctionDefinition> functions) | 24 | // |
18 | { | 25 | // } |
19 | 26 | // | |
20 | } | 27 | // |
28 | // def canoniseToConstraintBlock(Term predicate, List<Variable> variables) { | ||
29 | // val | ||
30 | // } | ||
31 | // | ||
32 | // def freeVariables(Term t) { | ||
33 | // val subterms = #[t]+t.eAllContents.toList | ||
34 | // val variables = subterms.filter(Variable).toSet | ||
35 | // val variableReferences = subterms.filter(SymbolicValue).filter[it.symbolicReference instanceof Variable] | ||
36 | // val freeVariables = variableReferences.filter[!variables.contains(it.symbolicReference)] | ||
37 | // return freeVariables.map | ||
38 | // } | ||
21 | } \ No newline at end of file | 39 | } \ No newline at end of file |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PConstraintTransformer.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PConstraintTransformer.xtend new file mode 100644 index 00000000..dd5cade1 --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PConstraintTransformer.xtend | |||
@@ -0,0 +1,275 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns | ||
2 | |||
3 | import hu.bme.mit.inf.dslreasoner.viatra2logic.XExpressionExtractor | ||
4 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality | ||
5 | import org.eclipse.emf.ecore.EAttribute | ||
6 | import org.eclipse.emf.ecore.EEnumLiteral | ||
7 | import org.eclipse.emf.ecore.EReference | ||
8 | import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey | ||
9 | import org.eclipse.viatra.query.runtime.emf.types.EDataTypeInSlotsKey | ||
10 | import org.eclipse.viatra.query.runtime.emf.types.EStructuralFeatureInstancesKey | ||
11 | import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint | ||
12 | import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable | ||
13 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Equality | ||
14 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter | ||
15 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExpressionEvaluation | ||
16 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Inequality | ||
17 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.NegativePatternCall | ||
18 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.TypeFilterConstraint | ||
19 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.BinaryTransitiveClosure | ||
20 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.ConstantValue | ||
21 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.PositivePatternCall | ||
22 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint | ||
23 | import hu.bme.mit.inf.dslreasoner.viatra2logic.viatra2logicannotations.VariableMapping | ||
24 | import java.util.List | ||
25 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeReference | ||
26 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.PrimitiveTypeReference | ||
27 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.StringTypeReference | ||
28 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.BoolTypeReference | ||
29 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.IntTypeReference | ||
30 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RealTypeReference | ||
31 | import java.util.Map | ||
32 | |||
33 | class PConstraintTransformer { | ||
34 | val extension RelationDefinitionIndexer relationDefinitionIndexer; | ||
35 | val expressionExtractor = new XExpressionExtractor | ||
36 | val expressionGenerator = new PExpressionGenerator | ||
37 | |||
38 | new(RelationDefinitionIndexer relationDefinitionIndexer) { | ||
39 | this.relationDefinitionIndexer = relationDefinitionIndexer | ||
40 | } | ||
41 | |||
42 | dispatch def transformConstraint(TypeConstraint constraint, Modality modality, List<VariableMapping> variableMapping) { | ||
43 | val touple = constraint.variablesTuple | ||
44 | if(touple.size == 1) { | ||
45 | val inputKey = constraint.equivalentJudgement.inputKey | ||
46 | if(inputKey instanceof EClassTransitiveInstancesKey) { | ||
47 | return relationDefinitionIndexer.base.typeIndexer.referInstanceOf(inputKey.emfKey,modality.toMustMay, | ||
48 | constraint.getVariableInTuple(0).canonizeName) | ||
49 | } else if(inputKey instanceof EDataTypeInSlotsKey){ | ||
50 | return '''// type constraint is enforced by construction''' | ||
51 | } | ||
52 | |||
53 | } else if(touple.size == 2){ | ||
54 | val key = (constraint.equivalentJudgement.inputKey as EStructuralFeatureInstancesKey).emfKey | ||
55 | if(key instanceof EReference) { | ||
56 | return base.referRelationByName( | ||
57 | key, | ||
58 | constraint.getVariableInTuple(0).canonizeName, | ||
59 | constraint.getVariableInTuple(1).canonizeName, | ||
60 | modality.toMustMay) | ||
61 | } else if (key instanceof EAttribute) { | ||
62 | return base.referAttributeByName(key, | ||
63 | constraint.getVariableInTuple(0).canonizeName, | ||
64 | constraint.getVariableInTuple(1).canonizeName, | ||
65 | modality.toMustMay) | ||
66 | } else throw new UnsupportedOperationException('''unknown key: «key.class»''') | ||
67 | } else { | ||
68 | throw new UnsupportedOperationException('''Unsupported touple size: «touple.size»''') | ||
69 | } | ||
70 | } | ||
71 | dispatch def transformConstraint(TypeFilterConstraint constraint, Modality modality, List<VariableMapping> variableMapping) { | ||
72 | val touple = constraint.variablesTuple | ||
73 | if(touple.size == 1) { | ||
74 | val inputKey = constraint.equivalentJudgement.inputKey | ||
75 | if(inputKey instanceof EClassTransitiveInstancesKey) { | ||
76 | return base.typeIndexer.referInstanceOf(inputKey.emfKey,modality.toMustMay, | ||
77 | (constraint.getVariablesTuple.get(0) as PVariable).canonizeName) | ||
78 | } else if(inputKey instanceof EDataTypeInSlotsKey){ | ||
79 | return '''// type constraint is enforced by construction''' | ||
80 | } | ||
81 | |||
82 | } else if(touple.size == 2){ | ||
83 | val key = (constraint.equivalentJudgement.inputKey as EStructuralFeatureInstancesKey).emfKey | ||
84 | if(key instanceof EReference) { | ||
85 | return base.referRelationByName( | ||
86 | key, | ||
87 | (constraint.getVariablesTuple.get(0) as PVariable).canonizeName, | ||
88 | (constraint.getVariablesTuple.get(1) as PVariable).canonizeName, | ||
89 | modality.toMustMay) | ||
90 | } else if (key instanceof EAttribute) { | ||
91 | return base.referAttributeByName(key, | ||
92 | (constraint.getVariablesTuple.get(0) as PVariable).canonizeName, | ||
93 | (constraint.getVariablesTuple.get(1) as PVariable).canonizeName, | ||
94 | modality.toMustMay) | ||
95 | } else throw new UnsupportedOperationException('''unknown key: «key.class»''') | ||
96 | } else { | ||
97 | throw new UnsupportedOperationException('''Unsupported touple size: «touple.size»''') | ||
98 | } | ||
99 | } | ||
100 | |||
101 | dispatch def transformConstraint(Equality equality, Modality modality, List<VariableMapping> variableMapping) { | ||
102 | val a = equality.who | ||
103 | val b = equality.withWhom | ||
104 | transformEquality(modality.toMustMay, a, b) | ||
105 | } | ||
106 | |||
107 | private def CharSequence transformEquality(Modality modality, PVariable a, PVariable b) { | ||
108 | if(modality.isMustOrCurrent) '''find mustEquivalent(problem, interpretation, «a.canonizeName», «b.canonizeName»);''' | ||
109 | else '''find mayEquivalent(problem, interpretation, «a.canonizeName», «b.canonizeName»);''' | ||
110 | } | ||
111 | |||
112 | dispatch def transformConstraint(Inequality inequality, Modality modality, List<VariableMapping> variableMapping) { | ||
113 | val a = inequality.who | ||
114 | val b = inequality.withWhom | ||
115 | if(modality.isCurrent) { | ||
116 | return '''neg find mustEquivalent(problem, interpretation, «a.canonizeName», «b.canonizeName»);''' | ||
117 | } else if(modality.isMust) { | ||
118 | return '''neg find mayEquivalent(problem, interpretation, «a.canonizeName», «b.canonizeName»);''' | ||
119 | } else { // modality.isMay | ||
120 | return '''neg find mustEquivalent(problem, interpretation, «a.canonizeName», «b.canonizeName»);''' | ||
121 | } | ||
122 | } | ||
123 | |||
124 | dispatch def transformConstraint(NegativePatternCall pcall, Modality modality, List<VariableMapping> variableMapping) { | ||
125 | val params = (0..<pcall.actualParametersTuple.size).map[index | | ||
126 | val variable = pcall.actualParametersTuple.get(index) as PVariable | ||
127 | return variable.canonizeName | ||
128 | ] | ||
129 | return referPattern(pcall.referredQuery,params,modality.dual,false,false) | ||
130 | } | ||
131 | |||
132 | dispatch def transformConstraint(PositivePatternCall pcall, Modality modality, List<VariableMapping> variableMapping) { | ||
133 | val params = (0..<pcall.variablesTuple.size).map[index | | ||
134 | val variable = pcall.variablesTuple.get(index) as PVariable | ||
135 | return variable.canonizeName | ||
136 | ] | ||
137 | return referPattern(pcall.referredQuery,params,modality,true,false) | ||
138 | } | ||
139 | dispatch def transformConstraint(BinaryTransitiveClosure pcall, Modality modality, List<VariableMapping> variableMapping) { | ||
140 | val params = (0..1).map[index | | ||
141 | val variable = pcall.getVariableInTuple(index) as PVariable | ||
142 | return variable.canonizeName | ||
143 | ] | ||
144 | return referPattern(pcall.referredQuery,params,modality,true,true) | ||
145 | } | ||
146 | dispatch def transformConstraint(ExportedParameter e, Modality modality, List<VariableMapping> variableMapping) { | ||
147 | val v1 = '''var_«e.parameterName»''' | ||
148 | val v2 = e.parameterVariable.canonizeName | ||
149 | if(v1.compareTo(v2) == 0) { | ||
150 | return '''// «v1» exported''' | ||
151 | } else { | ||
152 | return '''«v1» == «v2»;''' | ||
153 | } | ||
154 | } | ||
155 | dispatch def transformConstraint(ConstantValue c, Modality modality, List<VariableMapping> variableMapping) { | ||
156 | val target = c.supplierKey | ||
157 | |||
158 | var String targetString; | ||
159 | var String additionalDefinition; | ||
160 | if(target instanceof EEnumLiteral) { | ||
161 | targetString = '''const_«target.name»_«target.EEnum.name»''' | ||
162 | additionalDefinition = '''DefinedElement.name(«targetString»,"«target.name» «target.EEnum.name»"); //LogicProblem.elements(problem,«targetString»);''' | ||
163 | } else if(target instanceof Integer) { | ||
164 | targetString = '''const_«target»_Integer''' | ||
165 | additionalDefinition = '''PrimitiveElement.valueSet(«targetString»,true); IntegerElement.value(«targetString»,«target»);''' | ||
166 | } else if(target instanceof Boolean) { | ||
167 | targetString = '''const_«target»_Boolean''' | ||
168 | additionalDefinition = '''PrimitiveElement.valueSet(«targetString»,true); BooleanElement.value(«targetString»,«target»);''' | ||
169 | } else if(target instanceof String) { | ||
170 | targetString = '''const_«target»_String''' | ||
171 | additionalDefinition = '''PrimitiveElement.valueSet(«targetString»,true); StringElement.value(«targetString»,"«target»");''' | ||
172 | } else if(target instanceof Double) { | ||
173 | targetString = '''const_«target»_Real''' | ||
174 | additionalDefinition = '''PrimitiveElement.valueSet(«targetString»,true); RealElement.value(«targetString»,«target»);''' | ||
175 | } else if(target instanceof Float) { | ||
176 | targetString = '''const_«target»_Real''' | ||
177 | additionalDefinition = '''PrimitiveElement.valueSet(«targetString»,true); RealElement.value(«targetString»,«target»);''' | ||
178 | } else { | ||
179 | throw new UnsupportedOperationException('''Unknown constant type: «target.class»''') | ||
180 | } | ||
181 | |||
182 | val source = c.variablesTuple | ||
183 | var String sourceName | ||
184 | if(source.size == 1) | ||
185 | sourceName = (source.get(0) as PVariable).canonizeName | ||
186 | else throw new UnsupportedOperationException("unknown source") | ||
187 | return '''«sourceName» == «targetString»;«additionalDefinition»'''; | ||
188 | } | ||
189 | |||
190 | protected def valueVariable(PVariable v) { | ||
191 | "value_"+v.canonizeName | ||
192 | } | ||
193 | protected def valueSetted(PVariable v) { | ||
194 | "setted_"+v.canonizeName | ||
195 | } | ||
196 | def hasValue(PVariable v, String target, Modality m, List<VariableMapping> variableMapping) { | ||
197 | val typeReference = variableMapping.filter[it.sourcePVariable === v].head.targetLogicVariable.range as PrimitiveTypeReference | ||
198 | if(m.isMay) { | ||
199 | '''PrimitiveElement.valueSet(«v.canonizeName»,«v.valueSetted»); «hasValueExpressionByRef(typeReference,v,v.valueVariable)» | ||
200 | ««« check(!«v.valueSetted»||«v.valueVariable»==«target»)); | ||
201 | ''' | ||
202 | } else { // Must or current | ||
203 | '''PrimitiveElement.valueSet(«v.canonizeName»,true);«hasValueExpressionByRef(typeReference,v,target)»''' | ||
204 | } | ||
205 | } | ||
206 | |||
207 | private def hasValueExpression(List<VariableMapping> variableMapping, PVariable v, String target) { | ||
208 | val mapping = variableMapping.filter[ | ||
209 | val v2 = (it.sourcePVariable as PVariable) | ||
210 | v2 === v | ||
211 | ].head | ||
212 | val range = mapping.targetLogicVariable.range | ||
213 | hasValueExpressionByRef( | ||
214 | range, | ||
215 | v, | ||
216 | target | ||
217 | ) | ||
218 | } | ||
219 | private def dispatch hasValueExpressionByRef(BoolTypeReference typeReference, PVariable v, String target) '''BooleanElement.value(«v.canonizeName»,«target»);''' | ||
220 | private def dispatch hasValueExpressionByRef(IntTypeReference typeReference, PVariable v, String target) '''IntegerElement.value(«v.canonizeName»,«target»);''' | ||
221 | private def dispatch hasValueExpressionByRef(RealTypeReference typeReference, PVariable v, String target) '''RealElement.value(«v.canonizeName»,«target»);''' | ||
222 | private def dispatch hasValueExpressionByRef(StringTypeReference typeReference, PVariable v, String target) '''StringElement.value(«v.canonizeName»,«target»);''' | ||
223 | private def dispatch hasValueExpressionByRef(TypeReference typeReference, PVariable v, String target) { | ||
224 | throw new UnsupportedOperationException('''Unsupported primitive type reference: «typeReference.class»''') | ||
225 | } | ||
226 | |||
227 | dispatch def transformConstraint(ExpressionEvaluation e, Modality modality, List<VariableMapping> variableMapping) { | ||
228 | if(e.outputVariable!==null) { | ||
229 | throw new UnsupportedOperationException('''Only check expressions are supported "«e.class.name»"!''') | ||
230 | } else { | ||
231 | val expression = expressionExtractor.extractExpression(e.evaluator) | ||
232 | val Map<PVariable, PrimitiveTypeReference> variable2Type = e.affectedVariables.toInvertedMap[v|variableMapping.filter[it.sourcePVariable === v].head.targetLogicVariable.range as PrimitiveTypeReference] | ||
233 | if(modality.isMay) { | ||
234 | return ''' | ||
235 | «FOR variable: e.affectedVariables» | ||
236 | PrimitiveElement.valueSet(«variable.canonizeName»,«variable.valueSetted»); «hasValueExpression(variableMapping,variable,variable.valueVariable)» | ||
237 | «ENDFOR» | ||
238 | ««« check( | ||
239 | ««« «FOR variable: e.affectedVariables SEPARATOR " || "»!«variable.valueSetted»«ENDFOR» | ||
240 | ««« «IF variable2Type.values.filter(RealTypeReference).empty» | ||
241 | ««« || | ||
242 | ««« («expressionGenerator.translateExpression(expression,e.affectedVariables.toInvertedMap[valueVariable],variable2Type)») | ||
243 | ««« «ENDIF» | ||
244 | ««« ); | ||
245 | ''' | ||
246 | } else { // Must or Current | ||
247 | return ''' | ||
248 | «FOR variable: e.affectedVariables» | ||
249 | PrimitiveElement.valueSet(«variable.canonizeName»,true); «hasValueExpression(variableMapping,variable,variable.valueVariable)» | ||
250 | «ENDFOR» | ||
251 | ««« «IF variable2Type.values.filter(RealTypeReference).empty» | ||
252 | ««« check(«expressionGenerator.translateExpression(expression,e.affectedVariables.toInvertedMap[valueVariable],variable2Type)»); | ||
253 | ««« «ENDIF» | ||
254 | ''' | ||
255 | } | ||
256 | } | ||
257 | } | ||
258 | |||
259 | dispatch def transformConstraint(PConstraint c, Modality modality, List<VariableMapping> variableMapping) { | ||
260 | throw new UnsupportedOperationException('''Unknown constraint type: "«c.class.name»"!''') | ||
261 | } | ||
262 | |||
263 | dispatch def transformConstraintUnset(ExpressionEvaluation e, List<VariableMapping> variableMapping) { | ||
264 | return ''' | ||
265 | «FOR variable: e.affectedVariables» | ||
266 | PrimitiveElement.valueSet(«variable.canonizeName»,«variable.valueSetted»); «hasValueExpression(variableMapping,variable,variable.valueVariable)» | ||
267 | «ENDFOR» | ||
268 | ««« check(«FOR variable: e.affectedVariables SEPARATOR " || "»!«variable.valueSetted»«ENDFOR»); | ||
269 | ''' | ||
270 | } | ||
271 | |||
272 | dispatch def transformConstraintUnset(PConstraint c, List<VariableMapping> variableMapping) { | ||
273 | throw new UnsupportedOperationException('''Unknown constraint type: "«c.class.name»"!''') | ||
274 | } | ||
275 | } \ No newline at end of file | ||
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PExpressionGenerator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PExpressionGenerator.xtend new file mode 100644 index 00000000..62ff92b2 --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PExpressionGenerator.xtend | |||
@@ -0,0 +1,116 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns | ||
2 | |||
3 | import java.util.Map | ||
4 | import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable | ||
5 | import org.eclipse.xtext.xbase.XBinaryOperation | ||
6 | import org.eclipse.xtext.xbase.XExpression | ||
7 | import org.eclipse.xtext.xbase.XFeatureCall | ||
8 | import org.eclipse.xtext.xbase.XMemberFeatureCall | ||
9 | import org.eclipse.xtext.xbase.XNumberLiteral | ||
10 | import org.eclipse.xtext.xbase.XUnaryOperation | ||
11 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.PrimitiveTypeReference | ||
12 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RealTypeReference | ||
13 | |||
14 | class PExpressionGenerator { | ||
15 | static val N_Base = "org.eclipse.xtext.xbase.lib." | ||
16 | |||
17 | static val N_PLUS1 = "operator_plus" | ||
18 | static val N_MINUS1 = "operator_minus" | ||
19 | |||
20 | static val N_MINUS2 = "operator_minus" | ||
21 | static val N_PLUS2 = "operator_plus" | ||
22 | static val N_POWER = "operator_power" | ||
23 | static val N_MULTIPLY = "operator_multiply" | ||
24 | static val N_DIVIDE = "operator_divide" | ||
25 | static val N_MODULO = "operator_modulo" | ||
26 | static val N_LESSTHAN = "operator_lessThan" | ||
27 | static val N_LESSEQUALSTHAN = "operator_lessEqualsThan" | ||
28 | static val N_GREATERTHAN = "operator_greaterThan" | ||
29 | static val N_GREATEREQUALTHAN = "operator_greaterEqualsThan" | ||
30 | static val N_EQUALS = "operator_equals" | ||
31 | static val N_NOTEQUALS = "operator_notEquals" | ||
32 | static val N_EQUALS3 = "operator_tripleEquals" | ||
33 | static val N_NOTEQUALS3 = "operator_tripleNotEquals" | ||
34 | |||
35 | protected def isN(String name, String s) { | ||
36 | val res = name.startsWith(N_Base) && name.endsWith(s) | ||
37 | //println('''[«res»] «name» ?= «N_Base»*«s»''') | ||
38 | return res | ||
39 | } | ||
40 | |||
41 | static val N_POWER2 = "java.lang.Math.pow" | ||
42 | |||
43 | def dispatch CharSequence translateExpression(XBinaryOperation e, Map<PVariable,String> valueName, Map<PVariable, PrimitiveTypeReference> variable2Type) { | ||
44 | val left = e.leftOperand.translateExpression(valueName,variable2Type) | ||
45 | val right = e.rightOperand.translateExpression(valueName,variable2Type) | ||
46 | val feature = e.feature.qualifiedName | ||
47 | if(feature.isN(N_MINUS2)) { return '''(«left»-«right»)'''} | ||
48 | else if(feature.isN(N_PLUS2)) { return '''(«left»+«right»)''' } | ||
49 | else if(feature.isN(N_POWER)) { return '''(«left»^«right»)''' } | ||
50 | else if(feature.isN(N_MULTIPLY)) { return '''(«left»*«right»)''' } | ||
51 | else if(feature.isN(N_DIVIDE)) { return '''(«left»/«right»)''' } | ||
52 | else if(feature.isN(N_MODULO)) { return '''(«left»%«right»)''' } | ||
53 | else if(feature.isN(N_LESSTHAN)) { return '''(«left»<«right»)''' } | ||
54 | else if(feature.isN(N_LESSEQUALSTHAN)) { return '''(«left»<=«right»)''' } | ||
55 | else if(feature.isN(N_GREATERTHAN)) { return '''(«left»>«right»)''' } | ||
56 | else if(feature.isN(N_GREATEREQUALTHAN)) { return '''(«left»>=«right»)''' } | ||
57 | else if(feature.isN(N_EQUALS)) { return '''(«left»==«right»)''' } | ||
58 | else if(feature.isN(N_NOTEQUALS)) { return '''(«left»!=«right»)''' } | ||
59 | else if(feature.isN(N_EQUALS3)) { return '''(«left»===«right»)''' } | ||
60 | else if(feature.isN(N_NOTEQUALS3)) { return '''(«left»!==«right»)''' } | ||
61 | else { | ||
62 | println("-> " + e.feature+","+e.class) | ||
63 | println("-> " + e.leftOperand) | ||
64 | println("-> " + e.rightOperand) | ||
65 | println("-> " + e.feature.qualifiedName) | ||
66 | throw new UnsupportedOperationException('''Unsupported binary operator feature: "«e.feature.class.simpleName»" - «e»''') | ||
67 | } | ||
68 | } | ||
69 | |||
70 | def dispatch CharSequence translateExpression(XUnaryOperation e, Map<PVariable,String> valueName, Map<PVariable, PrimitiveTypeReference> variable2Type) { | ||
71 | val operand = e.operand.translateExpression(valueName,variable2Type) | ||
72 | val feature = e.feature.qualifiedName | ||
73 | if(feature.isN(N_MINUS1)) { return '''(-«operand»)'''} | ||
74 | else if(feature.isN(N_PLUS1)) { return '''(+«operand»)'''} | ||
75 | else{ | ||
76 | println("-> " + e.feature+","+e.class) | ||
77 | println("-> " + e.operand) | ||
78 | println("-> " + e.feature.qualifiedName) | ||
79 | throw new UnsupportedOperationException('''Unsupported unary operator feature: "«e.feature.class.simpleName»" - «e»''') | ||
80 | } | ||
81 | } | ||
82 | |||
83 | def dispatch CharSequence translateExpression(XMemberFeatureCall e, Map<PVariable,String> valueName, Map<PVariable, PrimitiveTypeReference> variable2Type) { | ||
84 | val transformedArguments = e.actualArguments.map[translateExpression(valueName,variable2Type)] | ||
85 | val feature = e.feature.qualifiedName | ||
86 | if(feature == N_POWER2) { | ||
87 | return '''Math.pow(«transformedArguments.get(0)»,«transformedArguments.get(1)»)''' | ||
88 | }else { | ||
89 | println(e.feature+","+e.class) | ||
90 | println(e.actualArguments.join(", ")) | ||
91 | println(e.feature.qualifiedName) | ||
92 | throw new UnsupportedOperationException('''Unsupported feature call: "«e.feature.qualifiedName»" - «e»''') | ||
93 | } | ||
94 | } | ||
95 | |||
96 | def dispatch CharSequence translateExpression(XFeatureCall e, Map<PVariable,String> valueName, Map<PVariable, PrimitiveTypeReference> variable2Type) { | ||
97 | val featureName = e.feature.qualifiedName | ||
98 | val type = variable2Type.entrySet.filter[it.key.name===featureName].head.value | ||
99 | val entryWithName = valueName.entrySet.filter[it.key.name == featureName].head | ||
100 | if(entryWithName !== null) { | ||
101 | if(type instanceof RealTypeReference) { | ||
102 | return '''(«entryWithName.value».doubleValue)''' | ||
103 | } else { | ||
104 | return entryWithName.value | ||
105 | } | ||
106 | } else { | ||
107 | throw new IllegalArgumentException('''Feature call reference to unavailable variable "«featureName»"''') | ||
108 | } | ||
109 | } | ||
110 | |||
111 | def dispatch CharSequence translateExpression(XNumberLiteral l, Map<PVariable,String> valueName, Map<PVariable, PrimitiveTypeReference> variable2Type) '''«l.value»''' | ||
112 | |||
113 | def dispatch CharSequence translateExpression(XExpression expression, Map<PVariable,String> valueName, Map<PVariable, PrimitiveTypeReference> variable2Type) { | ||
114 | throw new UnsupportedOperationException('''Unsupported expression in check or eval: «expression.class.name», «expression»"''') | ||
115 | } | ||
116 | } \ No newline at end of file | ||
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PatternGenerator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PatternGenerator.xtend index 5c35fb54..f3125b80 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PatternGenerator.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PatternGenerator.xtend | |||
@@ -29,6 +29,14 @@ import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery | |||
29 | import org.eclipse.xtend.lib.annotations.Accessors | 29 | import org.eclipse.xtend.lib.annotations.Accessors |
30 | 30 | ||
31 | import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.* | 31 | import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.* |
32 | import org.eclipse.xtend.lib.annotations.Data | ||
33 | import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint | ||
34 | |||
35 | @Data class PatternGeneratorResult { | ||
36 | CharSequence patternText | ||
37 | HashMap<PConstraint,String> constraint2MustPreconditionName | ||
38 | HashMap<PConstraint,String> constraint2CurrentPreconditionName | ||
39 | } | ||
32 | 40 | ||
33 | class PatternGenerator { | 41 | class PatternGenerator { |
34 | @Accessors(PUBLIC_GETTER) val TypeIndexer typeIndexer // = new TypeIndexer(this) | 42 | @Accessors(PUBLIC_GETTER) val TypeIndexer typeIndexer // = new TypeIndexer(this) |
@@ -39,12 +47,12 @@ class PatternGenerator { | |||
39 | @Accessors(PUBLIC_GETTER) val ContainmentIndexer containmentIndexer = new ContainmentIndexer(this) | 47 | @Accessors(PUBLIC_GETTER) val ContainmentIndexer containmentIndexer = new ContainmentIndexer(this) |
40 | @Accessors(PUBLIC_GETTER) val InvalidIndexer invalidIndexer = new InvalidIndexer(this) | 48 | @Accessors(PUBLIC_GETTER) val InvalidIndexer invalidIndexer = new InvalidIndexer(this) |
41 | @Accessors(PUBLIC_GETTER) val UnfinishedIndexer unfinishedIndexer | 49 | @Accessors(PUBLIC_GETTER) val UnfinishedIndexer unfinishedIndexer |
42 | @Accessors(PUBLIC_GETTER) val TypeRefinementGenerator typeRefinementGenerator // = new RefinementGenerator(this) | 50 | @Accessors(PUBLIC_GETTER) val TypeRefinementGenerator typeRefinementGenerator //= new RefinementGenerator(this) |
43 | @Accessors(PUBLIC_GETTER) val RelationRefinementGenerator relationRefinementGenerator = new RelationRefinementGenerator( | 51 | @Accessors(PUBLIC_GETTER) val RelationRefinementGenerator relationRefinementGenerator = new RelationRefinementGenerator(this) |
44 | this) | 52 | @Accessors(PUBLIC_GETTER) val UnitPropagationPreconditionGenerator unitPropagationPreconditionGenerator = new UnitPropagationPreconditionGenerator(this) |
45 | 53 | ||
46 | new(TypeInferenceMethod typeInferenceMethod, ScopePropagatorStrategy scopePropagatorStrategy) { | 54 | public new(TypeInferenceMethod typeInferenceMethod, ScopePropagatorStrategy scopePropagatorStrategy) { |
47 | if (typeInferenceMethod == TypeInferenceMethod.Generic) { | 55 | if(typeInferenceMethod == TypeInferenceMethod.Generic) { |
48 | this.typeIndexer = new GenericTypeIndexer(this) | 56 | this.typeIndexer = new GenericTypeIndexer(this) |
49 | this.typeRefinementGenerator = new GenericTypeRefinementGenerator(this) | 57 | this.typeRefinementGenerator = new GenericTypeRefinementGenerator(this) |
50 | } else if (typeInferenceMethod == TypeInferenceMethod.PreliminaryAnalysis) { | 58 | } else if (typeInferenceMethod == TypeInferenceMethod.PreliminaryAnalysis) { |
@@ -151,8 +159,8 @@ class PatternGenerator { | |||
151 | RelationConstraints constraints, | 159 | RelationConstraints constraints, |
152 | Collection<LinearTypeConstraintHint> hints | 160 | Collection<LinearTypeConstraintHint> hints |
153 | ) { | 161 | ) { |
154 | 162 | val first = | |
155 | return ''' | 163 | ''' |
156 | import epackage "http://www.bme.hu/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage" | 164 | import epackage "http://www.bme.hu/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage" |
157 | import epackage "http://www.bme.hu/mit/inf/dslreasoner/logic/model/problem" | 165 | import epackage "http://www.bme.hu/mit/inf/dslreasoner/logic/model/problem" |
158 | import epackage "http://www.bme.hu/mit/inf/dslreasoner/logic/model/language" | 166 | import epackage "http://www.bme.hu/mit/inf/dslreasoner/logic/model/language" |
@@ -167,6 +175,7 @@ class PatternGenerator { | |||
167 | ///////////////////////// | 175 | ///////////////////////// |
168 | // 0.1 Existence | 176 | // 0.1 Existence |
169 | ///////////////////////// | 177 | ///////////////////////// |
178 | /** [[exist(element)]]=1 */ | ||
170 | private pattern mustExist(problem:LogicProblem, interpretation:PartialInterpretation, element:DefinedElement) { | 179 | private pattern mustExist(problem:LogicProblem, interpretation:PartialInterpretation, element:DefinedElement) { |
171 | find interpretation(problem,interpretation); | 180 | find interpretation(problem,interpretation); |
172 | LogicProblem.elements(problem,element); | 181 | LogicProblem.elements(problem,element); |
@@ -175,6 +184,7 @@ class PatternGenerator { | |||
175 | PartialInterpretation.newElements(interpretation,element); | 184 | PartialInterpretation.newElements(interpretation,element); |
176 | } | 185 | } |
177 | 186 | ||
187 | /** [[exist(element)]]>=1/2 */ | ||
178 | private pattern mayExist(problem:LogicProblem, interpretation:PartialInterpretation, element:DefinedElement) { | 188 | private pattern mayExist(problem:LogicProblem, interpretation:PartialInterpretation, element:DefinedElement) { |
179 | find mustExist(problem,interpretation,element); | 189 | find mustExist(problem,interpretation,element); |
180 | } or { | 190 | } or { |
@@ -195,57 +205,108 @@ class PatternGenerator { | |||
195 | //////////////////////// | 205 | //////////////////////// |
196 | // 0.2 Equivalence | 206 | // 0.2 Equivalence |
197 | //////////////////////// | 207 | //////////////////////// |
198 | pattern mayEquivalent(problem:LogicProblem, interpretation:PartialInterpretation, a: DefinedElement, b: DefinedElement) { | 208 | pattern mayEquivalent(problem:LogicProblem, interpretation:PartialInterpretation, a: DefinedElement, b: DefinedElement) |
209 | // For non-primitive type. Boolean types always must equivalent or cannot equivalent | ||
210 | { | ||
199 | find mayExist(problem,interpretation,a); | 211 | find mayExist(problem,interpretation,a); |
200 | find mayExist(problem,interpretation,b); | 212 | find mayExist(problem,interpretation,b); |
201 | a == b; | 213 | a == b; |
214 | ««« } or { | ||
215 | ««« find mayExist(problem,interpretation,a); | ||
216 | ««« find mayExist(problem,interpretation,b); | ||
217 | ««« IntegerElement(a); | ||
218 | ««« IntegerElement(b); | ||
219 | ««« PrimitiveElement.valueSet(a,false); | ||
220 | ««« } or { | ||
221 | ««« find mayExist(problem,interpretation,a); | ||
222 | ««« find mayExist(problem,interpretation,b); | ||
223 | ««« IntegerElement(a); | ||
224 | ««« IntegerElement(b); | ||
225 | ««« PrimitiveElement.valueSet(b,false); | ||
226 | ««« } or { | ||
227 | ««« find mayExist(problem,interpretation,a); | ||
228 | ««« find mayExist(problem,interpretation,b); | ||
229 | ««« RealElement(a); | ||
230 | ««« RealElement(b); | ||
231 | ««« PrimitiveElement.valueSet(a,false); | ||
232 | ««« } or { | ||
233 | ««« find mayExist(problem,interpretation,a); | ||
234 | ««« find mayExist(problem,interpretation,b); | ||
235 | ««« RealElement(a); | ||
236 | ««« RealElement(b); | ||
237 | ««« PrimitiveElement.valueSet(b,false); | ||
238 | ««« } or { | ||
239 | ««« find mayExist(problem,interpretation,a); | ||
240 | ««« find mayExist(problem,interpretation,b); | ||
241 | ««« StringElement(a); | ||
242 | ««« StringElement(b); | ||
243 | ««« PrimitiveElement.valueSet(a,false); | ||
244 | ««« } or { | ||
245 | ««« find mayExist(problem,interpretation,a); | ||
246 | ««« find mayExist(problem,interpretation,b); | ||
247 | ««« StringElement(a); | ||
248 | ««« StringElement(b); | ||
249 | ««« PrimitiveElement.valueSet(b,false); | ||
202 | } | 250 | } |
251 | |||
203 | pattern mustEquivalent(problem:LogicProblem, interpretation:PartialInterpretation, a: DefinedElement, b: DefinedElement) { | 252 | pattern mustEquivalent(problem:LogicProblem, interpretation:PartialInterpretation, a: DefinedElement, b: DefinedElement) { |
253 | // For non-primitive and Boolean primitive type | ||
204 | find mustExist(problem,interpretation,a); | 254 | find mustExist(problem,interpretation,a); |
205 | find mustExist(problem,interpretation,b); | 255 | find mustExist(problem,interpretation,b); |
206 | a == b; | 256 | a == b; |
257 | ««« } or { | ||
258 | ««« find mustExist(problem,interpretation,a); | ||
259 | ««« find mustExist(problem,interpretation,b); | ||
260 | ««« PrimitiveElement.valueSet(a,true); | ||
261 | ««« PrimitiveElement.valueSet(b,true); | ||
262 | ««« IntegerElement.value(a,value); | ||
263 | ««« IntegerElement.value(b,value); | ||
264 | ««« } or { | ||
265 | ««« find mustExist(problem,interpretation,a); | ||
266 | ««« find mustExist(problem,interpretation,b); | ||
267 | ««« PrimitiveElement.valueSet(a,true); | ||
268 | ««« PrimitiveElement.valueSet(b,true); | ||
269 | ««« RealElement.value(a,value); | ||
270 | ««« RealElement.value(b,value); | ||
271 | ««« } or { | ||
272 | ««« find mustExist(problem,interpretation,a); | ||
273 | ««« find mustExist(problem,interpretation,b); | ||
274 | ««« PrimitiveElement.valueSet(a,true); | ||
275 | ««« PrimitiveElement.valueSet(b,true); | ||
276 | ««« StringElement.value(a,value); | ||
277 | ««« StringElement.value(b,value); | ||
207 | } | 278 | } |
208 | 279 | ||
209 | //////////////////////// | ||
210 | // 0.3 Required Patterns by TypeIndexer | ||
211 | //////////////////////// | ||
212 | «typeIndexer.requiredQueries» | ||
213 | |||
214 | ////////// | 280 | ////////// |
215 | // 1. Problem-Specific Base Indexers | 281 | // 1. Problem-Specific Base Indexers |
216 | ////////// | 282 | ////////// |
217 | // 1.1 Type Indexers | 283 | // 1.1 Type Indexers |
218 | ////////// | 284 | ////////// |
219 | // 1.1.1 primitive Type Indexers | 285 | // 1.1.1 Required Patterns by TypeIndexer |
220 | ////////// | 286 | ////////// |
221 | ««« pattern instanceofBoolean(problem:LogicProblem, interpretation:PartialInterpretation, element:DefinedElement) { | 287 | |
222 | ««« find interpretation(problem,interpretation); | 288 | «typeIndexer.requiredQueries» |
223 | ««« PartialInterpretation.booleanelements(interpretation,element); | 289 | |
224 | ««« } | 290 | ////////// |
225 | ««« pattern instanceofInteger(problem:LogicProblem, interpretation:PartialInterpretation, element:DefinedElement) { | 291 | // 1.1.2 primitive Type Indexers |
226 | ««« find interpretation(problem,interpretation); | 292 | ////////// |
227 | ««« PartialInterpretation.integerelements(interpretation,element); | 293 | // Currently unused. Refer primitive types as: |
228 | ««« } or { | 294 | // > PrimitiveElement(element) |
229 | ««« find interpretation(problem,interpretation); | 295 | // specific types are referred as: |
230 | ««« PartialInterpretation.newIntegers(interpetation,element); | 296 | // > BooleanElement(variableName) |
231 | ««« } | 297 | // > IntegerElement(variableName) |
232 | ««« pattern instanceofReal(problem:LogicProblem, interpretation:PartialInterpretation, element:DefinedElement) { | 298 | // > RealElement(variableName) |
233 | ««« find interpretation(problem,interpretation); | 299 | // > StringElement(variableName) |
234 | ««« PartialInterpretation.realelements(interpretation,element); | 300 | // And their value as |
235 | ««« } or { | 301 | // > BooleanElement.value(variableName,value) |
236 | ««« find interpretation(problem,interpretation); | 302 | // > IntegerElement.value(variableName,value) |
237 | ««« PartialInterpretation.newReals(interpetation,element); | 303 | // > RealElement.value(variableName,value) |
238 | ««« } | 304 | // > StringElement.value(variableName,value) |
239 | ««« pattern instanceofString(problem:LogicProblem, interpretation:PartialInterpretation, element:DefinedElement) { | 305 | // Whether a value is set is defined by: |
240 | ««« find interpretation(problem,interpretation); | 306 | // > PrimitiveElement.valueSet(variableName,isFilled); |
241 | ««« PartialInterpretation.stringelements(interpretation,element); | ||
242 | ««« } or { | ||
243 | ««« find interpretation(problem,interpretation); | ||
244 | ««« PartialInterpretation.newStrings(interpetation,element); | ||
245 | ««« } | ||
246 | 307 | ||
247 | ////////// | 308 | ////////// |
248 | // 1.1.2 domain-specific Type Indexers | 309 | // 1.1.3 domain-specific Type Indexers |
249 | ////////// | 310 | ////////// |
250 | «typeIndexer.generateInstanceOfQueries(problem,emptySolution,typeAnalysisResult)» | 311 | «typeIndexer.generateInstanceOfQueries(problem,emptySolution,typeAnalysisResult)» |
251 | 312 | ||
@@ -306,6 +367,13 @@ class PatternGenerator { | |||
306 | «FOR hint : hints» | 367 | «FOR hint : hints» |
307 | «hint.getAdditionalPatterns(this)» | 368 | «hint.getAdditionalPatterns(this)» |
308 | «ENDFOR» | 369 | «ENDFOR» |
309 | ''' | 370 | |
371 | ////////// | ||
372 | // 6 Unit Propagations | ||
373 | ////////// | ||
374 | ''' | ||
375 | val up = unitPropagationPreconditionGenerator.generateUnitPropagationRules(problem,problem.relations.filter(RelationDefinition),fqn2PQuery) | ||
376 | val second = up.definitions | ||
377 | return new PatternGeneratorResult(first+second,up.constraint2MustPreconditionName,up.constraint2CurrentPreconditionName) | ||
310 | } | 378 | } |
311 | } | 379 | } |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PatternProvider.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PatternProvider.xtend index f5c85524..ac4a0855 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PatternProvider.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PatternProvider.xtend | |||
@@ -10,6 +10,7 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationStati | |||
10 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeAnalysis | 10 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeAnalysis |
11 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeAnalysisResult | 11 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeAnalysisResult |
12 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeInferenceMethod | 12 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeInferenceMethod |
13 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint | ||
13 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.RelationConstraints | 14 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.RelationConstraints |
14 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.RelationMultiplicityConstraint | 15 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.RelationMultiplicityConstraint |
15 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy | 16 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy |
@@ -17,27 +18,28 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.util.ParseUtil | |||
17 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation | 18 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation |
18 | import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace | 19 | import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace |
19 | import java.util.Collection | 20 | import java.util.Collection |
21 | import java.util.HashMap | ||
20 | import java.util.Map | 22 | import java.util.Map |
21 | import java.util.Set | 23 | import java.util.Set |
22 | import org.eclipse.viatra.query.runtime.api.IPatternMatch | 24 | import org.eclipse.viatra.query.runtime.api.IPatternMatch |
23 | import org.eclipse.viatra.query.runtime.api.IQuerySpecification | 25 | import org.eclipse.viatra.query.runtime.api.IQuerySpecification |
24 | import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher | 26 | import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher |
27 | import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint | ||
25 | import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery | 28 | import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery |
26 | import org.eclipse.xtend.lib.annotations.Data | 29 | import org.eclipse.xtend.lib.annotations.Data |
27 | 30 | ||
28 | import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.* | 31 | import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.* |
29 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint | ||
30 | 32 | ||
31 | @Data | 33 | @Data class GeneratedPatterns { |
32 | class GeneratedPatterns { | ||
33 | public Map<Relation, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> invalidWFQueries | 34 | public Map<Relation, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> invalidWFQueries |
34 | public Map<Relation, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedWFQueries | 35 | public Map<Relation, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedWFQueries |
35 | public Map<RelationMultiplicityConstraint, UnifinishedMultiplicityQueries> multiplicityConstraintQueries | 36 | public Map<RelationMultiplicityConstraint, UnifinishedMultiplicityQueries> multiplicityConstraintQueries |
36 | public IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> hasElementInContainmentQuery | 37 | public IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> hasElementInContainmentQuery |
37 | public Map<Relation, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedMulticiplicityQueries | 38 | public Map<ObjectCreationPrecondition, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> refineObjectQueries |
38 | public Map<ObjectCreationPrecondition, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> refineObjectQueries | ||
39 | public Map<? extends Type, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> refineTypeQueries | 39 | public Map<? extends Type, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> refineTypeQueries |
40 | public Map<Pair<RelationDeclaration, Relation>, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> refinerelationQueries | 40 | public Map<Pair<RelationDeclaration, Relation>, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> refinerelationQueries |
41 | public Map<PConstraint, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> mustUnitPropagationPreconditionPatterns | ||
42 | public Map<PConstraint, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> currentUnitPropagationPreconditionPatterns | ||
41 | public Map<RelationDefinition, ModalPatternQueries> modalRelationQueries | 43 | public Map<RelationDefinition, ModalPatternQueries> modalRelationQueries |
42 | public Collection<IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> allQueries | 44 | public Collection<IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> allQueries |
43 | } | 45 | } |
@@ -76,14 +78,15 @@ class PatternProvider { | |||
76 | } else { | 78 | } else { |
77 | null | 79 | null |
78 | } | 80 | } |
79 | val baseIndexerFile = patternGenerator.transformBaseProperties(problem, emptySolution, fqn2Query, | 81 | val patternGeneratorResult = patternGenerator.transformBaseProperties(problem, emptySolution, fqn2Query, |
80 | typeAnalysisResult, relationConstraints, hints) | 82 | typeAnalysisResult, relationConstraints, hints) |
81 | if (writeToFile) { | 83 | if (writeToFile) { |
82 | workspace.writeText('''generated3valued.vql_deactivated''', baseIndexerFile) | 84 | workspace.writeText('''generated3valued.vql_deactivated''', patternGeneratorResult.patternText) |
83 | } | 85 | } |
84 | val ParseUtil parseUtil = new ParseUtil | 86 | val ParseUtil parseUtil = new ParseUtil |
85 | val generatedQueries = parseUtil.parse(baseIndexerFile) | 87 | val generatedQueries = parseUtil.parse(patternGeneratorResult.patternText) |
86 | val runtimeQueries = calclulateRuntimeQueries(patternGenerator, problem, emptySolution, typeAnalysisResult, | 88 | val runtimeQueries = calclulateRuntimeQueries(patternGenerator, problem, emptySolution, typeAnalysisResult, |
89 | patternGeneratorResult.constraint2MustPreconditionName, patternGeneratorResult.constraint2CurrentPreconditionName, | ||
87 | relationConstraints, generatedQueries) | 90 | relationConstraints, generatedQueries) |
88 | return runtimeQueries | 91 | return runtimeQueries |
89 | } | 92 | } |
@@ -93,32 +96,36 @@ class PatternProvider { | |||
93 | LogicProblem problem, | 96 | LogicProblem problem, |
94 | PartialInterpretation emptySolution, | 97 | PartialInterpretation emptySolution, |
95 | TypeAnalysisResult typeAnalysisResult, | 98 | TypeAnalysisResult typeAnalysisResult, |
99 | HashMap<PConstraint, String> mustUnitPropagationTrace, | ||
100 | HashMap<PConstraint, String> currentUnitPropagationTrace, | ||
96 | RelationConstraints relationConstraints, | 101 | RelationConstraints relationConstraints, |
97 | Map<String, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> queries | 102 | Map<String, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> queries |
98 | ) { | 103 | ) { |
99 | val invalidWFQueries = patternGenerator.invalidIndexer.getInvalidateByWfQueryNames(problem).mapValues [ | 104 | val Map<Relation, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> |
100 | it.lookup(queries) | 105 | invalidWFQueries = patternGenerator.invalidIndexer.getInvalidateByWfQueryNames(problem).mapValues[it.lookup(queries)] |
101 | ] | 106 | val Map<Relation, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> |
102 | val unfinishedWFQueries = patternGenerator.unfinishedIndexer.getUnfinishedWFQueryNames(problem).mapValues [ | 107 | unfinishedWFQueries = patternGenerator.unfinishedIndexer.getUnfinishedWFQueryNames(problem).mapValues[it.lookup(queries)] |
103 | it.lookup(queries) | 108 | |
104 | ] | 109 | val unfinishedMultiplicities = patternGenerator.unfinishedIndexer.getUnfinishedMultiplicityQueries(relationConstraints.multiplicityConstraints) |
105 | val multiplicityConstraintQueries = patternGenerator.unfinishedIndexer.getUnfinishedMultiplicityQueries( | 110 | val multiplicityConstraintQueries = unfinishedMultiplicities.mapValues [ |
106 | relationConstraints.multiplicityConstraints).mapValues [ | ||
107 | new UnifinishedMultiplicityQueries(unfinishedMultiplicityQueryName?.lookup(queries), | 111 | new UnifinishedMultiplicityQueries(unfinishedMultiplicityQueryName?.lookup(queries), |
108 | unrepairableMultiplicityQueryName?.lookup(queries), | 112 | unrepairableMultiplicityQueryName?.lookup(queries), |
109 | remainingInverseMultiplicityQueryName?.lookup(queries), remainingContentsQueryName?.lookup(queries)) | 113 | remainingInverseMultiplicityQueryName?.lookup(queries), remainingContentsQueryName?.lookup(queries)) |
110 | ] | 114 | ] |
111 | val hasElementInContainmentQuery = patternGenerator.typeRefinementGenerator.hasElementInContainmentName.lookup( | 115 | val hasElementInContainmentQuery = patternGenerator.typeRefinementGenerator.hasElementInContainmentName.lookup( |
112 | queries) | 116 | queries) |
113 | val unfinishedMultiplicityQueries = multiplicityConstraintQueries.entrySet.filter [ | 117 | |
114 | value.unfinishedMultiplicityQuery !== null | 118 | val Map<ObjectCreationPrecondition, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> |
115 | ].toMap([key.relation], [value.unfinishedMultiplicityQuery]) | 119 | refineObjectsQueries = patternGenerator.typeRefinementGenerator.getRefineObjectQueryNames(problem,emptySolution,typeAnalysisResult).mapValues[it.lookup(queries)] |
116 | val refineObjectsQueries = patternGenerator.typeRefinementGenerator. | 120 | val Map<? extends Type, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> |
117 | getRefineObjectQueryNames(problem, emptySolution, typeAnalysisResult).mapValues[it.lookup(queries)] | 121 | refineTypeQueries = patternGenerator.typeRefinementGenerator.getRefineTypeQueryNames(problem,emptySolution,typeAnalysisResult).mapValues[it.lookup(queries)] |
118 | val refineTypeQueries = patternGenerator.typeRefinementGenerator.getRefineTypeQueryNames(problem, emptySolution, | 122 | val Map<Pair<RelationDeclaration, Relation>, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> |
119 | typeAnalysisResult).mapValues[it.lookup(queries)] | 123 | refineRelationQueries = patternGenerator.relationRefinementGenerator.getRefineRelationQueries(problem).mapValues[it.lookup(queries)] |
120 | val refineRelationQueries = patternGenerator.relationRefinementGenerator.getRefineRelationQueries(problem). | 124 | val Map<PConstraint, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> |
121 | mapValues[it.lookup(queries)] | 125 | mustUnitPropagationPreconditionPatterns = mustUnitPropagationTrace.mapValues[it.lookup(queries)] |
126 | val Map<PConstraint, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> | ||
127 | currentUnitPropagationPreconditionPatterns = currentUnitPropagationTrace.mapValues[it.lookup(queries)] | ||
128 | |||
122 | val modalRelationQueries = problem.relations.filter(RelationDefinition).toMap([it], [ relationDefinition | | 129 | val modalRelationQueries = problem.relations.filter(RelationDefinition).toMap([it], [ relationDefinition | |
123 | val indexer = patternGenerator.relationDefinitionIndexer | 130 | val indexer = patternGenerator.relationDefinitionIndexer |
124 | new ModalPatternQueries( | 131 | new ModalPatternQueries( |
@@ -127,15 +134,17 @@ class PatternProvider { | |||
127 | indexer.relationDefinitionName(relationDefinition, Modality.CURRENT).lookup(queries) | 134 | indexer.relationDefinitionName(relationDefinition, Modality.CURRENT).lookup(queries) |
128 | ) | 135 | ) |
129 | ]) | 136 | ]) |
137 | |||
130 | return new GeneratedPatterns( | 138 | return new GeneratedPatterns( |
131 | invalidWFQueries, | 139 | invalidWFQueries, |
132 | unfinishedWFQueries, | 140 | unfinishedWFQueries, |
133 | multiplicityConstraintQueries, | 141 | multiplicityConstraintQueries, |
134 | hasElementInContainmentQuery, | 142 | hasElementInContainmentQuery, |
135 | unfinishedMultiplicityQueries, | ||
136 | refineObjectsQueries, | 143 | refineObjectsQueries, |
137 | refineTypeQueries, | 144 | refineTypeQueries, |
138 | refineRelationQueries, | 145 | refineRelationQueries, |
146 | mustUnitPropagationPreconditionPatterns, | ||
147 | currentUnitPropagationPreconditionPatterns, | ||
139 | modalRelationQueries, | 148 | modalRelationQueries, |
140 | queries.values | 149 | queries.values |
141 | ) | 150 | ) |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/RelationDeclarationIndexer.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/RelationDeclarationIndexer.xtend index f384cd50..cef707c5 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/RelationDeclarationIndexer.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/RelationDeclarationIndexer.xtend | |||
@@ -90,13 +90,13 @@ class RelationDeclarationIndexer { | |||
90 | // There are "numberOfExistingReferences" currently existing instances of the reference from the source, | 90 | // There are "numberOfExistingReferences" currently existing instances of the reference from the source, |
91 | // the upper bound of the multiplicity should be considered. | 91 | // the upper bound of the multiplicity should be considered. |
92 | numberOfExistingReferences == count «referRelation(relation,"source","_",Modality.MUST)» | 92 | numberOfExistingReferences == count «referRelation(relation,"source","_",Modality.MUST)» |
93 | check(numberOfExistingReferences < «upperMultiplicities.get(relation)»); | 93 | numberOfExistingReferences != «upperMultiplicities.get(relation)»; |
94 | «ENDIF» | 94 | «ENDIF» |
95 | «IF inverseRelations.containsKey(relation) && upperMultiplicities.containsKey(inverseRelations.get(relation))» | 95 | «IF inverseRelations.containsKey(relation) && upperMultiplicities.containsKey(inverseRelations.get(relation))» |
96 | // There are "numberOfExistingReferences" currently existing instances of the reference to the target, | 96 | // There are "numberOfExistingReferences" currently existing instances of the reference to the target, |
97 | // the upper bound of the opposite reference multiplicity should be considered. | 97 | // the upper bound of the opposite reference multiplicity should be considered. |
98 | numberOfExistingOppositeReferences == count «base.referRelation(inverseRelations.get(relation),"target","_",Modality.MUST,fqn2PQuery)» | 98 | numberOfExistingOppositeReferences == count «base.referRelation(inverseRelations.get(relation),"target","_",Modality.MUST,fqn2PQuery)» |
99 | check(numberOfExistingOppositeReferences < «upperMultiplicities.get(inverseRelations.get(relation))»); | 99 | numberOfExistingOppositeReferences != «upperMultiplicities.get(inverseRelations.get(relation))»; |
100 | «ENDIF» | 100 | «ENDIF» |
101 | «IF containments.contains(relation)» | 101 | «IF containments.contains(relation)» |
102 | // The reference is containment, then a new reference cannot be create if: | 102 | // The reference is containment, then a new reference cannot be create if: |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/RelationDefinitionIndexer.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/RelationDefinitionIndexer.xtend index 0ae28b66..338a9af2 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/RelationDefinitionIndexer.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/RelationDefinitionIndexer.xtend | |||
@@ -5,39 +5,27 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem | |||
5 | import hu.bme.mit.inf.dslreasoner.viatra2logic.viatra2logicannotations.TransfomedViatraQuery | 5 | import hu.bme.mit.inf.dslreasoner.viatra2logic.viatra2logicannotations.TransfomedViatraQuery |
6 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality | 6 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality |
7 | import java.util.Map | 7 | import java.util.Map |
8 | import org.eclipse.emf.common.util.Enumerator | ||
9 | import org.eclipse.emf.ecore.EAttribute | ||
10 | import org.eclipse.emf.ecore.EEnumLiteral | ||
11 | import org.eclipse.emf.ecore.EReference | ||
12 | import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey | ||
13 | import org.eclipse.viatra.query.runtime.emf.types.EDataTypeInSlotsKey | ||
14 | import org.eclipse.viatra.query.runtime.emf.types.EStructuralFeatureInstancesKey | ||
15 | import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint | ||
16 | import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable | 8 | import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable |
17 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Equality | ||
18 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter | ||
19 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Inequality | ||
20 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.NegativePatternCall | ||
21 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.TypeFilterConstraint | ||
22 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.BinaryTransitiveClosure | 9 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.BinaryTransitiveClosure |
23 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.ConstantValue | 10 | import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PDisjunction |
24 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.PositivePatternCall | ||
25 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint | ||
26 | import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery | 11 | import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery |
27 | 12 | ||
28 | import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.* | 13 | import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.* |
29 | 14 | ||
30 | class RelationDefinitionIndexer { | 15 | class RelationDefinitionIndexer { |
31 | val PatternGenerator base; | 16 | public val PatternGenerator base; |
17 | val PConstraintTransformer constraintTransformer; | ||
32 | 18 | ||
33 | new(PatternGenerator base) { | 19 | new(PatternGenerator base) { |
34 | this.base = base | 20 | this.base = base |
21 | this.constraintTransformer = new PConstraintTransformer(this); | ||
35 | } | 22 | } |
36 | 23 | ||
37 | def generateRelationDefinitions( | 24 | def generateRelationDefinitions( |
38 | LogicProblem problem, | 25 | LogicProblem problem, |
39 | Iterable<RelationDefinition> relations, | 26 | Iterable<RelationDefinition> relations, |
40 | Map<String,PQuery> fqn2PQuery) { | 27 | Map<String,PQuery> fqn2PQuery) |
28 | { | ||
41 | val relation2PQuery = relations.toInvertedMap[ | 29 | val relation2PQuery = relations.toInvertedMap[ |
42 | annotations.filter(TransfomedViatraQuery).head.patternFullyQualifiedName.lookup(fqn2PQuery) | 30 | annotations.filter(TransfomedViatraQuery).head.patternFullyQualifiedName.lookup(fqn2PQuery) |
43 | ] | 31 | ] |
@@ -75,20 +63,21 @@ class RelationDefinitionIndexer { | |||
75 | def String relationDefinitionName(RelationDefinition relation, Modality modality) | 63 | def String relationDefinitionName(RelationDefinition relation, Modality modality) |
76 | '''«modality.name.toLowerCase»InRelation_«base.canonizeName(relation.name)»''' | 64 | '''«modality.name.toLowerCase»InRelation_«base.canonizeName(relation.name)»''' |
77 | 65 | ||
78 | private def canonizeName(PVariable v) { | 66 | def canonizeName(PVariable v) { |
79 | return '''«IF v.referringConstraints.size == 1»_«ENDIF»var_«v.name.replaceAll("\\W","")»''' | 67 | return '''«IF v.referringConstraints.size == 1»_«ENDIF»var_«v.name.replaceAll("\\W","")»''' |
80 | } | 68 | } |
81 | 69 | ||
82 | private def transformPattern(RelationDefinition relation, PQuery p, Modality modality) { | 70 | private def transformPattern(RelationDefinition relation, PQuery p, Modality modality) { |
83 | try { | 71 | try { |
72 | val bodies = (relation.annotations.filter(TransfomedViatraQuery).head.optimizedDisjunction as PDisjunction).bodies | ||
84 | return ''' | 73 | return ''' |
85 | private pattern «relationDefinitionName(relation,modality)»( | 74 | private pattern «relationDefinitionName(relation,modality)»( |
86 | problem:LogicProblem, interpretation:PartialInterpretation, | 75 | problem:LogicProblem, interpretation:PartialInterpretation, |
87 | «FOR param : p.parameters SEPARATOR ', '»var_«param.name»«ENDFOR») | 76 | «FOR param : p.parameters SEPARATOR ', '»var_«param.name»«ENDFOR») |
88 | «FOR body : p.disjunctBodies.bodies SEPARATOR "or"»{ | 77 | «FOR body : bodies SEPARATOR "or"»{ |
89 | find interpretation(problem,interpretation); | 78 | find interpretation(problem,interpretation); |
90 | «FOR constraint : body.constraints» | 79 | «FOR constraint : body.constraints» |
91 | «constraint.transformConstraint(modality)» | 80 | «this.constraintTransformer.transformConstraint(constraint,modality,relation.annotations.filter(TransfomedViatraQuery).head.variableTrace)» |
92 | «ENDFOR» | 81 | «ENDFOR» |
93 | }«ENDFOR» | 82 | }«ENDFOR» |
94 | ''' | 83 | ''' |
@@ -105,7 +94,7 @@ class RelationDefinitionIndexer { | |||
105 | ''' | 94 | ''' |
106 | } | 95 | } |
107 | 96 | ||
108 | private def toMustMay(Modality modality) { | 97 | def toMustMay(Modality modality) { |
109 | if(modality == Modality::MAY) return Modality::MAY | 98 | if(modality == Modality::MAY) return Modality::MAY |
110 | else return Modality::MUST | 99 | else return Modality::MUST |
111 | } | 100 | } |
@@ -113,154 +102,4 @@ class RelationDefinitionIndexer { | |||
113 | def referPattern(PQuery p, String[] variables, Modality modality, boolean positive, boolean transitive) ''' | 102 | def referPattern(PQuery p, String[] variables, Modality modality, boolean positive, boolean transitive) ''' |
114 | «IF !positive»neg «ENDIF»find «IF transitive»twoParam_«ENDIF»«modality.name.toLowerCase»InRelation_pattern_«p.fullyQualifiedName.replace('.','_')»«IF transitive»+«ENDIF»(«IF !transitive»problem,interpretation,«ENDIF»«variables.join(',')»); | 103 | «IF !positive»neg «ENDIF»find «IF transitive»twoParam_«ENDIF»«modality.name.toLowerCase»InRelation_pattern_«p.fullyQualifiedName.replace('.','_')»«IF transitive»+«ENDIF»(«IF !transitive»problem,interpretation,«ENDIF»«variables.join(',')»); |
115 | ''' | 104 | ''' |
116 | |||
117 | private dispatch def transformConstraint(TypeConstraint constraint, Modality modality) { | ||
118 | val touple = constraint.variablesTuple | ||
119 | if(touple.size == 1) { | ||
120 | val inputKey = constraint.equivalentJudgement.inputKey | ||
121 | if(inputKey instanceof EClassTransitiveInstancesKey) { | ||
122 | return base.typeIndexer.referInstanceOf(inputKey.emfKey,modality.toMustMay, | ||
123 | constraint.getVariableInTuple(0).canonizeName) | ||
124 | } else if(inputKey instanceof EDataTypeInSlotsKey){ | ||
125 | return '''// type constraint is enforced by construction''' | ||
126 | } | ||
127 | |||
128 | } else if(touple.size == 2){ | ||
129 | val key = (constraint.equivalentJudgement.inputKey as EStructuralFeatureInstancesKey).emfKey | ||
130 | if(key instanceof EReference) { | ||
131 | return base.referRelationByName( | ||
132 | key, | ||
133 | constraint.getVariableInTuple(0).canonizeName, | ||
134 | constraint.getVariableInTuple(1).canonizeName, | ||
135 | modality.toMustMay) | ||
136 | } else if (key instanceof EAttribute) { | ||
137 | return base.referAttributeByName(key, | ||
138 | constraint.getVariableInTuple(0).canonizeName, | ||
139 | constraint.getVariableInTuple(1).canonizeName, | ||
140 | modality.toMustMay) | ||
141 | } else throw new UnsupportedOperationException('''unknown key: «key.class»''') | ||
142 | } else { | ||
143 | throw new UnsupportedOperationException('''Unsupported touple size: «touple.size»''') | ||
144 | } | ||
145 | } | ||
146 | private dispatch def transformConstraint(TypeFilterConstraint constraint, Modality modality) { | ||
147 | val touple = constraint.variablesTuple | ||
148 | if(touple.size == 1) { | ||
149 | val inputKey = constraint.equivalentJudgement.inputKey | ||
150 | if(inputKey instanceof EClassTransitiveInstancesKey) { | ||
151 | return base.typeIndexer.referInstanceOf(inputKey.emfKey,modality.toMustMay, | ||
152 | (constraint.getVariablesTuple.get(0) as PVariable).canonizeName) | ||
153 | } else if(inputKey instanceof EDataTypeInSlotsKey){ | ||
154 | return '''// type constraint is enforced by construction''' | ||
155 | } | ||
156 | |||
157 | } else if(touple.size == 2){ | ||
158 | val key = (constraint.equivalentJudgement.inputKey as EStructuralFeatureInstancesKey).emfKey | ||
159 | if(key instanceof EReference) { | ||
160 | return base.referRelationByName( | ||
161 | key, | ||
162 | (constraint.getVariablesTuple.get(0) as PVariable).canonizeName, | ||
163 | (constraint.getVariablesTuple.get(1) as PVariable).canonizeName, | ||
164 | modality.toMustMay) | ||
165 | } else if (key instanceof EAttribute) { | ||
166 | return base.referAttributeByName(key, | ||
167 | (constraint.getVariablesTuple.get(0) as PVariable).canonizeName, | ||
168 | (constraint.getVariablesTuple.get(1) as PVariable).canonizeName, | ||
169 | modality.toMustMay) | ||
170 | } else throw new UnsupportedOperationException('''unknown key: «key.class»''') | ||
171 | } else { | ||
172 | throw new UnsupportedOperationException('''Unsupported touple size: «touple.size»''') | ||
173 | } | ||
174 | } | ||
175 | |||
176 | private dispatch def transformConstraint(Equality equality, Modality modality) { | ||
177 | val a = equality.who | ||
178 | val b = equality.withWhom | ||
179 | transformEquality(modality.toMustMay, a, b) | ||
180 | } | ||
181 | |||
182 | private def CharSequence transformEquality(Modality modality, PVariable a, PVariable b) { | ||
183 | if(modality.isMustOrCurrent) '''find mustEquivalent(problem, interpretation, «a.canonizeName», «b.canonizeName»);''' | ||
184 | else '''find mayEquivalent(problem, interpretation, «a.canonizeName», «b.canonizeName»);''' | ||
185 | } | ||
186 | |||
187 | private dispatch def transformConstraint(Inequality inequality, Modality modality) { | ||
188 | val a = inequality.who | ||
189 | val b = inequality.withWhom | ||
190 | if(modality.isCurrent) { | ||
191 | return '''neg find mustEquivalent(problem, interpretation, «a.canonizeName», «b.canonizeName»);''' | ||
192 | } else if(modality.isMust) { | ||
193 | return '''neg find mayEquivalent(problem, interpretation, «a.canonizeName», «b.canonizeName»);''' | ||
194 | } else { // modality.isMay | ||
195 | return '''neg find mustEquivalent(problem, interpretation, «a.canonizeName», «b.canonizeName»);''' | ||
196 | } | ||
197 | } | ||
198 | |||
199 | private dispatch def transformConstraint(NegativePatternCall pcall, Modality modality) { | ||
200 | val params = (0..<pcall.actualParametersTuple.size).map[index | | ||
201 | val variable = pcall.actualParametersTuple.get(index) as PVariable | ||
202 | return variable.canonizeName | ||
203 | ] | ||
204 | return referPattern(pcall.referredQuery,params,modality.dual,false,false) | ||
205 | } | ||
206 | |||
207 | private dispatch def transformConstraint(PositivePatternCall pcall, Modality modality) { | ||
208 | val params = (0..<pcall.variablesTuple.size).map[index | | ||
209 | val variable = pcall.variablesTuple.get(index) as PVariable | ||
210 | return variable.canonizeName | ||
211 | ] | ||
212 | return referPattern(pcall.referredQuery,params,modality,true,false) | ||
213 | } | ||
214 | private dispatch def transformConstraint(BinaryTransitiveClosure pcall, Modality modality) { | ||
215 | val params = (0..1).map[index | | ||
216 | val variable = pcall.getVariableInTuple(index) as PVariable | ||
217 | return variable.canonizeName | ||
218 | ] | ||
219 | return referPattern(pcall.referredQuery,params,modality,true,true) | ||
220 | } | ||
221 | private dispatch def transformConstraint(ExportedParameter e, Modality modality) { | ||
222 | return '''// «e.parameterName» is exported''' | ||
223 | } | ||
224 | private dispatch def transformConstraint(ConstantValue c, Modality modality) { | ||
225 | val target = c.supplierKey | ||
226 | |||
227 | var String targetString; | ||
228 | var String additionalDefinition; | ||
229 | if(target instanceof EEnumLiteral) { | ||
230 | targetString = '''const_«target.name»_«target.EEnum.name»''' | ||
231 | additionalDefinition = '''DefinedElement.name(«targetString»,"«target.name» literal «target.EEnum.name»"); //LogicProblem.elements(problem,«targetString»);''' | ||
232 | } else if(target instanceof Enumerator) { | ||
233 | // XXX We should get the corresponding EEnum name instead of the java class name. | ||
234 | targetString = '''const_«target.name»_«target.class.simpleName»''' | ||
235 | additionalDefinition = '''DefinedElement.name(«targetString»,"«target.name» literal «target.class.simpleName»"); //LogicProblem.elements(problem,«targetString»);''' | ||
236 | } else if(target instanceof Integer) { | ||
237 | targetString = '''const_«target»_Integer''' | ||
238 | additionalDefinition = '''IntegerElement.value(«targetString»,«target»);''' | ||
239 | } else if(target instanceof Boolean) { | ||
240 | targetString = '''const_«target»_Boolean''' | ||
241 | additionalDefinition = '''BooleanElement.value(«targetString»,«target»);''' | ||
242 | } else if(target instanceof String) { | ||
243 | targetString = '''const_«target»_String''' | ||
244 | additionalDefinition = '''StringElement.value(«targetString»,"«target»");''' | ||
245 | } else if(target instanceof Double) { | ||
246 | targetString = '''const_«target»_Number''' | ||
247 | additionalDefinition = '''RealElement.value(«targetString»,"«target»");''' | ||
248 | } else if(target instanceof Float) { | ||
249 | targetString = '''const_«target»_Number''' | ||
250 | additionalDefinition = '''RealElement.value(«targetString»,"«target»");''' | ||
251 | } else { | ||
252 | throw new UnsupportedOperationException('''Unknown constant type: «target.class»''') | ||
253 | } | ||
254 | |||
255 | val source = c.variablesTuple | ||
256 | var String sourceName | ||
257 | if(source.size == 1) | ||
258 | sourceName = (source.get(0) as PVariable).canonizeName | ||
259 | else throw new UnsupportedOperationException("unknown source") | ||
260 | return '''«sourceName» == «targetString»;«additionalDefinition»'''; | ||
261 | } | ||
262 | |||
263 | private dispatch def transformConstraint(PConstraint c, Modality modality) { | ||
264 | throw new UnsupportedOperationException('''Unknown constraint type: "«c.class.name»"!''') | ||
265 | } | ||
266 | } \ No newline at end of file | 105 | } \ No newline at end of file |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/TypeIndexer.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/TypeIndexer.xtend index 7d687e99..e4e2aa30 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/TypeIndexer.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/TypeIndexer.xtend | |||
@@ -119,4 +119,8 @@ abstract class TypeIndexer { | |||
119 | '''StringElement.value(«variableName»,"«value»");''' | 119 | '''StringElement.value(«variableName»,"«value»");''' |
120 | } | 120 | } |
121 | 121 | ||
122 | def CharSequence referPrimitiveFilled(String variableName, boolean isFilled) { | ||
123 | '''PrimitiveElement.valueSet(«variableName»,«isFilled»);''' | ||
124 | } | ||
122 | } | 125 | } |
126 | |||
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/UnitPropagationPreconditionGenerator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/UnitPropagationPreconditionGenerator.xtend new file mode 100644 index 00000000..400f47bc --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/UnitPropagationPreconditionGenerator.xtend | |||
@@ -0,0 +1,302 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns | ||
2 | |||
3 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Relation | ||
4 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RelationDefinition | ||
5 | import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem | ||
6 | import hu.bme.mit.inf.dslreasoner.viatra2logic.viatra2logicannotations.TransfomedViatraQuery | ||
7 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality | ||
8 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.PropagationModality | ||
9 | import java.util.Map | ||
10 | import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint | ||
11 | import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable | ||
12 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExpressionEvaluation | ||
13 | import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery | ||
14 | |||
15 | import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.* | ||
16 | import java.util.LinkedList | ||
17 | import java.util.List | ||
18 | import org.eclipse.xtend.lib.annotations.Data | ||
19 | import java.util.HashMap | ||
20 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.PositivePatternCall | ||
21 | import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.NegativePatternCall | ||
22 | import java.util.Comparator | ||
23 | import java.util.ArrayList | ||
24 | import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PDisjunction | ||
25 | import java.util.LinkedHashSet | ||
26 | |||
27 | @Data class UnitPropagation { | ||
28 | val PQuery q | ||
29 | val PConstraint c | ||
30 | val PropagationModality pm | ||
31 | val Modality m3 | ||
32 | } | ||
33 | @Data | ||
34 | class UnitPropagationPreconditionGenerationResult { | ||
35 | List<CharSequence> definitions= new LinkedList | ||
36 | Map<UnitPropagation,String> unitPropagation2PatternName = new HashMap | ||
37 | Map<PConstraint,String> constraintOccurence2Name = new HashMap | ||
38 | |||
39 | def registerQuery(PQuery q, PConstraint c, PropagationModality pm, Modality m3, String patternName, CharSequence definition) { | ||
40 | val key = new UnitPropagation(q,c,pm,m3) | ||
41 | definitions += definition | ||
42 | unitPropagation2PatternName.put(key,patternName) | ||
43 | } | ||
44 | def registerUnsatQuery(PQuery q, PConstraint c, PropagationModality pm, Modality m3) { | ||
45 | val key = new UnitPropagation(q,c,pm,m3) | ||
46 | unitPropagation2PatternName.put(key,null) | ||
47 | } | ||
48 | def contains(PQuery q, PConstraint c, PropagationModality pm, Modality m3) { | ||
49 | val key = new UnitPropagation(q,c,pm,m3) | ||
50 | return unitPropagation2PatternName.containsKey(key) | ||
51 | } | ||
52 | def getName(PQuery q, PConstraint c, PropagationModality pm, Modality m3) { | ||
53 | val key = new UnitPropagation(q,c,pm,m3) | ||
54 | return key.lookup(unitPropagation2PatternName) | ||
55 | } | ||
56 | def isDefined(PQuery q, PConstraint c, PropagationModality pm, Modality m3) { | ||
57 | val key = new UnitPropagation(q,c,pm,m3) | ||
58 | return unitPropagation2PatternName.get(key) !== null | ||
59 | } | ||
60 | } | ||
61 | @Data | ||
62 | class UnitPropagationPreconditionFinalResult { | ||
63 | CharSequence definitions | ||
64 | HashMap<PConstraint,String> constraint2MustPreconditionName | ||
65 | HashMap<PConstraint,String> constraint2CurrentPreconditionName | ||
66 | } | ||
67 | |||
68 | class UnitPropagationPreconditionGenerator { | ||
69 | val PatternGenerator base | ||
70 | val PConstraintTransformer constraintTransformer; | ||
71 | |||
72 | new(PatternGenerator patternGenerator) { | ||
73 | this.base = patternGenerator | ||
74 | this.constraintTransformer = new PConstraintTransformer(base.relationDefinitionIndexer) | ||
75 | } | ||
76 | |||
77 | def generateUnitPropagationRules( | ||
78 | LogicProblem problem, | ||
79 | Iterable<RelationDefinition> relations, | ||
80 | Map<String,PQuery> fqn2PQuery) | ||
81 | { | ||
82 | // Create an empty result | ||
83 | val res = new UnitPropagationPreconditionGenerationResult | ||
84 | val wfs = base.wfQueries(problem)//.map[it.patternPQuery] | ||
85 | val Map<PConstraint,List<Pair<String,Integer>>> mainMustPropagationNames = new HashMap | ||
86 | val Map<PConstraint,List<Pair<String,Integer>>> mainCurrentPropagationNames = new HashMap | ||
87 | for(wf : wfs) { | ||
88 | val query = wf.patternPQuery as PQuery | ||
89 | val relation = wf.target | ||
90 | val allReferredChecks = allReferredConstraints(relation,query).filter(ExpressionEvaluation) | ||
91 | |||
92 | for(referredCheck : allReferredChecks) { | ||
93 | val mustPropagationPrecondition = getOrGeneratePropagationRule(res,relation,query,referredCheck,PropagationModality::UP, Modality::MUST) | ||
94 | val currentPropagationPrecondition = getOrGeneratePropagationRule(res,relation,query,referredCheck,PropagationModality::UP, Modality::CURRENT) | ||
95 | if(!mainMustPropagationNames.containsKey(referredCheck)) { | ||
96 | mainMustPropagationNames.put(referredCheck,new LinkedList) | ||
97 | } | ||
98 | if(!mainCurrentPropagationNames.containsKey(referredCheck)) { | ||
99 | mainCurrentPropagationNames.put(referredCheck,new LinkedList) | ||
100 | } | ||
101 | if(mustPropagationPrecondition !== null) { | ||
102 | mainMustPropagationNames.get(referredCheck).add(mustPropagationPrecondition->query.parameterNames.size) | ||
103 | } | ||
104 | if(currentPropagationPrecondition !== null) { | ||
105 | mainCurrentPropagationNames.get(referredCheck).add(currentPropagationPrecondition->query.parameterNames.size) | ||
106 | } | ||
107 | } | ||
108 | } | ||
109 | val preconditions = new LinkedList | ||
110 | val constraint2MustPrecondition = new HashMap | ||
111 | val constraint2CurrentPrecondition = new HashMap | ||
112 | for(entry : mainMustPropagationNames.entrySet) { | ||
113 | val name = '''UPMUSTPropagate_«res.getOrGenerateConstraintName(entry.key)»'''; | ||
114 | val def = ''' | ||
115 | pattern «name»(«FOR index : 1..entry.key.arity SEPARATOR ", "»«canonizeName(index,PropagationModality::UP)»«ENDFOR») | ||
116 | «FOR propagation : entry.value SEPARATOR " or "» | ||
117 | { find «propagation.key»(problem,interpretation,«FOR index : 0..<propagation.value SEPARATOR ','»_«ENDFOR»,«FOR index : 1..entry.key.arity SEPARATOR ", "»«canonizeName(index,PropagationModality::UP)»«ENDFOR»); } | ||
118 | «ENDFOR»''' | ||
119 | preconditions+=def | ||
120 | constraint2MustPrecondition.put(entry.key,name) | ||
121 | } | ||
122 | for(entry : mainCurrentPropagationNames.entrySet) { | ||
123 | val name = '''UPCurrentPropagate_«res.getOrGenerateConstraintName(entry.key)»'''; | ||
124 | val def = ''' | ||
125 | pattern «name»(«FOR index : 1..entry.key.arity SEPARATOR ", "»«canonizeName(index,PropagationModality::UP)»«ENDFOR») | ||
126 | «FOR propagation : entry.value SEPARATOR " or "» | ||
127 | { find «propagation.key»(problem,interpretation,«FOR index : 0..<propagation.value SEPARATOR ','»_«ENDFOR»,«FOR index : 1..entry.key.arity SEPARATOR ", "»«canonizeName(index,PropagationModality::UP)»«ENDFOR»); } | ||
128 | «ENDFOR»''' | ||
129 | preconditions+=def | ||
130 | constraint2CurrentPrecondition.put(entry.key,name) | ||
131 | } | ||
132 | |||
133 | val definitions = ''' | ||
134 | «FOR def : res.definitions» | ||
135 | «def» | ||
136 | «ENDFOR» | ||
137 | |||
138 | // Collected propagation preconditions: | ||
139 | |||
140 | «FOR predondition : preconditions» | ||
141 | «predondition» | ||
142 | «ENDFOR» | ||
143 | ''' | ||
144 | return new UnitPropagationPreconditionFinalResult(definitions,constraint2MustPrecondition,constraint2CurrentPrecondition) | ||
145 | } | ||
146 | def allReferredConstraints(Relation relation, PQuery query) { | ||
147 | val allReferredQueries = query.allReferredQueries | ||
148 | val problem = relation.eContainer as LogicProblem | ||
149 | val constraints = new LinkedHashSet | ||
150 | for(referredQuery: #[query]+allReferredQueries) { | ||
151 | val referredRelation = problem.annotations.filter(TransfomedViatraQuery).filter[it.patternPQuery === referredQuery].head.target | ||
152 | val bodies = (referredRelation.annotations.filter(TransfomedViatraQuery).head.optimizedDisjunction as PDisjunction).bodies | ||
153 | constraints.addAll(bodies.map[getConstraints].flatten) | ||
154 | } | ||
155 | |||
156 | return constraints | ||
157 | } | ||
158 | |||
159 | def getOrGeneratePropagationRule(UnitPropagationPreconditionGenerationResult res, Relation relation, PQuery q, PConstraint c, PropagationModality pm, Modality m3) { | ||
160 | if(res.contains(q,c,pm,m3)) { | ||
161 | return res.getName(q,c,pm,m3) | ||
162 | } else { | ||
163 | res.generatePropagationRule(relation,q,c,pm,m3) | ||
164 | return res.getName(q,c,pm,m3) | ||
165 | } | ||
166 | } | ||
167 | def getOrGenerateConstraintName(UnitPropagationPreconditionGenerationResult res, PConstraint c){ | ||
168 | if(res.constraintOccurence2Name.containsKey(c)) { | ||
169 | return res.constraintOccurence2Name.get(c) | ||
170 | } else { | ||
171 | val constraintName = '''Constraint«res.constraintOccurence2Name.size»''' | ||
172 | res.constraintOccurence2Name.put(c,constraintName) | ||
173 | return constraintName | ||
174 | } | ||
175 | } | ||
176 | |||
177 | def void generatePropagationRule(UnitPropagationPreconditionGenerationResult res, Relation relation, PQuery q, PConstraint c, PropagationModality pm, Modality m3) { | ||
178 | val name = relationDefinitionName(res,relation,q,c,pm,m3) | ||
179 | val constraintArity = c.arity | ||
180 | val bodies = (relation.annotations.filter(TransfomedViatraQuery).head.optimizedDisjunction as PDisjunction).bodies | ||
181 | val generatedBodies = new LinkedList | ||
182 | for(body : bodies) { | ||
183 | if(body.constraints.contains(c)) { | ||
184 | if(pm === PropagationModality::UP) { | ||
185 | generatedBodies += ''' | ||
186 | // Original Constraints | ||
187 | «FOR constraint : body.constraints.filter[it !== c]» | ||
188 | «this.constraintTransformer.transformConstraint(constraint,m3,relation.annotations.filter(TransfomedViatraQuery).head.variableTrace)» | ||
189 | «ENDFOR» | ||
190 | // Propagation for constraint | ||
191 | «this.constraintTransformer.transformConstraintUnset(c as ExpressionEvaluation,relation.annotations.filter(TransfomedViatraQuery).head.variableTrace)» | ||
192 | // Matching variables | ||
193 | «this.propagateVariables(c,pm)» | ||
194 | ''' | ||
195 | } | ||
196 | // Otherwise, for PropagationModality::DOWN, the body cannot be satisfied | ||
197 | } else { | ||
198 | val positives = body.constraints.filter(PositivePatternCall) | ||
199 | for(positive: positives) { | ||
200 | val referredPQuery = positive.referredQuery | ||
201 | val referredRelation = (relation.eContainer as LogicProblem) | ||
202 | .annotations.filter(TransfomedViatraQuery).filter[it.patternPQuery === referredPQuery].head.target | ||
203 | if(allReferredConstraints(referredRelation,referredPQuery).toSet.contains(c)) { | ||
204 | val referredName = getOrGeneratePropagationRule(res,referredRelation,referredPQuery,c,pm,m3) | ||
205 | if(referredName !== null) { | ||
206 | generatedBodies += ''' | ||
207 | // Original Constraints | ||
208 | «FOR constraint : body.constraints.filter[it !== positive]» | ||
209 | «this.constraintTransformer.transformConstraint(constraint,m3,relation.annotations.filter(TransfomedViatraQuery).head.variableTrace)» | ||
210 | «ENDFOR» | ||
211 | // Propagation for constraint referred indirectly from this pattern through «referredName» | ||
212 | find «referredName»(problem, interpretation, | ||
213 | «FOR index : 0..<referredPQuery.parameters.size SEPARATOR ", "»«positive.getVariableInTuple(index).canonizeName»«ENDFOR», | ||
214 | «FOR index : 1..c.arity SEPARATOR ", "»«canonizeName(index,pm)»«ENDFOR»); | ||
215 | ''' | ||
216 | } | ||
217 | // Otherwise, if the referred pattern is not satisfiable, this pattern is not satisfiable either | ||
218 | } | ||
219 | } | ||
220 | |||
221 | val negatives = body.constraints.filter(NegativePatternCall) | ||
222 | for(negative : negatives) { | ||
223 | val referredPQuery = negative.referredQuery | ||
224 | val referredRelation = (relation.eContainer as LogicProblem) | ||
225 | .annotations.filter(TransfomedViatraQuery).filter[it.patternPQuery === referredPQuery].head.target | ||
226 | if(allReferredConstraints(referredRelation,referredPQuery).toSet.contains(c)) { | ||
227 | val referredName = getOrGeneratePropagationRule(res,referredRelation,referredPQuery,c,pm,m3.dual) | ||
228 | if(referredName !== null) { | ||
229 | generatedBodies += ''' | ||
230 | // Original Constraints | ||
231 | «FOR constraint : body.constraints.filter[it !== negative]» | ||
232 | «this.constraintTransformer.transformConstraint(constraint,m3,relation.annotations.filter(TransfomedViatraQuery).head.variableTrace)» | ||
233 | «ENDFOR» | ||
234 | // Propagation for constraint referred indirectly from this pattern through «referredName» | ||
235 | find «referredName»(problem, interpretation, | ||
236 | «FOR index : 0..<referredPQuery.parameters.size SEPARATOR ", "»«(negative.actualParametersTuple.get(index) as PVariable).canonizeName»«ENDFOR», | ||
237 | «FOR index : 1..c.arity SEPARATOR ", "»«canonizeName(index,pm)»«ENDFOR»); | ||
238 | ''' | ||
239 | } else { | ||
240 | generatedBodies += ''' | ||
241 | // Original Constraints | ||
242 | «FOR constraint : body.constraints.filter[it !== negative]» | ||
243 | «this.constraintTransformer.transformConstraint(constraint,m3,relation.annotations.filter(TransfomedViatraQuery).head.variableTrace)» | ||
244 | «ENDFOR» | ||
245 | // Propagation for constraint referred indirectly from this pattern through «referredName», | ||
246 | // which was unsatisfiable | ||
247 | ''' | ||
248 | } | ||
249 | } | ||
250 | } | ||
251 | } | ||
252 | } | ||
253 | |||
254 | // Register the result | ||
255 | if(generatedBodies.empty) { | ||
256 | res.registerUnsatQuery(q,c,pm,m3) | ||
257 | } else { | ||
258 | val definition = ''' | ||
259 | private pattern «name»( | ||
260 | problem:LogicProblem, interpretation:PartialInterpretation, | ||
261 | «FOR param : q.parameters SEPARATOR ', '»var_«param.name»«ENDFOR», | ||
262 | «FOR arity : 1..constraintArity SEPARATOR ', '»«canonizeName(arity,pm)»«ENDFOR») | ||
263 | «FOR generatedBody: generatedBodies SEPARATOR " or "»{ | ||
264 | «generatedBody» | ||
265 | }«ENDFOR» | ||
266 | ''' | ||
267 | res.registerQuery(q,c,pm,m3,name,definition) | ||
268 | } | ||
269 | } | ||
270 | |||
271 | private def String relationDefinitionName(UnitPropagationPreconditionGenerationResult res, Relation relation, PQuery q, PConstraint c, PropagationModality pm, Modality m3) | ||
272 | '''«pm.name»«m3.name»Propagate«res.getOrGenerateConstraintName(c)»_«base.canonizeName(relation.name)»''' | ||
273 | |||
274 | def canonizeName(PVariable v) { | ||
275 | return '''«IF v.referringConstraints.size == 1»_«ENDIF»var_«v.name.replaceAll("\\W","")»''' | ||
276 | } | ||
277 | |||
278 | def canonizeName(int index, PropagationModality m) { | ||
279 | return '''«m.name.toLowerCase»_«index»''' | ||
280 | } | ||
281 | |||
282 | def dispatch propagateVariables(ExpressionEvaluation c, PropagationModality m) { | ||
283 | val comparator = new Comparator<PVariable>(){ | ||
284 | override compare(PVariable o1, PVariable o2) { | ||
285 | o1.name.compareTo(o2.name) | ||
286 | } | ||
287 | } | ||
288 | val variablesInOrder = new ArrayList(c.affectedVariables) | ||
289 | variablesInOrder.toList.sort(comparator) | ||
290 | return '''«FOR variableIndex : 1..variablesInOrder.size»«variablesInOrder.get(variableIndex-1).canonizeName»==«canonizeName(variableIndex,m)»;«ENDFOR»''' | ||
291 | } | ||
292 | def dispatch propagateVariables(PConstraint c, PropagationModality m) { | ||
293 | throw new UnsupportedOperationException('''Constraint not supported: «c.class.simpleName»''') | ||
294 | } | ||
295 | |||
296 | def dispatch arity(ExpressionEvaluation c) { | ||
297 | c.affectedVariables.size | ||
298 | } | ||
299 | def dispatch arity(PConstraint c) { | ||
300 | throw new UnsupportedOperationException('''Constraint not supported: «c.class.simpleName»''') | ||
301 | } | ||
302 | } \ No newline at end of file | ||
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/rules/GoalConstraintProvider.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/rules/GoalConstraintProvider.xtend index b6fdbe06..238ade5b 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/rules/GoalConstraintProvider.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/rules/GoalConstraintProvider.xtend | |||
@@ -1,18 +1,26 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules | 1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules |
2 | 2 | ||
3 | import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem | ||
3 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.MultiplicityGoalConstraintCalculator | 4 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.MultiplicityGoalConstraintCalculator |
4 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.GeneratedPatterns | 5 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.GeneratedPatterns |
5 | import java.util.ArrayList | 6 | import java.util.ArrayList |
6 | 7 | ||
7 | class GoalConstraintProvider { | 8 | class GoalConstraintProvider { |
8 | def public getUnfinishedMultiplicityQueries(GeneratedPatterns patterns) { | 9 | |
9 | val multiplicityQueries = patterns.unfinishedMulticiplicityQueries | 10 | def getUnfinishedMultiplicityQueries(LogicProblem p, GeneratedPatterns patterns) { |
10 | val res = new ArrayList(multiplicityQueries.size) | 11 | val res = new ArrayList() |
11 | for(multiplicityQuery : multiplicityQueries.entrySet) { | 12 | for (entry : patterns.multiplicityConstraintQueries.entrySet) { |
12 | val targetRelationName = multiplicityQuery.key.name | 13 | val constraint = entry.key |
13 | val query = multiplicityQuery.value | 14 | if (constraint.constrainsUnfinished) { |
14 | res += new MultiplicityGoalConstraintCalculator(targetRelationName,query); | 15 | val queries = entry.value |
16 | val targetRelationName = constraint.relation.name | ||
17 | val query = queries.unfinishedMultiplicityQuery | ||
18 | val minValue = constraint.lowerBound | ||
19 | val containment = constraint.containment | ||
20 | res += new MultiplicityGoalConstraintCalculator(targetRelationName, query, minValue, containment, 1) | ||
21 | } | ||
15 | } | 22 | } |
16 | return res | 23 | return res |
17 | } | 24 | } |
25 | |||
18 | } \ No newline at end of file | 26 | } \ No newline at end of file |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/rules/RefinementRuleProvider.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/rules/RefinementRuleProvider.xtend index 7891ebd8..0b8a9019 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/rules/RefinementRuleProvider.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/rules/RefinementRuleProvider.xtend | |||
@@ -1,71 +1,93 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules | 1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules |
2 | 2 | ||
3 | import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.InverseRelationAssertion | ||
4 | import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.LowerMultiplicityAssertion | ||
5 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.BoolTypeReference | ||
6 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.ComplexTypeReference | ||
3 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.DefinedElement | 7 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.DefinedElement |
8 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.IntTypeReference | ||
4 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.LogiclanguageFactory | 9 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.LogiclanguageFactory |
10 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.PrimitiveTypeReference | ||
11 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RealTypeReference | ||
5 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Relation | 12 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Relation |
6 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RelationDeclaration | 13 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RelationDeclaration |
14 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.StringTypeReference | ||
7 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type | 15 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type |
16 | import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem | ||
8 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationStatistics | 17 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationStatistics |
9 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagator | 18 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagator |
10 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.GeneratedPatterns | 19 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.GeneratedPatterns |
11 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.ObjectCreationPrecondition | 20 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.ObjectCreationPrecondition |
21 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialBooleanInterpretation | ||
12 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialComplexTypeInterpretation | 22 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialComplexTypeInterpretation |
23 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialIntegerInterpretation | ||
13 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation | 24 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation |
25 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialRealInterpretation | ||
14 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialRelationInterpretation | 26 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialRelationInterpretation |
27 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialStringInterpretation | ||
28 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialTypeInterpratation | ||
15 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationFactory | 29 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationFactory |
30 | import java.util.HashMap | ||
16 | import java.util.LinkedHashMap | 31 | import java.util.LinkedHashMap |
32 | import java.util.LinkedList | ||
33 | import java.util.List | ||
34 | import java.util.Map | ||
17 | import org.eclipse.viatra.query.runtime.api.GenericPatternMatch | 35 | import org.eclipse.viatra.query.runtime.api.GenericPatternMatch |
18 | import org.eclipse.viatra.query.runtime.api.IQuerySpecification | 36 | import org.eclipse.viatra.query.runtime.api.IQuerySpecification |
19 | import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher | 37 | import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher |
20 | import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRule | 38 | import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRule |
21 | import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRuleFactory | 39 | import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRuleFactory |
40 | import org.eclipse.xtend.lib.annotations.Data | ||
41 | import org.eclipse.xtext.xbase.lib.Functions.Function0 | ||
22 | 42 | ||
23 | class RefinementRuleProvider { | 43 | class RefinementRuleProvider { |
24 | private extension BatchTransformationRuleFactory factory = new BatchTransformationRuleFactory | 44 | val extension BatchTransformationRuleFactory factory = new BatchTransformationRuleFactory |
25 | private extension PartialinterpretationFactory factory2 = PartialinterpretationFactory.eINSTANCE | 45 | val extension PartialinterpretationFactory factory2 = PartialinterpretationFactory.eINSTANCE |
26 | private extension LogiclanguageFactory factory3 = LogiclanguageFactory.eINSTANCE | 46 | val extension LogiclanguageFactory factory3 = LogiclanguageFactory.eINSTANCE |
27 | 47 | ||
28 | def canonizeName(String name) { | 48 | def canonizeName(String name) { |
29 | return name.replace(' ','_') | 49 | return name.replace(' ','_') |
30 | } | 50 | } |
31 | 51 | ||
32 | def LinkedHashMap<ObjectCreationPrecondition, BatchTransformationRule<GenericPatternMatch, ViatraQueryMatcher<GenericPatternMatch>>> | 52 | def LinkedHashMap<ObjectCreationPrecondition, BatchTransformationRule<GenericPatternMatch, ViatraQueryMatcher<GenericPatternMatch>>> createObjectRefinementRules( |
33 | createObjectRefinementRules( | 53 | LogicProblem p, |
54 | PartialInterpretation i, | ||
34 | GeneratedPatterns patterns, | 55 | GeneratedPatterns patterns, |
35 | ScopePropagator scopePropagator, | 56 | ScopePropagator scopePropagator, |
36 | boolean nameNewElement, | 57 | boolean nameNewElement, |
37 | ModelGenerationStatistics statistics | 58 | ModelGenerationStatistics statistics |
38 | ) | 59 | ) |
39 | { | 60 | { |
40 | val res = new LinkedHashMap | 61 | val res = new LinkedHashMap |
62 | val recursiveObjectCreation = recursiveObjectCreation(p,i) | ||
41 | for(LHSEntry: patterns.refineObjectQueries.entrySet) { | 63 | for(LHSEntry: patterns.refineObjectQueries.entrySet) { |
42 | val containmentRelation = LHSEntry.key.containmentRelation | 64 | val containmentRelation = LHSEntry.key.containmentRelation |
43 | val inverseRelation = LHSEntry.key.inverseContainment | 65 | val inverseRelation = LHSEntry.key.inverseContainment |
44 | val type = LHSEntry.key.newType | 66 | val type = LHSEntry.key.newType |
45 | val lhs = LHSEntry.value as IQuerySpecification<ViatraQueryMatcher<GenericPatternMatch>> | 67 | val lhs = LHSEntry.value as IQuerySpecification<ViatraQueryMatcher<GenericPatternMatch>> |
46 | val rule = createObjectCreationRule(containmentRelation,inverseRelation,type,lhs,nameNewElement,scopePropagator,statistics) | 68 | val rule = createObjectCreationRule(p,containmentRelation,inverseRelation,type,recursiveObjectCreation.get(type),lhs,nameNewElement,scopePropagator,statistics) |
47 | res.put(LHSEntry.key,rule) | 69 | res.put(LHSEntry.key,rule) |
48 | } | 70 | } |
49 | return res | 71 | return res |
50 | } | 72 | } |
51 | 73 | ||
52 | def private createObjectCreationRule( | 74 | def private createObjectCreationRule( |
75 | LogicProblem p, | ||
53 | Relation containmentRelation, | 76 | Relation containmentRelation, |
54 | Relation inverseRelation, | 77 | Relation inverseRelation, |
55 | Type type, | 78 | Type type, |
79 | List<ObjectCreationInterpretationData> recursiceObjectCreations, | ||
56 | IQuerySpecification<ViatraQueryMatcher<GenericPatternMatch>> lhs, | 80 | IQuerySpecification<ViatraQueryMatcher<GenericPatternMatch>> lhs, |
57 | boolean nameNewElement, | 81 | boolean nameNewElement, |
58 | ScopePropagator scopePropagator, | 82 | ScopePropagator scopePropagator, |
59 | ModelGenerationStatistics statistics) | 83 | ModelGenerationStatistics statistics) |
60 | { | 84 | { |
61 | val name = '''addObject_«type.name.canonizeName»« | 85 | val name = '''addObject_«type.name.canonizeName»« |
62 | IF containmentRelation!=null»_by_«containmentRelation.name.canonizeName»«ENDIF»''' | 86 | IF containmentRelation!==null»_by_«containmentRelation.name.canonizeName»«ENDIF»''' |
63 | //println("Rule created: " + name + "> " + lhs.fullyQualifiedName) | 87 | val ruleBuilder = factory.createRule(lhs) |
64 | val ruleBuilder = factory.createRule | ||
65 | .name(name) | 88 | .name(name) |
66 | .precondition(lhs) | 89 | if(containmentRelation !== null) { |
67 | if(containmentRelation != null) { | 90 | if(inverseRelation!== null) { |
68 | if(inverseRelation!= null) { | ||
69 | ruleBuilder.action[match | | 91 | ruleBuilder.action[match | |
70 | statistics.incrementTransformationCount | 92 | statistics.incrementTransformationCount |
71 | // println(name) | 93 | // println(name) |
@@ -77,33 +99,23 @@ class RefinementRuleProvider { | |||
77 | val typeInterpretation = match.get(4) as PartialComplexTypeInterpretation | 99 | val typeInterpretation = match.get(4) as PartialComplexTypeInterpretation |
78 | val container = match.get(5) as DefinedElement | 100 | val container = match.get(5) as DefinedElement |
79 | 101 | ||
80 | val newElement = createDefinedElement | 102 | createObjectActionWithContainmentAndInverse( |
81 | if(nameNewElement) { | 103 | nameNewElement, |
82 | newElement.name = '''new «interpretation.newElements.size»''' | 104 | interpretation, |
83 | } | 105 | typeInterpretation, |
84 | 106 | container, | |
85 | // Existence | 107 | relationInterpretation, |
86 | interpretation.newElements+=newElement | 108 | inverseRelationInterpretation, |
87 | /*interpretation.maxNewElements=interpretation.maxNewElements-1 | 109 | [createDefinedElement], |
88 | if(interpretation.minNewElements > 0) { | 110 | recursiceObjectCreations, |
89 | interpretation.minNewElements=interpretation.minNewElements-1 | 111 | scopePropagator |
90 | }*/ | 112 | ) |
91 | |||
92 | // Types | ||
93 | typeInterpretation.elements += newElement | ||
94 | typeInterpretation.supertypeInterpretation.forEach[it.elements += newElement] | ||
95 | // ContainmentRelation | ||
96 | val newLink1 = factory2.createBinaryElementRelationLink => [it.param1 = container it.param2 = newElement] | ||
97 | relationInterpretation.relationlinks+=newLink1 | ||
98 | // Inverse Containment | ||
99 | val newLink2 = factory2.createBinaryElementRelationLink => [it.param1 = newElement it.param2 = container] | ||
100 | inverseRelationInterpretation.relationlinks+=newLink2 | ||
101 | 113 | ||
102 | val propagatorStartTime = System.nanoTime | 114 | val propagatorStartTime = System.nanoTime |
103 | statistics.addExecutionTime(propagatorStartTime-startTime) | 115 | statistics.addExecutionTime(propagatorStartTime-startTime) |
104 | 116 | ||
105 | // Scope propagation | 117 | // Scope propagation |
106 | scopePropagator.propagateAdditionToType(typeInterpretation) | 118 | scopePropagator.propagateAllScopeConstraints() |
107 | statistics.addScopePropagationTime(System.nanoTime-propagatorStartTime) | 119 | statistics.addScopePropagationTime(System.nanoTime-propagatorStartTime) |
108 | ] | 120 | ] |
109 | } else { | 121 | } else { |
@@ -117,30 +129,22 @@ class RefinementRuleProvider { | |||
117 | val typeInterpretation = match.get(3) as PartialComplexTypeInterpretation | 129 | val typeInterpretation = match.get(3) as PartialComplexTypeInterpretation |
118 | val container = match.get(4) as DefinedElement | 130 | val container = match.get(4) as DefinedElement |
119 | 131 | ||
120 | val newElement = createDefinedElement | 132 | createObjectActionWithContainment( |
121 | if(nameNewElement) { | 133 | nameNewElement, |
122 | newElement.name = '''new «interpretation.newElements.size»''' | 134 | interpretation, |
123 | } | 135 | typeInterpretation, |
124 | 136 | container, | |
125 | // Existence | 137 | relationInterpretation, |
126 | interpretation.newElements+=newElement | 138 | [createDefinedElement], |
127 | /*interpretation.maxNewElements=interpretation.maxNewElements-1 | 139 | recursiceObjectCreations, |
128 | if(interpretation.minNewElements > 0) { | 140 | scopePropagator |
129 | interpretation.minNewElements=interpretation.minNewElements-1 | 141 | ) |
130 | }*/ | ||
131 | |||
132 | // Types | ||
133 | typeInterpretation.elements += newElement | ||
134 | typeInterpretation.supertypeInterpretation.forEach[it.elements += newElement] | ||
135 | // ContainmentRelation | ||
136 | val newLink = factory2.createBinaryElementRelationLink => [it.param1 = container it.param2 = newElement] | ||
137 | relationInterpretation.relationlinks+=newLink | ||
138 | 142 | ||
139 | val propagatorStartTime = System.nanoTime | 143 | val propagatorStartTime = System.nanoTime |
140 | statistics.addExecutionTime(propagatorStartTime-startTime) | 144 | statistics.addExecutionTime(propagatorStartTime-startTime) |
141 | 145 | ||
142 | // Scope propagation | 146 | // Scope propagation |
143 | scopePropagator.propagateAdditionToType(typeInterpretation) | 147 | scopePropagator.propagateAllScopeConstraints() |
144 | statistics.addScopePropagationTime(System.nanoTime-propagatorStartTime) | 148 | statistics.addScopePropagationTime(System.nanoTime-propagatorStartTime) |
145 | ] | 149 | ] |
146 | } | 150 | } |
@@ -148,40 +152,175 @@ class RefinementRuleProvider { | |||
148 | ruleBuilder.action[match | | 152 | ruleBuilder.action[match | |
149 | statistics.incrementTransformationCount | 153 | statistics.incrementTransformationCount |
150 | // println(name) | 154 | // println(name) |
151 | |||
152 | val startTime = System.nanoTime | 155 | val startTime = System.nanoTime |
153 | //val problem = match.get(0) as LogicProblem | 156 | //val problem = match.get(0) as LogicProblem |
154 | val interpretation = match.get(1) as PartialInterpretation | 157 | val interpretation = match.get(1) as PartialInterpretation |
155 | val typeInterpretation = match.get(2) as PartialComplexTypeInterpretation | 158 | val typeInterpretation = match.get(2) as PartialComplexTypeInterpretation |
156 | 159 | ||
157 | val newElement = createDefinedElement | 160 | createObjectAction( |
158 | if(nameNewElement) { | 161 | nameNewElement, |
159 | newElement.name = '''new «interpretation.newElements.size»''' | 162 | interpretation, |
160 | } | 163 | typeInterpretation, |
161 | 164 | [createDefinedElement], | |
162 | // Existence | 165 | recursiceObjectCreations, |
163 | interpretation.newElements+=newElement | 166 | scopePropagator |
164 | /* | 167 | ) |
165 | interpretation.maxNewElements=interpretation.maxNewElements-1 | ||
166 | if(interpretation.minNewElements > 0) { | ||
167 | interpretation.minNewElements=interpretation.minNewElements-1 | ||
168 | }*/ | ||
169 | |||
170 | // Types | ||
171 | typeInterpretation.elements += newElement | ||
172 | typeInterpretation.supertypeInterpretation.forEach[it.elements += newElement] | ||
173 | 168 | ||
174 | val propagatorStartTime = System.nanoTime | 169 | val propagatorStartTime = System.nanoTime |
175 | statistics.addExecutionTime(propagatorStartTime-startTime) | 170 | statistics.addExecutionTime(propagatorStartTime-startTime) |
176 | 171 | ||
177 | // Scope propagation | 172 | // Scope propagation |
178 | scopePropagator.propagateAdditionToType(typeInterpretation) | 173 | scopePropagator.propagateAllScopeConstraints() |
179 | statistics.addScopePropagationTime(System.nanoTime-propagatorStartTime) | 174 | statistics.addScopePropagationTime(System.nanoTime-propagatorStartTime) |
180 | ] | 175 | ] |
181 | } | 176 | } |
182 | return ruleBuilder.build | 177 | return ruleBuilder.build |
183 | } | 178 | } |
184 | 179 | ||
180 | def private recursiveObjectCreation(LogicProblem p, PartialInterpretation i) { | ||
181 | val Map<Type,List<ObjectCreationInterpretationData>> recursiveObjectCreation = new HashMap | ||
182 | for(type : p.types) { | ||
183 | recursiveObjectCreation.put(type,new LinkedList) | ||
184 | } | ||
185 | |||
186 | val containmentReferences = p.containmentHierarchies.head.containmentRelations | ||
187 | |||
188 | for(relationInterpretation : i.partialrelationinterpretation) { | ||
189 | val relation = relationInterpretation.interpretationOf | ||
190 | val lowermultiplicities = p.annotations.filter(LowerMultiplicityAssertion).filter[it.relation === relation] | ||
191 | if((!lowermultiplicities.empty)) { | ||
192 | val number = lowermultiplicities.head.lower | ||
193 | if(number > 0) { | ||
194 | val sourceTypeInterpretation = getTypeInterpretation(i, relation, 0) as PartialComplexTypeInterpretation | ||
195 | val subtypeInterpretations = i.partialtypeinterpratation.filter(PartialComplexTypeInterpretation).filter[ | ||
196 | it === sourceTypeInterpretation || | ||
197 | it.supertypeInterpretation.contains(sourceTypeInterpretation) | ||
198 | ] | ||
199 | |||
200 | if(containmentReferences.contains(relation)) { | ||
201 | val targetTypeInterpretation = getTypeInterpretation(i, relation, 1) | ||
202 | val targetType = (targetTypeInterpretation as PartialComplexTypeInterpretation).interpretationOf | ||
203 | if((!targetType.isIsAbstract) && (targetType.supertypes.empty)) { | ||
204 | val inverseAnnotation = p.annotations.filter(InverseRelationAssertion).filter[it.inverseA === relation || it.inverseB === relation] | ||
205 | if(!inverseAnnotation.empty) { | ||
206 | val onlyInverseAnnotation = if(inverseAnnotation.head.inverseA===relation) { | ||
207 | inverseAnnotation.head.inverseB | ||
208 | } else { | ||
209 | inverseAnnotation.head.inverseA | ||
210 | } | ||
211 | val inverseRelationInterpretation = i.partialrelationinterpretation.filter[it.interpretationOf === onlyInverseAnnotation].head | ||
212 | for(subTypeInterpretation : subtypeInterpretations) { | ||
213 | for(var times=0; times<number; times++) { | ||
214 | recursiveObjectCreation.get(subTypeInterpretation.interpretationOf) += | ||
215 | new ObjectCreationInterpretationData( | ||
216 | i, | ||
217 | targetTypeInterpretation, | ||
218 | relationInterpretation, | ||
219 | inverseRelationInterpretation, | ||
220 | targetTypeInterpretation.getTypeConstructor | ||
221 | ) | ||
222 | } | ||
223 | } | ||
224 | } else { | ||
225 | for(subTypeInterpretation : subtypeInterpretations) { | ||
226 | for(var times=0; times<number; times++) { | ||
227 | recursiveObjectCreation.get(subTypeInterpretation.interpretationOf) += | ||
228 | new ObjectCreationInterpretationData( | ||
229 | i, | ||
230 | targetTypeInterpretation, | ||
231 | relationInterpretation, | ||
232 | null, | ||
233 | targetTypeInterpretation.getTypeConstructor | ||
234 | ) | ||
235 | } | ||
236 | } | ||
237 | } | ||
238 | } | ||
239 | } else if(relation.parameters.get(1) instanceof PrimitiveTypeReference) { | ||
240 | val targetTypeInterpretation = getTypeInterpretation(i, relation, 1) | ||
241 | for(subTypeInterpretation : subtypeInterpretations) { | ||
242 | for(var times=0; times<number; times++) { | ||
243 | recursiveObjectCreation.get(subTypeInterpretation.interpretationOf) += | ||
244 | new ObjectCreationInterpretationData( | ||
245 | i, | ||
246 | targetTypeInterpretation, | ||
247 | relationInterpretation, | ||
248 | null, | ||
249 | targetTypeInterpretation.getTypeConstructor | ||
250 | ) | ||
251 | } | ||
252 | } | ||
253 | } | ||
254 | } | ||
255 | } | ||
256 | } | ||
257 | |||
258 | // Doing the recursion | ||
259 | var objectCreations = new LinkedList(recursiveObjectCreation.values.flatten.toList) | ||
260 | for(objectCreation : objectCreations) { | ||
261 | val newInterpretation = objectCreation.typeInterpretation | ||
262 | if(newInterpretation instanceof PartialComplexTypeInterpretation) { | ||
263 | val newlyCreatedType = newInterpretation.interpretationOf | ||
264 | if(recursiveObjectCreation.containsKey(newlyCreatedType)) { | ||
265 | val actionsWhenTypeCreated = recursiveObjectCreation.get(newlyCreatedType) | ||
266 | objectCreation.recursiveConstructors+=actionsWhenTypeCreated | ||
267 | } | ||
268 | } | ||
269 | } | ||
270 | |||
271 | // checking acyclicity | ||
272 | for(objectCreation : objectCreations) { | ||
273 | var reachable = objectCreation.recursiveConstructors | ||
274 | do { | ||
275 | if(reachable.contains(objectCreation)) { | ||
276 | throw new IllegalArgumentException('''Cicrle in the containment!''') | ||
277 | } else { | ||
278 | reachable = reachable.map[it.recursiveConstructors].flatten.toList | ||
279 | } | ||
280 | } while(!reachable.empty) | ||
281 | } | ||
282 | |||
283 | return recursiveObjectCreation | ||
284 | } | ||
285 | |||
286 | private def getTypeInterpretation(PartialInterpretation i, RelationDeclaration relation, int index) { | ||
287 | val typeReference = relation.parameters.get(index) | ||
288 | return getTypeInterpretation(i,typeReference) | ||
289 | |||
290 | } | ||
291 | private dispatch def getTypeInterpretation(PartialInterpretation i, ComplexTypeReference reference) { | ||
292 | return i.partialtypeinterpratation | ||
293 | .filter(PartialComplexTypeInterpretation) | ||
294 | .filter[it.getInterpretationOf == reference.referred] | ||
295 | .head | ||
296 | } | ||
297 | private dispatch def getTypeInterpretation(PartialInterpretation i, BoolTypeReference reference) { | ||
298 | return i.partialtypeinterpratation | ||
299 | .filter(PartialBooleanInterpretation) | ||
300 | .head | ||
301 | } | ||
302 | private dispatch def getTypeInterpretation(PartialInterpretation i, IntTypeReference reference) { | ||
303 | return i.partialtypeinterpratation | ||
304 | .filter(PartialIntegerInterpretation) | ||
305 | .head | ||
306 | } | ||
307 | private dispatch def getTypeInterpretation(PartialInterpretation i, RealTypeReference reference) { | ||
308 | return i.partialtypeinterpratation | ||
309 | .filter(PartialRealInterpretation) | ||
310 | .head | ||
311 | } | ||
312 | private dispatch def getTypeInterpretation(PartialInterpretation i, StringTypeReference reference) { | ||
313 | return i.partialtypeinterpratation | ||
314 | .filter(PartialStringInterpretation) | ||
315 | .head | ||
316 | } | ||
317 | private dispatch def Function0<DefinedElement> getTypeConstructor(PartialComplexTypeInterpretation reference) { [createDefinedElement] } | ||
318 | private dispatch def Function0<DefinedElement> getTypeConstructor(PartialBooleanInterpretation reference) { [createBooleanElement] } | ||
319 | private dispatch def Function0<DefinedElement> getTypeConstructor(PartialIntegerInterpretation reference) { [createIntegerElement] } | ||
320 | private dispatch def Function0<DefinedElement> getTypeConstructor(PartialRealInterpretation reference) { [createRealElement] } | ||
321 | private dispatch def Function0<DefinedElement> getTypeConstructor(PartialStringInterpretation reference) { [createStringElement] } | ||
322 | |||
323 | |||
185 | def createRelationRefinementRules(GeneratedPatterns patterns, ScopePropagator scopePropagator, ModelGenerationStatistics statistics) { | 324 | def createRelationRefinementRules(GeneratedPatterns patterns, ScopePropagator scopePropagator, ModelGenerationStatistics statistics) { |
186 | val res = new LinkedHashMap | 325 | val res = new LinkedHashMap |
187 | for(LHSEntry: patterns.refinerelationQueries.entrySet) { | 326 | for(LHSEntry: patterns.refinerelationQueries.entrySet) { |
@@ -197,11 +336,10 @@ class RefinementRuleProvider { | |||
197 | def private BatchTransformationRule<GenericPatternMatch, ViatraQueryMatcher<GenericPatternMatch>> | 336 | def private BatchTransformationRule<GenericPatternMatch, ViatraQueryMatcher<GenericPatternMatch>> |
198 | createRelationRefinementRule(RelationDeclaration declaration, Relation inverseRelation, IQuerySpecification<ViatraQueryMatcher<GenericPatternMatch>> lhs, ScopePropagator scopePropagator, ModelGenerationStatistics statistics) | 337 | createRelationRefinementRule(RelationDeclaration declaration, Relation inverseRelation, IQuerySpecification<ViatraQueryMatcher<GenericPatternMatch>> lhs, ScopePropagator scopePropagator, ModelGenerationStatistics statistics) |
199 | { | 338 | { |
200 | val name = '''addRelation_«declaration.name.canonizeName»«IF inverseRelation != null»_and_«inverseRelation.name.canonizeName»«ENDIF»''' | 339 | val name = '''addRelation_«declaration.name.canonizeName»«IF inverseRelation !== null»_and_«inverseRelation.name.canonizeName»«ENDIF»''' |
201 | val ruleBuilder = factory.createRule | 340 | val ruleBuilder = factory.createRule(lhs) |
202 | .name(name) | 341 | .name(name) |
203 | .precondition(lhs) | 342 | if (inverseRelation === null) { |
204 | if (inverseRelation == null) { | ||
205 | ruleBuilder.action [ match | | 343 | ruleBuilder.action [ match | |
206 | statistics.incrementTransformationCount | 344 | statistics.incrementTransformationCount |
207 | val startTime = System.nanoTime | 345 | val startTime = System.nanoTime |
@@ -211,8 +349,8 @@ class RefinementRuleProvider { | |||
211 | val relationInterpretation = match.get(2) as PartialRelationInterpretation | 349 | val relationInterpretation = match.get(2) as PartialRelationInterpretation |
212 | val src = match.get(3) as DefinedElement | 350 | val src = match.get(3) as DefinedElement |
213 | val trg = match.get(4) as DefinedElement | 351 | val trg = match.get(4) as DefinedElement |
214 | val link = createBinaryElementRelationLink => [it.param1 = src it.param2 = trg] | 352 | |
215 | relationInterpretation.relationlinks += link | 353 | createRelationLinkAction(src, trg, relationInterpretation) |
216 | 354 | ||
217 | val propagatorStartTime = System.nanoTime | 355 | val propagatorStartTime = System.nanoTime |
218 | statistics.addExecutionTime(propagatorStartTime-startTime) | 356 | statistics.addExecutionTime(propagatorStartTime-startTime) |
@@ -232,10 +370,8 @@ class RefinementRuleProvider { | |||
232 | val inverseInterpretation = match.get(3) as PartialRelationInterpretation | 370 | val inverseInterpretation = match.get(3) as PartialRelationInterpretation |
233 | val src = match.get(4) as DefinedElement | 371 | val src = match.get(4) as DefinedElement |
234 | val trg = match.get(5) as DefinedElement | 372 | val trg = match.get(5) as DefinedElement |
235 | val link = createBinaryElementRelationLink => [it.param1 = src it.param2 = trg] | 373 | |
236 | relationInterpretation.relationlinks += link | 374 | createRelationLinkWithInverse(src, trg, relationInterpretation, inverseInterpretation) |
237 | val inverseLink = createBinaryElementRelationLink => [it.param1 = trg it.param2 = src] | ||
238 | inverseInterpretation.relationlinks += inverseLink | ||
239 | 375 | ||
240 | val propagatorStartTime = System.nanoTime | 376 | val propagatorStartTime = System.nanoTime |
241 | statistics.addExecutionTime(propagatorStartTime-startTime) | 377 | statistics.addExecutionTime(propagatorStartTime-startTime) |
@@ -248,4 +384,182 @@ class RefinementRuleProvider { | |||
248 | 384 | ||
249 | return ruleBuilder.build | 385 | return ruleBuilder.build |
250 | } | 386 | } |
387 | |||
388 | ///////////////////////// | ||
389 | // Actions | ||
390 | ///////////////////////// | ||
391 | |||
392 | protected def void createObjectAction(boolean nameNewElement, ObjectCreationInterpretationData data, DefinedElement container, ScopePropagator scopePropagator) { | ||
393 | if(data.containerInterpretation !== null) { | ||
394 | if(data.containerInverseInterpretation !== null) { | ||
395 | createObjectActionWithContainmentAndInverse( | ||
396 | nameNewElement, | ||
397 | data.interpretation, | ||
398 | data.typeInterpretation, | ||
399 | container, | ||
400 | data.containerInterpretation, | ||
401 | data.containerInverseInterpretation, | ||
402 | data.constructor, | ||
403 | data.recursiveConstructors, | ||
404 | scopePropagator | ||
405 | ) | ||
406 | } else { | ||
407 | createObjectActionWithContainment( | ||
408 | nameNewElement, | ||
409 | data.interpretation, | ||
410 | data.typeInterpretation, | ||
411 | container, | ||
412 | data.containerInterpretation, | ||
413 | data.constructor, | ||
414 | data.recursiveConstructors, | ||
415 | scopePropagator | ||
416 | ) | ||
417 | } | ||
418 | } else { | ||
419 | createObjectAction( | ||
420 | nameNewElement, | ||
421 | data.interpretation, | ||
422 | data.typeInterpretation, | ||
423 | data.constructor, | ||
424 | data.recursiveConstructors, | ||
425 | scopePropagator | ||
426 | ) | ||
427 | } | ||
428 | |||
429 | } | ||
430 | |||
431 | protected def createObjectActionWithContainmentAndInverse( | ||
432 | boolean nameNewElement, | ||
433 | PartialInterpretation interpretation, | ||
434 | PartialTypeInterpratation typeInterpretation, | ||
435 | DefinedElement container, | ||
436 | PartialRelationInterpretation relationInterpretation, | ||
437 | PartialRelationInterpretation inverseRelationInterpretation, | ||
438 | Function0<DefinedElement> constructor, | ||
439 | List<ObjectCreationInterpretationData> recursiceObjectCreations, | ||
440 | ScopePropagator scopePropagator | ||
441 | ) { | ||
442 | val newElement = constructor.apply | ||
443 | if(nameNewElement) { | ||
444 | newElement.name = '''new «interpretation.newElements.size»''' | ||
445 | } | ||
446 | |||
447 | // Types | ||
448 | typeInterpretation.elements += newElement | ||
449 | if(typeInterpretation instanceof PartialComplexTypeInterpretation) { | ||
450 | typeInterpretation.supertypeInterpretation.forEach[it.elements += newElement] | ||
451 | } | ||
452 | // ContainmentRelation | ||
453 | val newLink1 = factory2.createBinaryElementRelationLink => [it.param1 = container it.param2 = newElement] | ||
454 | relationInterpretation.relationlinks+=newLink1 | ||
455 | // Inverse Containment | ||
456 | val newLink2 = factory2.createBinaryElementRelationLink => [it.param1 = newElement it.param2 = container] | ||
457 | inverseRelationInterpretation.relationlinks+=newLink2 | ||
458 | |||
459 | // Scope propagation | ||
460 | scopePropagator.decrementTypeScope(typeInterpretation) | ||
461 | |||
462 | // Existence | ||
463 | interpretation.newElements+=newElement | ||
464 | |||
465 | // Do recursive object creation | ||
466 | for(newConstructor : recursiceObjectCreations) { | ||
467 | createObjectAction(nameNewElement,newConstructor,newElement,scopePropagator) | ||
468 | } | ||
469 | |||
470 | return newElement | ||
471 | } | ||
472 | |||
473 | protected def createObjectActionWithContainment( | ||
474 | boolean nameNewElement, | ||
475 | PartialInterpretation interpretation, | ||
476 | PartialTypeInterpratation typeInterpretation, | ||
477 | DefinedElement container, | ||
478 | PartialRelationInterpretation relationInterpretation, | ||
479 | Function0<DefinedElement> constructor, | ||
480 | List<ObjectCreationInterpretationData> recursiceObjectCreations, | ||
481 | ScopePropagator scopePropagator | ||
482 | ) { | ||
483 | val newElement = constructor.apply | ||
484 | if(nameNewElement) { | ||
485 | newElement.name = '''new «interpretation.newElements.size»''' | ||
486 | } | ||
487 | |||
488 | // Types | ||
489 | typeInterpretation.elements += newElement | ||
490 | if(typeInterpretation instanceof PartialComplexTypeInterpretation) { | ||
491 | typeInterpretation.supertypeInterpretation.forEach[it.elements += newElement] | ||
492 | } | ||
493 | // ContainmentRelation | ||
494 | val newLink = factory2.createBinaryElementRelationLink => [it.param1 = container it.param2 = newElement] | ||
495 | relationInterpretation.relationlinks+=newLink | ||
496 | |||
497 | // Scope propagation | ||
498 | scopePropagator.decrementTypeScope(typeInterpretation) | ||
499 | |||
500 | // Existence | ||
501 | interpretation.newElements+=newElement | ||
502 | |||
503 | // Do recursive object creation | ||
504 | for(newConstructor : recursiceObjectCreations) { | ||
505 | createObjectAction(nameNewElement,newConstructor,newElement,scopePropagator) | ||
506 | } | ||
507 | |||
508 | return newElement | ||
509 | } | ||
510 | |||
511 | protected def createObjectAction( | ||
512 | boolean nameNewElement, | ||
513 | PartialInterpretation interpretation, | ||
514 | PartialTypeInterpratation typeInterpretation, | ||
515 | Function0<DefinedElement> constructor, | ||
516 | List<ObjectCreationInterpretationData> recursiceObjectCreations, | ||
517 | ScopePropagator scopePropagator) | ||
518 | { | ||
519 | val newElement = constructor.apply | ||
520 | if(nameNewElement) { | ||
521 | newElement.name = '''new «interpretation.newElements.size»''' | ||
522 | } | ||
523 | |||
524 | // Types | ||
525 | typeInterpretation.elements += newElement | ||
526 | if(typeInterpretation instanceof PartialComplexTypeInterpretation) { | ||
527 | typeInterpretation.supertypeInterpretation.forEach[it.elements += newElement] | ||
528 | } | ||
529 | |||
530 | // Scope propagation | ||
531 | scopePropagator.decrementTypeScope(typeInterpretation) | ||
532 | |||
533 | // Existence | ||
534 | interpretation.newElements+=newElement | ||
535 | |||
536 | // Do recursive object creation | ||
537 | for(newConstructor : recursiceObjectCreations) { | ||
538 | createObjectAction(nameNewElement,newConstructor,newElement,scopePropagator) | ||
539 | } | ||
540 | |||
541 | return newElement | ||
542 | } | ||
543 | |||
544 | protected def boolean createRelationLinkAction(DefinedElement src, DefinedElement trg, PartialRelationInterpretation relationInterpretation) { | ||
545 | val link = createBinaryElementRelationLink => [it.param1 = src it.param2 = trg] | ||
546 | relationInterpretation.relationlinks += link | ||
547 | } | ||
548 | |||
549 | protected def boolean createRelationLinkWithInverse(DefinedElement src, DefinedElement trg, PartialRelationInterpretation relationInterpretation, PartialRelationInterpretation inverseInterpretation) { | ||
550 | val link = createBinaryElementRelationLink => [it.param1 = src it.param2 = trg] | ||
551 | relationInterpretation.relationlinks += link | ||
552 | val inverseLink = createBinaryElementRelationLink => [it.param1 = trg it.param2 = src] | ||
553 | inverseInterpretation.relationlinks += inverseLink | ||
554 | } | ||
555 | } | ||
556 | |||
557 | @Data | ||
558 | class ObjectCreationInterpretationData { | ||
559 | PartialInterpretation interpretation | ||
560 | PartialTypeInterpratation typeInterpretation | ||
561 | PartialRelationInterpretation containerInterpretation | ||
562 | PartialRelationInterpretation containerInverseInterpretation | ||
563 | Function0<DefinedElement> constructor | ||
564 | List<ObjectCreationInterpretationData> recursiveConstructors = new LinkedList | ||
251 | } | 565 | } |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/util/ParseUtil.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/util/ParseUtil.xtend index 8e264488..26ec7091 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/util/ParseUtil.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/util/ParseUtil.xtend | |||
@@ -196,8 +196,20 @@ class ParseUtil { | |||
196 | } | 196 | } |
197 | 197 | ||
198 | class FixedMetamodelProvider implements IMetamodelProvider { | 198 | class FixedMetamodelProvider implements IMetamodelProvider { |
199 | |||
200 | static val EPACKAGE_TO_PLUGIN_MAP = #{ | ||
201 | PartialinterpretationPackage.eINSTANCE -> "hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage", | ||
202 | LogicproblemPackage.eINSTANCE -> "hu.bme.mit.inf.dslreasoner.logic.model", | ||
203 | LogiclanguagePackage.eINSTANCE -> "hu.bme.mit.inf.dslreasoner.logic.model" | ||
204 | } | ||
205 | |||
206 | static val EPACKAGE_TO_JAVA_PACKAGE_MAP = #{ | ||
207 | PartialinterpretationPackage.eINSTANCE -> "hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation", | ||
208 | LogicproblemPackage.eINSTANCE -> "hu.bme.mit.inf.dslreasoner.logic.model.logicproblem", | ||
209 | LogiclanguagePackage.eINSTANCE -> "hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage" | ||
210 | } | ||
199 | 211 | ||
200 | protected val List<EPackage> packages = new LinkedList | 212 | val List<EPackage> packages = new LinkedList |
201 | 213 | ||
202 | new() { | 214 | new() { |
203 | packages += PartialinterpretationPackage.eINSTANCE | 215 | packages += PartialinterpretationPackage.eINSTANCE |
@@ -213,15 +225,24 @@ class FixedMetamodelProvider implements IMetamodelProvider { | |||
213 | } | 225 | } |
214 | 226 | ||
215 | override boolean isGeneratedCodeAvailable(EPackage ePackage, ResourceSet set) { | 227 | override boolean isGeneratedCodeAvailable(EPackage ePackage, ResourceSet set) { |
216 | true | 228 | EPACKAGE_TO_PLUGIN_MAP.containsKey(ePackage) |
217 | } | 229 | } |
218 | 230 | ||
219 | override String getModelPluginId(EPackage ePackage, ResourceSet set) { | 231 | override String getModelPluginId(EPackage ePackage, ResourceSet set) { |
220 | return "hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage" | 232 | EPACKAGE_TO_PLUGIN_MAP.get(ePackage) |
221 | } | 233 | } |
222 | 234 | ||
223 | override String getQualifiedClassName(EClassifier classifier, EObject context) { | 235 | override String getQualifiedClassName(EClassifier classifier, EObject context) { |
224 | classifier.name | 236 | val instanceClassName = classifier.instanceClassName |
237 | if (instanceClassName !== null) { | ||
238 | return instanceClassName | ||
239 | } | ||
240 | val javaPackage = EPACKAGE_TO_JAVA_PACKAGE_MAP.get(classifier.EPackage) | ||
241 | if (javaPackage !== null) { | ||
242 | javaPackage + "." + classifier.name | ||
243 | } else { | ||
244 | null | ||
245 | } | ||
225 | } | 246 | } |
226 | 247 | ||
227 | override loadEPackage(String uri, ResourceSet resourceSet) { | 248 | override loadEPackage(String uri, ResourceSet resourceSet) { |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/PartialInterpretationInitialiser.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/PartialInterpretationInitialiser.xtend index f7a1ce4f..d37acb6d 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/PartialInterpretationInitialiser.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/PartialInterpretationInitialiser.xtend | |||
@@ -42,6 +42,7 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.IntLiteral | |||
42 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RealLiteral | 42 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RealLiteral |
43 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.StringLiteral | 43 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.StringLiteral |
44 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialTypeInterpratation | 44 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialTypeInterpratation |
45 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RelationDefinition | ||
45 | 46 | ||
46 | @Data class Problem2PartialInterpretationTrace { | 47 | @Data class Problem2PartialInterpretationTrace { |
47 | Map<TypeDeclaration, PartialComplexTypeInterpretation> type2Interpretation | 48 | Map<TypeDeclaration, PartialComplexTypeInterpretation> type2Interpretation |
@@ -233,7 +234,11 @@ class PartialInterpretationInitialiser { | |||
233 | 234 | ||
234 | def private Map<RelationDeclaration, PartialRelationInterpretation> initRelations(PartialInterpretation interpretation, PrimitiveValueTrace trace) { | 235 | def private Map<RelationDeclaration, PartialRelationInterpretation> initRelations(PartialInterpretation interpretation, PrimitiveValueTrace trace) { |
235 | val Map<RelationDeclaration, PartialRelationInterpretation> relation2Interpretation = new HashMap | 236 | val Map<RelationDeclaration, PartialRelationInterpretation> relation2Interpretation = new HashMap |
236 | for(relation : interpretation.problem.relations.filter(RelationDeclaration)) { | 237 | val definedRelationDeclarations = interpretation.problem.relations.filter(RelationDefinition).map[defines] |
238 | val undefinedRelationDeclarations = interpretation.problem.relations.filter(RelationDeclaration).filter[ | ||
239 | declared | !definedRelationDeclarations.exists[defined | defined === declared] | ||
240 | ] | ||
241 | for(relation : undefinedRelationDeclarations) { | ||
237 | val partialInterpretation = relation.initialisePartialRelationInterpretation | 242 | val partialInterpretation = relation.initialisePartialRelationInterpretation |
238 | interpretation.partialrelationinterpretation += partialInterpretation | 243 | interpretation.partialrelationinterpretation += partialInterpretation |
239 | relation2Interpretation.put(relation,partialInterpretation) | 244 | relation2Interpretation.put(relation,partialInterpretation) |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/visualisation/PartialInterpretation2Gml.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/visualisation/PartialInterpretation2Gml.xtend index 2b42a8b1..bdf402f3 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/visualisation/PartialInterpretation2Gml.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/visualisation/PartialInterpretation2Gml.xtend | |||
@@ -5,9 +5,13 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Relation | |||
5 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type | 5 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type |
6 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeDefinition | 6 | import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeDefinition |
7 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.BinaryElementRelationLink | 7 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.BinaryElementRelationLink |
8 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.BooleanElement | ||
9 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.IntegerElement | ||
8 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialComplexTypeInterpretation | 10 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialComplexTypeInterpretation |
9 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation | 11 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation |
10 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialRelationInterpretation | 12 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialRelationInterpretation |
13 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.RealElement | ||
14 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.StringElement | ||
11 | import java.util.HashMap | 15 | import java.util.HashMap |
12 | import java.util.Map | 16 | import java.util.Map |
13 | import java.util.Set | 17 | import java.util.Set |
@@ -106,10 +110,38 @@ class PartialInterpretation2Gml { | |||
106 | ''' | 110 | ''' |
107 | } | 111 | } |
108 | 112 | ||
109 | def protected transormTitle(DefinedElement object) { | 113 | def protected dispatch transormTitle(DefinedElement object) { |
110 | if(object.name!= null)object.name | 114 | if(object.name !== null) object.name.replace("\"", "") |
111 | else "null" | 115 | else "null" |
112 | } | 116 | } |
117 | def protected dispatch transormTitle(BooleanElement object) { | ||
118 | if(object.valueSet) { | ||
119 | object.value.toString | ||
120 | } else { | ||
121 | "?" | ||
122 | } | ||
123 | } | ||
124 | def protected dispatch transormTitle(IntegerElement object) { | ||
125 | if(object.valueSet) { | ||
126 | object.value.toString | ||
127 | } else { | ||
128 | "?" | ||
129 | } | ||
130 | } | ||
131 | def protected dispatch transormTitle(RealElement object) { | ||
132 | if(object.valueSet) { | ||
133 | object.value.toString | ||
134 | } else { | ||
135 | "?" | ||
136 | } | ||
137 | } | ||
138 | def protected dispatch transormTitle(StringElement object) { | ||
139 | if(object.valueSet) { | ||
140 | object.value.toString | ||
141 | } else { | ||
142 | "?" | ||
143 | } | ||
144 | } | ||
113 | 145 | ||
114 | def protected transformLink( | 146 | def protected transformLink( |
115 | PartialRelationInterpretation reference, | 147 | PartialRelationInterpretation reference, |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ModelGenerationMethodBasedGlobalConstraint.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ModelGenerationMethodBasedGlobalConstraint.xtend index 28cf986d..9ef5e091 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ModelGenerationMethodBasedGlobalConstraint.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ModelGenerationMethodBasedGlobalConstraint.xtend | |||
@@ -1,11 +1,11 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner | 1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner |
2 | 2 | ||
3 | import org.eclipse.viatra.dse.objectives.IGlobalConstraint | 3 | import org.eclipse.viatra.dse.objectives.IGlobalConstraint |
4 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod | 4 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod |
5 | 5 | ||
6 | abstract class ModelGenerationMethodBasedGlobalConstraint implements IGlobalConstraint { | 6 | abstract class ModelGenerationMethodBasedGlobalConstraint implements IGlobalConstraint { |
7 | val protected ModelGenerationMethod method | 7 | val protected ModelGenerationMethod method |
8 | new(ModelGenerationMethod method) { | 8 | new(ModelGenerationMethod method) { |
9 | this.method = method | 9 | this.method = method |
10 | } | 10 | } |
11 | } \ No newline at end of file | 11 | } |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasoner.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasoner.xtend index aa02cd30..3033eca7 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasoner.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasoner.xtend | |||
@@ -42,6 +42,7 @@ import org.eclipse.viatra.dse.api.DesignSpaceExplorer | |||
42 | import org.eclipse.viatra.dse.api.DesignSpaceExplorer.DseLoggingLevel | 42 | import org.eclipse.viatra.dse.api.DesignSpaceExplorer.DseLoggingLevel |
43 | import org.eclipse.viatra.dse.solutionstore.SolutionStore | 43 | import org.eclipse.viatra.dse.solutionstore.SolutionStore |
44 | import org.eclipse.viatra.dse.statecode.IStateCoderFactory | 44 | import org.eclipse.viatra.dse.statecode.IStateCoderFactory |
45 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.NumericSolver | ||
45 | 46 | ||
46 | class ViatraReasoner extends LogicReasoner { | 47 | class ViatraReasoner extends LogicReasoner { |
47 | val PartialInterpretationInitialiser initialiser = new PartialInterpretationInitialiser() | 48 | val PartialInterpretationInitialiser initialiser = new PartialInterpretationInitialiser() |
@@ -66,12 +67,12 @@ class ViatraReasoner extends LogicReasoner { | |||
66 | dse.addMetaModelPackage(PartialinterpretationPackage.eINSTANCE) | 67 | dse.addMetaModelPackage(PartialinterpretationPackage.eINSTANCE) |
67 | 68 | ||
68 | val transformationStartTime = System.nanoTime | 69 | val transformationStartTime = System.nanoTime |
69 | |||
70 | val emptySolution = initialiser.initialisePartialInterpretation(problem, viatraConfig.typeScopes).output | 70 | val emptySolution = initialiser.initialisePartialInterpretation(problem, viatraConfig.typeScopes).output |
71 | if ((viatraConfig.documentationLevel == DocumentationLevel::FULL || | 71 | if ((viatraConfig.documentationLevel == DocumentationLevel::FULL || |
72 | viatraConfig.documentationLevel == DocumentationLevel::NORMAL) && workspace !== null) { | 72 | viatraConfig.documentationLevel == DocumentationLevel::NORMAL) && workspace !== null) { |
73 | workspace.writeModel(emptySolution, "init.partialmodel") | 73 | workspace.writeModel(emptySolution, "init.partialmodel") |
74 | } | 74 | } |
75 | |||
75 | emptySolution.problemConainer = problem | 76 | emptySolution.problemConainer = problem |
76 | var BasicScopeGlobalConstraint basicScopeGlobalConstraint = null | 77 | var BasicScopeGlobalConstraint basicScopeGlobalConstraint = null |
77 | if (viatraConfig.scopePropagatorStrategy == ScopePropagatorStrategy.None) { | 78 | if (viatraConfig.scopePropagatorStrategy == ScopePropagatorStrategy.None) { |
@@ -93,7 +94,8 @@ class ViatraReasoner extends LogicReasoner { | |||
93 | dse.addObjective(new ModelGenerationCompositeObjective( | 94 | dse.addObjective(new ModelGenerationCompositeObjective( |
94 | basicScopeGlobalConstraint ?: new ScopeObjective, | 95 | basicScopeGlobalConstraint ?: new ScopeObjective, |
95 | method.unfinishedMultiplicities.map[new UnfinishedMultiplicityObjective(it)], | 96 | method.unfinishedMultiplicities.map[new UnfinishedMultiplicityObjective(it)], |
96 | wf2ObjectiveConverter.createCompletenessObjective(method.unfinishedWF) | 97 | wf2ObjectiveConverter.createCompletenessObjective(method.unfinishedWF), |
98 | viatraConfig | ||
97 | )) | 99 | )) |
98 | 100 | ||
99 | val extremalObjectives = Lists.newArrayListWithExpectedSize(viatraConfig.costObjectives.size) | 101 | val extremalObjectives = Lists.newArrayListWithExpectedSize(viatraConfig.costObjectives.size) |
@@ -131,8 +133,9 @@ class ViatraReasoner extends LogicReasoner { | |||
131 | } | 133 | } |
132 | solutionStore.registerSolutionFoundHandler(new LoggerSolutionFoundHandler(viatraConfig)) | 134 | solutionStore.registerSolutionFoundHandler(new LoggerSolutionFoundHandler(viatraConfig)) |
133 | val diversityChecker = DiversityChecker.of(viatraConfig.diversityRequirement) | 135 | val diversityChecker = DiversityChecker.of(viatraConfig.diversityRequirement) |
136 | val numericSolver = new NumericSolver(method, viatraConfig.runIntermediateNumericalConsistencyChecks, false) | ||
134 | val solutionSaver = new ViatraReasonerSolutionSaver(newArrayList(extremalObjectives), numberOfRequiredSolutions, | 137 | val solutionSaver = new ViatraReasonerSolutionSaver(newArrayList(extremalObjectives), numberOfRequiredSolutions, |
135 | diversityChecker) | 138 | diversityChecker, numericSolver) |
136 | val solutionCopier = solutionSaver.solutionCopier | 139 | val solutionCopier = solutionSaver.solutionCopier |
137 | solutionStore.withSolutionSaver(solutionSaver) | 140 | solutionStore.withSolutionSaver(solutionSaver) |
138 | dse.solutionStore = solutionStore | 141 | dse.solutionStore = solutionStore |
@@ -168,10 +171,10 @@ class ViatraReasoner extends LogicReasoner { | |||
168 | dse.addTransformationRule(rule) | 171 | dse.addTransformationRule(rule) |
169 | } | 172 | } |
170 | 173 | ||
171 | val strategy = new BestFirstStrategyForModelGeneration(workspace, viatraConfig, method) | 174 | val strategy = new BestFirstStrategyForModelGeneration(workspace, viatraConfig, method, solutionSaver, numericSolver) |
172 | viatraConfig.progressMonitor.workedForwardTransformation | 175 | viatraConfig.progressMonitor.workedForwardTransformation |
173 | 176 | val transformationFinished = System.nanoTime | |
174 | val transformationTime = System.nanoTime - transformationStartTime | 177 | val transformationTime = transformationFinished - transformationStartTime |
175 | val solverStartTime = System.nanoTime | 178 | val solverStartTime = System.nanoTime |
176 | 179 | ||
177 | var boolean stoppedByTimeout | 180 | var boolean stoppedByTimeout |
@@ -194,6 +197,15 @@ class ViatraReasoner extends LogicReasoner { | |||
194 | it.value = (pair.value / 1000000) as int | 197 | it.value = (pair.value / 1000000) as int |
195 | ] | 198 | ] |
196 | } | 199 | } |
200 | for(x: 0..<strategy.times.size) { | ||
201 | it.entries += createStringStatisticEntry => [ | ||
202 | it.name = '''Solution«x+1»DetailedStatistics''' | ||
203 | it.value = strategy.times.get(x) | ||
204 | ] | ||
205 | } | ||
206 | it.entries += createIntStatisticEntry => [ | ||
207 | it.name = "ExplorationInitializationTime" it.value = ((strategy.explorationStarted-transformationFinished)/1000000) as int | ||
208 | ] | ||
197 | it.entries += createIntStatisticEntry => [ | 209 | it.entries += createIntStatisticEntry => [ |
198 | it.name = "TransformationExecutionTime" | 210 | it.name = "TransformationExecutionTime" |
199 | it.value = (method.statistics.transformationExecutionTime / 1000000) as int | 211 | it.value = (method.statistics.transformationExecutionTime / 1000000) as int |
@@ -223,6 +235,24 @@ class ViatraReasoner extends LogicReasoner { | |||
223 | it.value = dse.numberOfStates as int | 235 | it.value = dse.numberOfStates as int |
224 | ] | 236 | ] |
225 | it.entries += createIntStatisticEntry => [ | 237 | it.entries += createIntStatisticEntry => [ |
238 | it.name = "ForwardTime" it.value = (strategy.forwardTime/1000000) as int | ||
239 | ] | ||
240 | it.entries += createIntStatisticEntry => [ | ||
241 | it.name = "BacktrackingTime" it.value = (strategy.backtrackingTime/1000000) as int | ||
242 | ] | ||
243 | it.entries += createIntStatisticEntry => [ | ||
244 | it.name = "GlobalConstraintEvaluationTime" it.value = (strategy.globalConstraintEvaluationTime/1000000) as int | ||
245 | ] | ||
246 | it.entries += createIntStatisticEntry => [ | ||
247 | it.name = "FitnessCalculationTime" it.value = (strategy.fitnessCalculationTime/1000000) as int | ||
248 | ] | ||
249 | it.entries += createIntStatisticEntry => [ | ||
250 | it.name = "SolutionCopyTime" it.value = (solutionSaver.totalCopierRuntime/1000000) as int | ||
251 | ] | ||
252 | it.entries += createIntStatisticEntry => [ | ||
253 | it.name = "ActivationSelectionTime" it.value = (strategy.activationSelector.runtime/1000000) as int | ||
254 | ] | ||
255 | it.entries += createIntStatisticEntry => [ | ||
226 | it.name = "Decisions" | 256 | it.name = "Decisions" |
227 | it.value = method.statistics.decisionsTried | 257 | it.value = method.statistics.decisionsTried |
228 | ] | 258 | ] |
@@ -238,7 +268,28 @@ class ViatraReasoner extends LogicReasoner { | |||
238 | it.name = "ScopePropagationsSolverCalls" | 268 | it.name = "ScopePropagationsSolverCalls" |
239 | it.value = method.statistics.scopePropagatorSolverInvocations | 269 | it.value = method.statistics.scopePropagatorSolverInvocations |
240 | ] | 270 | ] |
241 | if (diversityChecker.isActive) { | 271 | it.entries += createIntStatisticEntry => [ |
272 | it.name = "NumericalSolverSumTime" it.value = (strategy.numericSolver.runtime/1000000) as int | ||
273 | ] | ||
274 | it.entries += createIntStatisticEntry => [ | ||
275 | it.name = "NumericalSolverProblemFormingTime" it.value = (strategy.numericSolver.solverFormingProblem/1000000) as int | ||
276 | ] | ||
277 | it.entries += createIntStatisticEntry => [ | ||
278 | it.name = "NumericalSolverSolvingTime" it.value = (strategy.numericSolver.solverSolvingProblem/1000000) as int | ||
279 | ] | ||
280 | it.entries += createIntStatisticEntry => [ | ||
281 | it.name = "NumericalSolverInterpretingSolution" it.value = (strategy.numericSolver.solverSolution/1000000) as int | ||
282 | ] | ||
283 | it.entries += createIntStatisticEntry => [ | ||
284 | it.name = "NumericalSolverCachingTime" it.value = (strategy.numericSolver.cachingTime/1000000) as int | ||
285 | ] | ||
286 | it.entries += createIntStatisticEntry => [ | ||
287 | it.name = "NumericalSolverCallNumber" it.value = strategy.numericSolver.numberOfSolverCalls | ||
288 | ] | ||
289 | it.entries += createIntStatisticEntry => [ | ||
290 | it.name = "NumericalSolverCachedAnswerNumber" it.value = strategy.numericSolver.numberOfCachedSolverCalls | ||
291 | ] | ||
292 | if(diversityChecker.active) { | ||
242 | it.entries += createIntStatisticEntry => [ | 293 | it.entries += createIntStatisticEntry => [ |
243 | it.name = "SolutionDiversityCheckTime" | 294 | it.name = "SolutionDiversityCheckTime" |
244 | it.value = (diversityChecker.totalRuntime / 1000000) as int | 295 | it.value = (diversityChecker.totalRuntime / 1000000) as int |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasonerConfiguration.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasonerConfiguration.xtend index c0a71c85..ddd25aac 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasonerConfiguration.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasonerConfiguration.xtend | |||
@@ -54,8 +54,16 @@ class ViatraReasonerConfiguration extends LogicSolverConfiguration { | |||
54 | * Configuration for cutting search space. | 54 | * Configuration for cutting search space. |
55 | */ | 55 | */ |
56 | public var SearchSpaceConstraint searchSpaceConstraints = new SearchSpaceConstraint | 56 | public var SearchSpaceConstraint searchSpaceConstraints = new SearchSpaceConstraint |
57 | 57 | ||
58 | public var ScopePropagatorStrategy scopePropagatorStrategy = ScopePropagatorStrategy.Polyhedral( | 58 | public var runIntermediateNumericalConsistencyChecks = true |
59 | |||
60 | public var punishSize = true | ||
61 | public var scopeWeight = 1 | ||
62 | public var conaintmentWeight = 2 | ||
63 | public var nonContainmentWeight = 1 | ||
64 | public var unfinishedWFWeight = 1 | ||
65 | |||
66 | public var ScopePropagatorStrategy scopePropagatorStrategy = new ScopePropagatorStrategy.Polyhedral( | ||
59 | PolyhedralScopePropagatorConstraints.Relational, PolyhedralScopePropagatorSolver.Clp) | 67 | PolyhedralScopePropagatorConstraints.Relational, PolyhedralScopePropagatorSolver.Clp) |
60 | 68 | ||
61 | public var List<LinearTypeConstraintHint> hints = newArrayList | 69 | public var List<LinearTypeConstraintHint> hints = newArrayList |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ActivationSelector.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ActivationSelector.xtend new file mode 100644 index 00000000..65f9814c --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ActivationSelector.xtend | |||
@@ -0,0 +1,24 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse | ||
2 | |||
3 | import java.util.ArrayList | ||
4 | import java.util.Collection | ||
5 | import java.util.Random | ||
6 | |||
7 | abstract class ActivationSelector { | ||
8 | long runtime = 0 | ||
9 | protected val Random r | ||
10 | new(Random r) { | ||
11 | this.r = r | ||
12 | } | ||
13 | |||
14 | def randomizeActivationIDs(Collection<Object> activationIDs) { | ||
15 | val startTime = System.nanoTime | ||
16 | val res = internalRandomizationOfActivationIDs(activationIDs) | ||
17 | runtime+= System.nanoTime-startTime | ||
18 | return res | ||
19 | } | ||
20 | def protected ArrayList<Object> internalRandomizationOfActivationIDs(Collection<Object> activationIDs); | ||
21 | def getRuntime(){ | ||
22 | return runtime | ||
23 | } | ||
24 | } \ No newline at end of file | ||
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BalancedActivationSelector.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BalancedActivationSelector.xtend new file mode 100644 index 00000000..2df9957b --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BalancedActivationSelector.xtend | |||
@@ -0,0 +1,51 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse | ||
2 | |||
3 | import java.util.Collection | ||
4 | import java.util.HashMap | ||
5 | import java.util.Map | ||
6 | import java.util.List | ||
7 | import java.util.Random | ||
8 | import java.util.ArrayList | ||
9 | import java.util.LinkedList | ||
10 | import java.util.Collections | ||
11 | |||
12 | class BalancedActivationSelector extends ActivationSelector{ | ||
13 | val Random r = new Random | ||
14 | |||
15 | new(Random r) { | ||
16 | super(r) | ||
17 | } | ||
18 | |||
19 | override protected internalRandomizationOfActivationIDs(Collection<Object> activationIDs) { | ||
20 | val Map<String,List<Object>> urns = new HashMap | ||
21 | val res = new ArrayList(activationIDs.size) | ||
22 | for(activationID : activationIDs) { | ||
23 | val pair = activationID as Pair<String,? extends Object> | ||
24 | val name = pair.key | ||
25 | val selectedUrn = urns.get(name) | ||
26 | if(selectedUrn!==null) { | ||
27 | selectedUrn.add(activationID) | ||
28 | } else { | ||
29 | val collection = new LinkedList | ||
30 | collection.add(activationID) | ||
31 | urns.put(name,collection) | ||
32 | } | ||
33 | } | ||
34 | |||
35 | for(list:urns.values) { | ||
36 | Collections.shuffle(list,r) | ||
37 | } | ||
38 | |||
39 | while(!urns.empty) { | ||
40 | val randomEntry = urns.entrySet.get(r.nextInt(urns.size)) | ||
41 | val list = randomEntry.value | ||
42 | val removedLast = list.remove(list.size-1) | ||
43 | res.add(removedLast) | ||
44 | if(list.empty) { | ||
45 | urns.remove(randomEntry.key) | ||
46 | } | ||
47 | } | ||
48 | return res | ||
49 | } | ||
50 | |||
51 | } \ No newline at end of file | ||
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BestFirstStrategyForModelGeneration.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BestFirstStrategyForModelGeneration.java index 081e48fa..e529892c 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BestFirstStrategyForModelGeneration.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BestFirstStrategyForModelGeneration.java | |||
@@ -9,9 +9,7 @@ | |||
9 | *******************************************************************************/ | 9 | *******************************************************************************/ |
10 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse; | 10 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse; |
11 | 11 | ||
12 | import java.util.ArrayList; | ||
13 | import java.util.Arrays; | 12 | import java.util.Arrays; |
14 | import java.util.Collection; | ||
15 | import java.util.Collections; | 13 | import java.util.Collections; |
16 | import java.util.Comparator; | 14 | import java.util.Comparator; |
17 | import java.util.Iterator; | 15 | import java.util.Iterator; |
@@ -23,15 +21,13 @@ import java.util.Random; | |||
23 | import org.apache.log4j.Logger; | 21 | import org.apache.log4j.Logger; |
24 | import org.eclipse.emf.ecore.EObject; | 22 | import org.eclipse.emf.ecore.EObject; |
25 | import org.eclipse.emf.ecore.util.EcoreUtil; | 23 | import org.eclipse.emf.ecore.util.EcoreUtil; |
24 | import org.eclipse.viatra.dse.api.SolutionTrajectory; | ||
26 | import org.eclipse.viatra.dse.api.strategy.interfaces.IStrategy; | 25 | import org.eclipse.viatra.dse.api.strategy.interfaces.IStrategy; |
27 | import org.eclipse.viatra.dse.base.ThreadContext; | 26 | import org.eclipse.viatra.dse.base.ThreadContext; |
28 | import org.eclipse.viatra.dse.objectives.Fitness; | 27 | import org.eclipse.viatra.dse.objectives.Fitness; |
29 | import org.eclipse.viatra.dse.objectives.ObjectiveComparatorHelper; | 28 | import org.eclipse.viatra.dse.objectives.ObjectiveComparatorHelper; |
29 | import org.eclipse.viatra.dse.solutionstore.ISolutionFoundHandler; | ||
30 | import org.eclipse.viatra.dse.solutionstore.SolutionStore; | 30 | import org.eclipse.viatra.dse.solutionstore.SolutionStore; |
31 | import org.eclipse.viatra.query.runtime.api.IPatternMatch; | ||
32 | import org.eclipse.viatra.query.runtime.api.IQuerySpecification; | ||
33 | import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine; | ||
34 | import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher; | ||
35 | 31 | ||
36 | import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel; | 32 | import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel; |
37 | import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasoner; | 33 | import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasoner; |
@@ -42,6 +38,7 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult; | |||
42 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod; | 38 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod; |
43 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic.PartialInterpretation2Logic; | 39 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic.PartialInterpretation2Logic; |
44 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation; | 40 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation; |
41 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.NeighbourhoodBasedPartialInterpretationStateCoder; | ||
45 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualisation; | 42 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualisation; |
46 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualiser; | 43 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualiser; |
47 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration; | 44 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration; |
@@ -79,41 +76,70 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { | |||
79 | private volatile boolean isInterrupted = false; | 76 | private volatile boolean isInterrupted = false; |
80 | private ModelResult modelResultByInternalSolver = null; | 77 | private ModelResult modelResultByInternalSolver = null; |
81 | private Random random = new Random(); | 78 | private Random random = new Random(); |
82 | private Collection<ViatraQueryMatcher<? extends IPatternMatch>> matchers; | 79 | //private Collection<ViatraQueryMatcher<? extends IPatternMatch>> matchers; |
83 | 80 | public ActivationSelector activationSelector = new EvenActivationSelector(random); | |
81 | public ViatraReasonerSolutionSaver solutionSaver; | ||
82 | public NumericSolver numericSolver; | ||
84 | // Statistics | 83 | // Statistics |
85 | private int numberOfStatecoderFail = 0; | 84 | private int numberOfStatecoderFail = 0; |
86 | private int numberOfPrintedModel = 0; | 85 | private int numberOfPrintedModel = 0; |
87 | private int numberOfSolverCalls = 0; | 86 | private int numberOfSolverCalls = 0; |
87 | public long globalConstraintEvaluationTime = 0; | ||
88 | public long fitnessCalculationTime = 0; | ||
89 | |||
90 | public long explorationStarted = 0; | ||
88 | 91 | ||
89 | public BestFirstStrategyForModelGeneration( | 92 | public BestFirstStrategyForModelGeneration( |
90 | ReasonerWorkspace workspace, | 93 | ReasonerWorkspace workspace, |
91 | ViatraReasonerConfiguration configuration, | 94 | ViatraReasonerConfiguration configuration, |
92 | ModelGenerationMethod method) | 95 | ModelGenerationMethod method, |
93 | { | 96 | ViatraReasonerSolutionSaver solutionSaver, |
97 | NumericSolver numericSolver) { | ||
94 | this.workspace = workspace; | 98 | this.workspace = workspace; |
95 | this.configuration = configuration; | 99 | this.configuration = configuration; |
96 | this.method = method; | 100 | this.method = method; |
101 | this.solutionSaver = solutionSaver; | ||
102 | this.numericSolver = numericSolver; | ||
97 | //logger.setLevel(Level.DEBUG); | 103 | //logger.setLevel(Level.DEBUG); |
98 | } | 104 | } |
99 | 105 | ||
100 | public int getNumberOfStatecoderFail() { | 106 | public int getNumberOfStatecoderFail() { |
101 | return numberOfStatecoderFail; | 107 | return numberOfStatecoderFail; |
102 | } | 108 | } |
109 | public long getForwardTime() { | ||
110 | return context.getDesignSpaceManager().getForwardTime(); | ||
111 | } | ||
112 | public long getBacktrackingTime() { | ||
113 | return context.getDesignSpaceManager().getBacktrackingTime(); | ||
114 | } | ||
103 | 115 | ||
104 | @Override | 116 | @Override |
105 | public void initStrategy(ThreadContext context) { | 117 | public void initStrategy(ThreadContext context) { |
106 | this.context = context; | 118 | this.context = context; |
107 | this.solutionStore = context.getGlobalContext().getSolutionStore(); | 119 | this.solutionStore = context.getGlobalContext().getSolutionStore(); |
120 | solutionStore.registerSolutionFoundHandler(new ISolutionFoundHandler() { | ||
121 | |||
122 | @Override | ||
123 | public void solutionTriedToSave(ThreadContext context, SolutionTrajectory trajectory) { | ||
124 | // Ignore. | ||
125 | } | ||
126 | |||
127 | @Override | ||
128 | public void solutionFound(ThreadContext context, SolutionTrajectory trajectory) { | ||
129 | configuration.progressMonitor.workedModelFound(configuration.solutionScope.numberOfRequiredSolutions); | ||
130 | saveTimes(); | ||
131 | logger.debug("Found a solution."); | ||
132 | } | ||
133 | }); | ||
134 | numericSolver.init(context); | ||
108 | 135 | ||
109 | ViatraQueryEngine engine = context.getQueryEngine(); | 136 | // ViatraQueryEngine engine = context.getQueryEngine(); |
110 | // // TODO: visualisation | 137 | // matchers = new LinkedList<ViatraQueryMatcher<? extends IPatternMatch>>(); |
111 | matchers = new LinkedList<ViatraQueryMatcher<? extends IPatternMatch>>(); | 138 | // for(IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> p : this.method.getAllPatterns()) { |
112 | for(IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> p : this.method.getAllPatterns()) { | 139 | // //System.out.println(p.getSimpleName()); |
113 | //System.out.println(p.getSimpleName()); | 140 | // ViatraQueryMatcher<? extends IPatternMatch> matcher = p.getMatcher(engine); |
114 | ViatraQueryMatcher<? extends IPatternMatch> matcher = p.getMatcher(engine); | 141 | // matchers.add(matcher); |
115 | matchers.add(matcher); | 142 | // } |
116 | } | ||
117 | 143 | ||
118 | final ObjectiveComparatorHelper objectiveComparatorHelper = context.getObjectiveComparatorHelper(); | 144 | final ObjectiveComparatorHelper objectiveComparatorHelper = context.getObjectiveComparatorHelper(); |
119 | this.comparator = new Comparator<TrajectoryWithFitness>() { | 145 | this.comparator = new Comparator<TrajectoryWithFitness>() { |
@@ -128,23 +154,33 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { | |||
128 | 154 | ||
129 | @Override | 155 | @Override |
130 | public void explore() { | 156 | public void explore() { |
131 | if (!context.checkGlobalConstraints()) { | 157 | // System.out.println("press enter"); |
158 | // try { | ||
159 | // new BufferedReader(new InputStreamReader(System.in)).readLine(); | ||
160 | // } catch (IOException e) { | ||
161 | // // TODO Auto-generated catch block | ||
162 | // e.printStackTrace(); | ||
163 | // } | ||
164 | this.explorationStarted=System.nanoTime(); | ||
165 | if (!checkGlobalConstraints()) { | ||
132 | logger.info("Global contraint is not satisifed in the first state. Terminate."); | 166 | logger.info("Global contraint is not satisifed in the first state. Terminate."); |
133 | return; | 167 | return; |
168 | } else if(!numericSolver.maySatisfiable()) { | ||
169 | logger.info("Numeric contraints are not satisifed in the first state. Terminate."); | ||
170 | return; | ||
134 | } | 171 | } |
135 | if (configuration.searchSpaceConstraints.maxDepth == 0) { | 172 | if (configuration.searchSpaceConstraints.maxDepth == 0) { |
136 | logger.info("Maximal depth is reached in the initial solution. Terminate."); | 173 | logger.info("Maximal depth is reached in the initial solution. Terminate."); |
137 | return; | 174 | return; |
138 | } | 175 | } |
139 | 176 | ||
140 | final Fitness firstfitness = context.calculateFitness(); | 177 | final Fitness firstFitness = calculateFitness(); |
141 | solutionStore.newSolution(context); | 178 | checkForSolution(firstFitness); |
142 | 179 | ||
143 | final ObjectiveComparatorHelper objectiveComparatorHelper = context.getObjectiveComparatorHelper(); | 180 | final ObjectiveComparatorHelper objectiveComparatorHelper = context.getObjectiveComparatorHelper(); |
144 | final Object[] firstTrajectory = context.getTrajectory().toArray(new Object[0]); | 181 | final Object[] firstTrajectory = context.getTrajectory().toArray(new Object[0]); |
145 | TrajectoryWithFitness currentTrajectoryWithfitness = new TrajectoryWithFitness(firstTrajectory, firstfitness); | 182 | TrajectoryWithFitness currentTrajectoryWithFitness = new TrajectoryWithFitness(firstTrajectory, firstFitness); |
146 | trajectoiresToExplore.add(currentTrajectoryWithfitness); | 183 | trajectoiresToExplore.add(currentTrajectoryWithFitness); |
147 | |||
148 | //if(configuration) | 184 | //if(configuration) |
149 | visualiseCurrentState(); | 185 | visualiseCurrentState(); |
150 | // for(ViatraQueryMatcher<? extends IPatternMatch> matcher : matchers) { | 186 | // for(ViatraQueryMatcher<? extends IPatternMatch> matcher : matchers) { |
@@ -158,17 +194,17 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { | |||
158 | 194 | ||
159 | mainLoop: while (!isInterrupted && !configuration.progressMonitor.isCancelled()) { | 195 | mainLoop: while (!isInterrupted && !configuration.progressMonitor.isCancelled()) { |
160 | 196 | ||
161 | if (currentTrajectoryWithfitness == null) { | 197 | if (currentTrajectoryWithFitness == null) { |
162 | if (trajectoiresToExplore.isEmpty()) { | 198 | if (trajectoiresToExplore.isEmpty()) { |
163 | logger.debug("State space is fully traversed."); | 199 | logger.debug("State space is fully traversed."); |
164 | return; | 200 | return; |
165 | } else { | 201 | } else { |
166 | currentTrajectoryWithfitness = selectState(); | 202 | currentTrajectoryWithFitness = selectState(); |
167 | if (logger.isDebugEnabled()) { | 203 | if (logger.isDebugEnabled()) { |
168 | logger.debug("Current trajectory: " + Arrays.toString(context.getTrajectory().toArray())); | 204 | logger.debug("Current trajectory: " + Arrays.toString(context.getTrajectory().toArray())); |
169 | logger.debug("New trajectory is chosen: " + currentTrajectoryWithfitness); | 205 | logger.debug("New trajectory is chosen: " + currentTrajectoryWithFitness); |
170 | } | 206 | } |
171 | context.getDesignSpaceManager().executeTrajectoryWithMinimalBacktrackWithoutStateCoding(currentTrajectoryWithfitness.trajectory); | 207 | context.getDesignSpaceManager().executeTrajectoryWithMinimalBacktrackWithoutStateCoding(currentTrajectoryWithFitness.trajectory); |
172 | } | 208 | } |
173 | } | 209 | } |
174 | 210 | ||
@@ -193,26 +229,28 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { | |||
193 | 229 | ||
194 | visualiseCurrentState(); | 230 | visualiseCurrentState(); |
195 | // for(ViatraQueryMatcher<? extends IPatternMatch> matcher : matchers) { | 231 | // for(ViatraQueryMatcher<? extends IPatternMatch> matcher : matchers) { |
196 | // System.out.println(matcher.getPatternName()); | 232 | // int c = matcher.countMatches(); |
197 | // System.out.println("---------"); | 233 | // if(c>=100) { |
198 | // for(IPatternMatch m : matcher.getAllMatches()) { | 234 | // System.out.println(c+ " " +matcher.getPatternName()); |
199 | // System.out.println(m); | ||
200 | // } | 235 | // } |
201 | // System.out.println("---------"); | 236 | // |
202 | // } | 237 | // } |
203 | 238 | ||
204 | boolean consistencyCheckResult = checkConsistency(currentTrajectoryWithfitness); | 239 | boolean consistencyCheckResult = checkConsistency(currentTrajectoryWithFitness); |
205 | if(consistencyCheckResult == true) { continue mainLoop; } | 240 | if(consistencyCheckResult == true) { continue mainLoop; } |
206 | 241 | ||
207 | if (context.isCurrentStateAlreadyTraversed()) { | 242 | if (context.isCurrentStateAlreadyTraversed()) { |
208 | logger.info("The new state is already visited."); | 243 | logger.info("The new state is already visited."); |
209 | context.backtrack(); | 244 | context.backtrack(); |
210 | } else if (!context.checkGlobalConstraints()) { | 245 | } else if (!checkGlobalConstraints()) { |
211 | logger.debug("Global contraint is not satisifed."); | 246 | logger.debug("Global contraint is not satisifed."); |
212 | context.backtrack(); | 247 | context.backtrack(); |
248 | } else if (!numericSolver.maySatisfiable()) { | ||
249 | logger.debug("Numeric constraints are not satisifed."); | ||
250 | context.backtrack(); | ||
213 | } else { | 251 | } else { |
214 | final Fitness nextFitness = context.calculateFitness(); | 252 | final Fitness nextFitness = context.calculateFitness(); |
215 | solutionStore.newSolution(context); | 253 | checkForSolution(nextFitness); |
216 | if (context.getDepth() > configuration.searchSpaceConstraints.maxDepth) { | 254 | if (context.getDepth() > configuration.searchSpaceConstraints.maxDepth) { |
217 | logger.debug("Reached max depth."); | 255 | logger.debug("Reached max depth."); |
218 | context.backtrack(); | 256 | context.backtrack(); |
@@ -223,37 +261,50 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { | |||
223 | context.getTrajectory().toArray(), nextFitness); | 261 | context.getTrajectory().toArray(), nextFitness); |
224 | trajectoiresToExplore.add(nextTrajectoryWithfitness); | 262 | trajectoiresToExplore.add(nextTrajectoryWithfitness); |
225 | 263 | ||
226 | int compare = objectiveComparatorHelper.compare(currentTrajectoryWithfitness.fitness, | 264 | int compare = objectiveComparatorHelper.compare(currentTrajectoryWithFitness.fitness, |
227 | nextTrajectoryWithfitness.fitness); | 265 | nextTrajectoryWithfitness.fitness); |
228 | if (compare < 0) { | 266 | if (compare < 0) { |
229 | logger.debug("Better fitness, moving on: " + nextFitness); | 267 | logger.debug("Better fitness, moving on: " + nextFitness); |
230 | currentTrajectoryWithfitness = nextTrajectoryWithfitness; | 268 | currentTrajectoryWithFitness = nextTrajectoryWithfitness; |
231 | continue mainLoop; | 269 | continue mainLoop; |
232 | } else if (compare == 0) { | 270 | } else if (compare == 0) { |
233 | logger.debug("Equally good fitness, moving on: " + nextFitness); | 271 | logger.debug("Equally good fitness, moving on: " + nextFitness); |
234 | currentTrajectoryWithfitness = nextTrajectoryWithfitness; | 272 | currentTrajectoryWithFitness = nextTrajectoryWithfitness; |
235 | continue mainLoop; | 273 | continue mainLoop; |
236 | } else { | 274 | } else { |
237 | logger.debug("Worse fitness."); | 275 | logger.debug("Worse fitness."); |
238 | currentTrajectoryWithfitness = null; | 276 | currentTrajectoryWithFitness = null; |
239 | continue mainLoop; | 277 | continue mainLoop; |
240 | } | 278 | } |
241 | } | 279 | } |
242 | } | 280 | } |
243 | 281 | ||
244 | logger.debug("State is fully traversed."); | 282 | logger.debug("State is fully traversed."); |
245 | trajectoiresToExplore.remove(currentTrajectoryWithfitness); | 283 | trajectoiresToExplore.remove(currentTrajectoryWithFitness); |
246 | currentTrajectoryWithfitness = null; | 284 | currentTrajectoryWithFitness = null; |
247 | 285 | ||
248 | } | 286 | } |
249 | logger.info("Interrupted."); | 287 | logger.info("Interrupted."); |
250 | } | 288 | } |
251 | 289 | ||
290 | private boolean checkGlobalConstraints() { | ||
291 | long start = System.nanoTime(); | ||
292 | boolean result = context.checkGlobalConstraints(); | ||
293 | globalConstraintEvaluationTime += System.nanoTime() - start; | ||
294 | return result; | ||
295 | } | ||
296 | |||
297 | private Fitness calculateFitness() { | ||
298 | long start = System.nanoTime(); | ||
299 | Fitness fitness = context.calculateFitness(); | ||
300 | fitnessCalculationTime += System.nanoTime() - start; | ||
301 | return fitness; | ||
302 | } | ||
303 | |||
252 | private List<Object> selectActivation() { | 304 | private List<Object> selectActivation() { |
253 | List<Object> activationIds; | 305 | List<Object> activationIds; |
254 | try { | 306 | try { |
255 | activationIds = new ArrayList<Object>(context.getUntraversedActivationIds()); | 307 | activationIds = this.activationSelector.randomizeActivationIDs(context.getUntraversedActivationIds()); |
256 | Collections.shuffle(activationIds); | ||
257 | } catch (NullPointerException e) { | 308 | } catch (NullPointerException e) { |
258 | // logger.warn("Unexpected state code: " + context.getDesignSpaceManager().getCurrentState()); | 309 | // logger.warn("Unexpected state code: " + context.getDesignSpaceManager().getCurrentState()); |
259 | numberOfStatecoderFail++; | 310 | numberOfStatecoderFail++; |
@@ -262,6 +313,37 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { | |||
262 | return activationIds; | 313 | return activationIds; |
263 | } | 314 | } |
264 | 315 | ||
316 | private void checkForSolution(final Fitness fittness) { | ||
317 | solutionStore.newSolution(context); | ||
318 | } | ||
319 | |||
320 | public List<String> times = new LinkedList<String>(); | ||
321 | private void saveTimes() { | ||
322 | long statecoderTime = ((NeighbourhoodBasedPartialInterpretationStateCoder<?, ?>)this.context.getStateCoder()).getStatecoderRuntime()/1000000; | ||
323 | long forwardTime = context.getDesignSpaceManager().getForwardTime()/1000000; | ||
324 | long backtrackingTime = context.getDesignSpaceManager().getBacktrackingTime()/1000000; | ||
325 | long activationSelection = this.activationSelector.getRuntime()/1000000; | ||
326 | long solutionCopierTime = this.solutionSaver.getTotalCopierRuntime()/1000000; | ||
327 | long numericalSolverSumTime = this.numericSolver.getRuntime()/1000000; | ||
328 | long numericalSolverProblemForming = this.numericSolver.getSolverSolvingProblem()/1000000; | ||
329 | long numericalSolverSolving = this.numericSolver.getSolverSolvingProblem()/1000000; | ||
330 | long numericalSolverInterpreting = this.numericSolver.getSolverSolution()/1000000; | ||
331 | this.times.add( | ||
332 | "(TransformationExecutionTime"+method.getStatistics().transformationExecutionTime/1000000+ | ||
333 | "|StateCoderTime:"+statecoderTime+ | ||
334 | "|ForwardTime:"+forwardTime+ | ||
335 | "|Backtrackingtime:"+backtrackingTime+ | ||
336 | "|GlobalConstraintEvaluationTime:"+(globalConstraintEvaluationTime/1000000)+ | ||
337 | "|FitnessCalculationTime:"+(fitnessCalculationTime/1000000)+ | ||
338 | "|ActivationSelectionTime:"+activationSelection+ | ||
339 | "|SolutionCopyTime:"+solutionCopierTime+ | ||
340 | "|NumericalSolverSumTime:"+numericalSolverSumTime+ | ||
341 | "|NumericalSolverProblemFormingTime:"+numericalSolverProblemForming+ | ||
342 | "|NumericalSolverSolvingTime:"+numericalSolverSolving+ | ||
343 | "|NumericalSolverInterpretingSolution:"+numericalSolverInterpreting+")"); | ||
344 | |||
345 | } | ||
346 | |||
265 | @Override | 347 | @Override |
266 | public void interruptStrategy() { | 348 | public void interruptStrategy() { |
267 | isInterrupted = true; | 349 | isInterrupted = true; |
@@ -288,7 +370,7 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { | |||
288 | } else { | 370 | } else { |
289 | return trajectoiresToExplore.element(); | 371 | return trajectoiresToExplore.element(); |
290 | } | 372 | } |
291 | } | 373 | } |
292 | 374 | ||
293 | public void visualiseCurrentState() { | 375 | public void visualiseCurrentState() { |
294 | PartialInterpretationVisualiser partialInterpretatioVisualiser = configuration.debugConfiguration.partialInterpretatioVisualiser; | 376 | PartialInterpretationVisualiser partialInterpretatioVisualiser = configuration.debugConfiguration.partialInterpretatioVisualiser; |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/EvenActivationSelector.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/EvenActivationSelector.xtend new file mode 100644 index 00000000..82a5f32d --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/EvenActivationSelector.xtend | |||
@@ -0,0 +1,20 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse | ||
2 | |||
3 | import java.util.Random | ||
4 | import java.util.Collection | ||
5 | import java.util.Collections | ||
6 | import java.util.ArrayList | ||
7 | |||
8 | class EvenActivationSelector extends ActivationSelector { | ||
9 | |||
10 | new(Random r) { | ||
11 | super(r) | ||
12 | } | ||
13 | |||
14 | override protected internalRandomizationOfActivationIDs(Collection<Object> activationIDs) { | ||
15 | val toShuffle = new ArrayList<Object>(activationIDs); | ||
16 | Collections.shuffle(toShuffle); | ||
17 | return toShuffle | ||
18 | } | ||
19 | |||
20 | } \ No newline at end of file | ||
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ModelGenerationCompositeObjective.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ModelGenerationCompositeObjective.xtend index 2976bebe..d2faaa65 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ModelGenerationCompositeObjective.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ModelGenerationCompositeObjective.xtend | |||
@@ -1,36 +1,58 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse | 1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse |
2 | 2 | ||
3 | import com.google.common.collect.ImmutableList | 3 | import com.google.common.collect.ImmutableList |
4 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation | ||
5 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration | ||
4 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.IThreeValuedObjective | 6 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.IThreeValuedObjective |
5 | import java.util.Comparator | 7 | import java.util.Comparator |
6 | import java.util.List | 8 | import java.util.List |
7 | import org.eclipse.viatra.dse.base.ThreadContext | 9 | import org.eclipse.viatra.dse.base.ThreadContext |
8 | import org.eclipse.viatra.dse.objectives.Comparators | 10 | import org.eclipse.viatra.dse.objectives.Comparators |
9 | import org.eclipse.viatra.dse.objectives.IObjective | 11 | import org.eclipse.viatra.dse.objectives.IObjective |
10 | import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor | ||
11 | 12 | ||
12 | //class ViatraReasonerNumbers { | ||
13 | // public static val scopePriority = 2 | ||
14 | // public static val unfinishedMultiplicityPriority = 2 | ||
15 | // public static val unifinshedWFPriority = 2 | ||
16 | // //public static val complexityPriority = 4 | ||
17 | // | ||
18 | // public static val scopeWeigth = 1.0 | ||
19 | // public static val unfinishedMultiplicityWeigth = 1.5 | ||
20 | // public static val unfinishedWFWeigth = 1.5 | ||
21 | // //public static val complexityWeigth = 0.1 | ||
22 | // | ||
23 | // public static val useCompositeObjective = true | ||
24 | // public static val compositePriority = 2 | ||
25 | //} | ||
26 | |||
27 | @FinalFieldsConstructor | ||
28 | class ModelGenerationCompositeObjective implements IThreeValuedObjective { | 13 | class ModelGenerationCompositeObjective implements IThreeValuedObjective { |
29 | val IObjective scopeObjective | 14 | val IObjective scopeObjective |
30 | val List<IObjective> unfinishedMultiplicityObjectives | 15 | val List<UnfinishedMultiplicityObjective> unfinishedMultiplicityObjectives |
31 | val IObjective unfinishedWFObjective | 16 | val UnfinishedWFObjective unfinishedWFObjective |
17 | var PartialInterpretation model = null | ||
18 | val boolean punishSize | ||
19 | val int scopeWeight | ||
20 | val int conaintmentWeight | ||
21 | val int nonContainmentWeight | ||
22 | val int unfinishedWFWeight | ||
23 | |||
24 | new( | ||
25 | IObjective scopeObjective, | ||
26 | List<UnfinishedMultiplicityObjective> unfinishedMultiplicityObjectives, | ||
27 | UnfinishedWFObjective unfinishedWFObjective, | ||
28 | ViatraReasonerConfiguration configuration) | ||
29 | { | ||
30 | this( | ||
31 | scopeObjective, unfinishedMultiplicityObjectives, unfinishedWFObjective, configuration.punishSize, | ||
32 | configuration.scopeWeight, configuration.conaintmentWeight, configuration.nonContainmentWeight, | ||
33 | configuration.unfinishedWFWeight | ||
34 | ) | ||
35 | } | ||
32 | 36 | ||
37 | new( | ||
38 | IObjective scopeObjective, | ||
39 | List<UnfinishedMultiplicityObjective> unfinishedMultiplicityObjectives, | ||
40 | UnfinishedWFObjective unfinishedWFObjective, | ||
41 | boolean punishSize, int scopeWeight, int conaintmentWeight, int nonContainmentWeight, int unfinishedWFWeight) | ||
42 | { | ||
43 | this.scopeObjective = scopeObjective | ||
44 | this.unfinishedMultiplicityObjectives = unfinishedMultiplicityObjectives | ||
45 | this.unfinishedWFObjective = unfinishedWFObjective | ||
46 | |||
47 | this.punishSize = punishSize | ||
48 | this.scopeWeight = scopeWeight | ||
49 | this.conaintmentWeight = conaintmentWeight | ||
50 | this.nonContainmentWeight = nonContainmentWeight | ||
51 | this.unfinishedWFWeight = unfinishedWFWeight | ||
52 | } | ||
53 | |||
33 | override init(ThreadContext context) { | 54 | override init(ThreadContext context) { |
55 | model = context.model as PartialInterpretation | ||
34 | this.scopeObjective.init(context) | 56 | this.scopeObjective.init(context) |
35 | this.unfinishedMultiplicityObjectives.forEach[it.init(context)] | 57 | this.unfinishedMultiplicityObjectives.forEach[it.init(context)] |
36 | this.unfinishedWFObjective.init(context) | 58 | this.unfinishedWFObjective.init(context) |
@@ -39,27 +61,40 @@ class ModelGenerationCompositeObjective implements IThreeValuedObjective { | |||
39 | override createNew() { | 61 | override createNew() { |
40 | return new ModelGenerationCompositeObjective( | 62 | return new ModelGenerationCompositeObjective( |
41 | scopeObjective.createNew, | 63 | scopeObjective.createNew, |
42 | ImmutableList.copyOf(unfinishedMultiplicityObjectives.map[createNew]), | 64 | ImmutableList.copyOf(unfinishedMultiplicityObjectives.map[createNew as UnfinishedMultiplicityObjective]), |
43 | unfinishedWFObjective.createNew | 65 | unfinishedWFObjective.createNew as UnfinishedWFObjective, |
66 | punishSize, scopeWeight, conaintmentWeight, nonContainmentWeight, unfinishedWFWeight | ||
44 | ) | 67 | ) |
45 | } | 68 | } |
46 | 69 | ||
47 | override getComparator() { Comparators.LOWER_IS_BETTER } | 70 | override getComparator() { Comparators.LOWER_IS_BETTER } |
48 | 71 | ||
49 | override getFitness(ThreadContext context) { | 72 | override getFitness(ThreadContext context) { |
50 | var sum = 0.0 | 73 | |
51 | val scopeFitnes = scopeObjective.getFitness(context) | 74 | val scopeFitnes = scopeObjective.getFitness(context) |
52 | // val unfinishedMultiplicitiesFitneses = unfinishedMultiplicityObjectives.map[x|x.getFitness(context)] | ||
53 | val unfinishedWFsFitness = unfinishedWFObjective.getFitness(context) | 75 | val unfinishedWFsFitness = unfinishedWFObjective.getFitness(context) |
54 | 76 | ||
55 | sum += scopeFitnes | 77 | var containmentMultiplicity = 0.0 |
56 | var multiplicity = 0.0 | 78 | var nonContainmentMultiplicity = 0.0 |
57 | for (multiplicityObjective : unfinishedMultiplicityObjectives) { | 79 | for(multiplicityObjective : unfinishedMultiplicityObjectives) { |
58 | multiplicity += multiplicityObjective.getFitness(context) // *0.5 | 80 | if(multiplicityObjective.containment) { |
81 | containmentMultiplicity+=multiplicityObjective.getFitness(context) | ||
82 | } else { | ||
83 | nonContainmentMultiplicity+=multiplicityObjective.getFitness(context) | ||
84 | } | ||
59 | } | 85 | } |
60 | sum += multiplicity | 86 | val size = if(punishSize) { |
61 | sum += unfinishedWFsFitness // *0.5 | 87 | 0.9/model.newElements.size |
62 | // println('''Sum=«sum»|Scope=«scopeFitnes»|Multiplicity=«multiplicity»|WFs=«unfinishedWFsFitness»''') | 88 | } else { |
89 | 0 | ||
90 | } | ||
91 | |||
92 | var sum = 0.0 | ||
93 | sum += scopeFitnes*scopeWeight | ||
94 | sum += containmentMultiplicity*conaintmentWeight | ||
95 | sum += nonContainmentMultiplicity*nonContainmentWeight | ||
96 | sum += unfinishedWFsFitness*unfinishedWFWeight | ||
97 | sum+=size | ||
63 | return sum | 98 | return sum |
64 | } | 99 | } |
65 | 100 | ||
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/NumericSolver.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/NumericSolver.xtend new file mode 100644 index 00000000..066040a0 --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/NumericSolver.xtend | |||
@@ -0,0 +1,192 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse | ||
2 | |||
3 | import hu.bme.mit.inf.dslreasoner.viatra2logic.NumericTranslator | ||
4 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod | ||
5 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.BooleanElement | ||
6 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.IntegerElement | ||
7 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation | ||
8 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PrimitiveElement | ||
9 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.RealElement | ||
10 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.StringElement | ||
11 | import java.math.BigDecimal | ||
12 | import java.util.HashMap | ||
13 | import java.util.LinkedHashMap | ||
14 | import java.util.LinkedHashSet | ||
15 | import java.util.List | ||
16 | import java.util.Map | ||
17 | import org.eclipse.emf.ecore.EObject | ||
18 | import org.eclipse.viatra.dse.base.ThreadContext | ||
19 | import org.eclipse.viatra.query.runtime.api.IPatternMatch | ||
20 | import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher | ||
21 | import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint | ||
22 | |||
23 | class NumericSolver { | ||
24 | val ModelGenerationMethod method | ||
25 | var ThreadContext threadContext | ||
26 | val constraint2MustUnitPropagationPrecondition = new HashMap<PConstraint,ViatraQueryMatcher<? extends IPatternMatch>> | ||
27 | val constraint2CurrentUnitPropagationPrecondition = new HashMap<PConstraint,ViatraQueryMatcher<? extends IPatternMatch>> | ||
28 | NumericTranslator t = new NumericTranslator | ||
29 | |||
30 | val boolean intermediateConsistencyCheck | ||
31 | val boolean caching; | ||
32 | Map<LinkedHashMap<PConstraint, Iterable<List<Integer>>>,Boolean> satisfiabilityCache = new HashMap | ||
33 | |||
34 | var long runtime = 0 | ||
35 | var long cachingTime = 0 | ||
36 | var int numberOfSolverCalls = 0 | ||
37 | var int numberOfCachedSolverCalls = 0 | ||
38 | |||
39 | new(ModelGenerationMethod method, boolean intermediateConsistencyCheck, boolean caching) { | ||
40 | this.method = method | ||
41 | this.intermediateConsistencyCheck = intermediateConsistencyCheck | ||
42 | this.caching = caching | ||
43 | } | ||
44 | |||
45 | def init(ThreadContext context) { | ||
46 | // This makes the NumericSolver single-threaded, | ||
47 | // but that's not a problem, because we only use the solver on a single thread anyways. | ||
48 | this.threadContext = context | ||
49 | val engine = threadContext.queryEngine | ||
50 | for(entry : method.mustUnitPropagationPreconditions.entrySet) { | ||
51 | val constraint = entry.key | ||
52 | val querySpec = entry.value | ||
53 | val matcher = querySpec.getMatcher(engine); | ||
54 | constraint2MustUnitPropagationPrecondition.put(constraint,matcher) | ||
55 | } | ||
56 | for(entry : method.currentUnitPropagationPreconditions.entrySet) { | ||
57 | val constraint = entry.key | ||
58 | val querySpec = entry.value | ||
59 | val matcher = querySpec.getMatcher(engine); | ||
60 | constraint2CurrentUnitPropagationPrecondition.put(constraint,matcher) | ||
61 | } | ||
62 | } | ||
63 | |||
64 | def getRuntime(){runtime} | ||
65 | def getCachingTime(){cachingTime} | ||
66 | def getNumberOfSolverCalls(){numberOfSolverCalls} | ||
67 | def getNumberOfCachedSolverCalls(){numberOfCachedSolverCalls} | ||
68 | def getSolverFormingProblem(){this.t.formingProblemTime} | ||
69 | def getSolverSolvingProblem(){this.t.solvingProblemTime} | ||
70 | def getSolverSolution(){this.t.formingSolutionTime} | ||
71 | |||
72 | def boolean maySatisfiable() { | ||
73 | if(intermediateConsistencyCheck) { | ||
74 | return isSatisfiable(this.constraint2MustUnitPropagationPrecondition) | ||
75 | } else { | ||
76 | return true | ||
77 | } | ||
78 | } | ||
79 | def boolean currentSatisfiable() { | ||
80 | isSatisfiable(this.constraint2CurrentUnitPropagationPrecondition) | ||
81 | } | ||
82 | |||
83 | private def boolean isSatisfiable(Map<PConstraint,ViatraQueryMatcher<? extends IPatternMatch>> matches) { | ||
84 | val start = System.nanoTime | ||
85 | var boolean finalResult | ||
86 | if(matches.empty){ | ||
87 | finalResult=true | ||
88 | } else { | ||
89 | val propagatedConstraints = new HashMap | ||
90 | for(entry : matches.entrySet) { | ||
91 | val constraint = entry.key | ||
92 | //println(constraint) | ||
93 | val allMatches = entry.value.allMatches.map[it.toArray] | ||
94 | //println(allMatches.toList) | ||
95 | propagatedConstraints.put(constraint,allMatches) | ||
96 | } | ||
97 | if(propagatedConstraints.values.forall[empty]) { | ||
98 | finalResult=true | ||
99 | } else { | ||
100 | if(caching) { | ||
101 | val code = getCode(propagatedConstraints) | ||
102 | val cachedResult = satisfiabilityCache.get(code) | ||
103 | if(cachedResult === null) { | ||
104 | // println('''new problem, call solver''') | ||
105 | // for(entry : code.entrySet) { | ||
106 | // println('''«entry.key» -> «entry.value»''') | ||
107 | // } | ||
108 | //println(code.hashCode) | ||
109 | this.numberOfSolverCalls++ | ||
110 | val res = t.delegateIsSatisfiable(propagatedConstraints) | ||
111 | satisfiabilityCache.put(code,res) | ||
112 | finalResult=res | ||
113 | } else { | ||
114 | //println('''similar problem, answer from cache''') | ||
115 | finalResult=cachedResult | ||
116 | this.numberOfCachedSolverCalls++ | ||
117 | } | ||
118 | } else { | ||
119 | finalResult= t.delegateIsSatisfiable(propagatedConstraints) | ||
120 | this.numberOfSolverCalls++ | ||
121 | } | ||
122 | } | ||
123 | } | ||
124 | this.runtime+=System.nanoTime-start | ||
125 | return finalResult | ||
126 | } | ||
127 | |||
128 | def getCode(HashMap<PConstraint, Iterable<Object[]>> propagatedConstraints) { | ||
129 | val start = System.nanoTime | ||
130 | val involvedObjects = new LinkedHashSet(propagatedConstraints.values.flatten.map[toList].flatten.toList).toList | ||
131 | val res = new LinkedHashMap(propagatedConstraints.mapValues[matches | matches.map[objects | objects.map[object | involvedObjects.indexOf(object)].toList]]) | ||
132 | this.cachingTime += System.nanoTime-start | ||
133 | return res | ||
134 | } | ||
135 | |||
136 | def fillSolutionCopy(Map<EObject, EObject> trace) { | ||
137 | val model = threadContext.getModel as PartialInterpretation | ||
138 | val dataObjects = model.newElements.filter(PrimitiveElement).filter[!model.openWorldElements.contains(it)].toList | ||
139 | if(constraint2CurrentUnitPropagationPrecondition.empty) { | ||
140 | fillWithDefaultValues(dataObjects,trace) | ||
141 | } else { | ||
142 | val propagatedConstraints = new HashMap | ||
143 | for(entry : constraint2CurrentUnitPropagationPrecondition.entrySet) { | ||
144 | val constraint = entry.key | ||
145 | val allMatches = entry.value.allMatches.map[it.toArray] | ||
146 | propagatedConstraints.put(constraint,allMatches) | ||
147 | } | ||
148 | |||
149 | if(propagatedConstraints.values.forall[empty]) { | ||
150 | fillWithDefaultValues(dataObjects,trace) | ||
151 | } else { | ||
152 | val solution = t.delegateGetSolution(dataObjects,propagatedConstraints) | ||
153 | fillWithSolutions(dataObjects,solution,trace) | ||
154 | } | ||
155 | } | ||
156 | } | ||
157 | |||
158 | def protected fillWithDefaultValues(List<PrimitiveElement> elements, Map<EObject, EObject> trace) { | ||
159 | for(element : elements) { | ||
160 | if(element.valueSet==false) { | ||
161 | val value = getDefaultValue(element) | ||
162 | val target = trace.get(element) as PrimitiveElement | ||
163 | target.fillWithValue(value) | ||
164 | } | ||
165 | } | ||
166 | } | ||
167 | |||
168 | def protected dispatch getDefaultValue(BooleanElement e) {false} | ||
169 | def protected dispatch getDefaultValue(IntegerElement e) {0} | ||
170 | def protected dispatch getDefaultValue(RealElement e) {0.0} | ||
171 | def protected dispatch getDefaultValue(StringElement e) {""} | ||
172 | |||
173 | def protected fillWithSolutions(List<PrimitiveElement> elements, Map<PrimitiveElement, Number> solution, Map<EObject, EObject> trace) { | ||
174 | for(element : elements) { | ||
175 | if(element.valueSet==false) { | ||
176 | if(solution.containsKey(element)) { | ||
177 | val value = solution.get(element) | ||
178 | val target = trace.get(element) as PrimitiveElement | ||
179 | target.fillWithValue(value) | ||
180 | } else { | ||
181 | val target = trace.get(element) as PrimitiveElement | ||
182 | target.fillWithValue(target.defaultValue) | ||
183 | } | ||
184 | } | ||
185 | } | ||
186 | } | ||
187 | |||
188 | def protected dispatch fillWithValue(BooleanElement e, Object value) {e.valueSet=true e.value=value as Boolean} | ||
189 | def protected dispatch fillWithValue(IntegerElement e, Object value) {e.valueSet=true e.value=value as Integer} | ||
190 | def protected dispatch fillWithValue(RealElement e, Object value) {e.valueSet=true e.value=BigDecimal.valueOf(value as Double) } | ||
191 | def protected dispatch fillWithValue(StringElement e, Object value) {e.valueSet=true e.value=value as String} | ||
192 | } \ No newline at end of file | ||
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/PartialModelAsLogicInterpretation.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/PartialModelAsLogicInterpretation.xtend index b63bfe8b..cfd11816 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/PartialModelAsLogicInterpretation.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/PartialModelAsLogicInterpretation.xtend | |||
@@ -153,14 +153,70 @@ class PartialModelAsLogicInterpretation implements LogicModelInterpretation{ | |||
153 | } | 153 | } |
154 | 154 | ||
155 | override getAllIntegersInStructure() { | 155 | override getAllIntegersInStructure() { |
156 | new TreeSet(this.integerForwardTrace.keySet) | 156 | new TreeSet(allIntegersWithInterpretation.values) |
157 | } | ||
158 | |||
159 | override getAllIntegersWithInterpretation() { | ||
160 | val builder = new HashMap | ||
161 | for (entry : integerForwardTrace.entrySet) { | ||
162 | builder.put(entry.value, entry.key) | ||
163 | } | ||
164 | for (element : partialInterpretation.newElements) { | ||
165 | if (element instanceof IntegerElement) { | ||
166 | builder.put(element, element.value) | ||
167 | } | ||
168 | } | ||
169 | builder | ||
157 | } | 170 | } |
158 | 171 | ||
159 | override getAllRealsInStructure() { | 172 | override getAllRealsInStructure() { |
160 | new TreeSet(this.realForwardTrace.keySet) | 173 | new TreeSet(allRealsWithInterpretation.values) |
174 | } | ||
175 | |||
176 | override getAllRealsWithInterpretation() { | ||
177 | val builder = new HashMap | ||
178 | for (entry : realForwardTrace.entrySet) { | ||
179 | builder.put(entry.value, entry.key) | ||
180 | } | ||
181 | for (element : partialInterpretation.newElements) { | ||
182 | if (element instanceof RealElement) { | ||
183 | builder.put(element, element.value) | ||
184 | } | ||
185 | } | ||
186 | builder | ||
161 | } | 187 | } |
162 | 188 | ||
163 | override getAllStringsInStructure() { | 189 | override getAllStringsInStructure() { |
164 | new TreeSet(this.stringForwardTrace.keySet) | 190 | new TreeSet(allStringsWithInterpretation.values) |
191 | } | ||
192 | |||
193 | override getAllStringsWithInterpretation() { | ||
194 | val builder = new HashMap | ||
195 | for (entry : stringForwardTrace.entrySet) { | ||
196 | builder.put(entry.value, entry.key) | ||
197 | } | ||
198 | for (element : partialInterpretation.newElements) { | ||
199 | if (element instanceof StringElement) { | ||
200 | builder.put(element, element.value) | ||
201 | } | ||
202 | } | ||
203 | builder | ||
204 | } | ||
205 | |||
206 | override getAllBooleansInStructure() { | ||
207 | new TreeSet(allBooleansWithInterpretation.values) | ||
208 | } | ||
209 | |||
210 | override getAllBooleansWithInterpretation() { | ||
211 | val builder = new HashMap | ||
212 | for (entry : booleanForwardTrace.entrySet) { | ||
213 | builder.put(entry.value, entry.key) | ||
214 | } | ||
215 | for (element : partialInterpretation.newElements) { | ||
216 | if (element instanceof BooleanElement) { | ||
217 | builder.put(element, element.value) | ||
218 | } | ||
219 | } | ||
220 | builder | ||
165 | } | 221 | } |
166 | } | 222 | } |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionCopier.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionCopier.xtend index d036257d..38c8f5a1 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionCopier.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionCopier.xtend | |||
@@ -19,12 +19,23 @@ class CopiedSolution { | |||
19 | @Accessors var boolean current = true | 19 | @Accessors var boolean current = true |
20 | } | 20 | } |
21 | 21 | ||
22 | /** | ||
23 | * Based on {@link SolutionStore.BestSolutionSaver}. | ||
24 | * | ||
25 | * Will also automatically fill any missing numerical values in the saved solutions | ||
26 | * using the supplied {@link NumericSolver}. | ||
27 | */ | ||
22 | class SolutionCopier { | 28 | class SolutionCopier { |
29 | val NumericSolver numericSolver | ||
23 | val copiedSolutions = new LinkedHashMap<Object, CopiedSolution> | 30 | val copiedSolutions = new LinkedHashMap<Object, CopiedSolution> |
24 | 31 | ||
25 | long startTime = System.nanoTime | 32 | long startTime = System.nanoTime |
26 | @Accessors(PUBLIC_GETTER) long totalCopierRuntime = 0 | 33 | @Accessors(PUBLIC_GETTER) long totalCopierRuntime = 0 |
27 | 34 | ||
35 | new(NumericSolver numericSolver) { | ||
36 | this.numericSolver = numericSolver | ||
37 | } | ||
38 | |||
28 | def void copySolution(ThreadContext context, Object solutionId) { | 39 | def void copySolution(ThreadContext context, Object solutionId) { |
29 | val existingCopy = copiedSolutions.get(solutionId) | 40 | val existingCopy = copiedSolutions.get(solutionId) |
30 | if (existingCopy === null) { | 41 | if (existingCopy === null) { |
@@ -36,6 +47,7 @@ class SolutionCopier { | |||
36 | totalCopierRuntime += System.nanoTime - copyStart | 47 | totalCopierRuntime += System.nanoTime - copyStart |
37 | val copierRuntime = System.nanoTime - startTime | 48 | val copierRuntime = System.nanoTime - startTime |
38 | val copiedSolution = new CopiedSolution(copiedPartialInterpretation, copier, copierRuntime) | 49 | val copiedSolution = new CopiedSolution(copiedPartialInterpretation, copier, copierRuntime) |
50 | numericSolver.fillSolutionCopy(copiedSolution.trace) | ||
39 | copiedSolutions.put(solutionId, copiedSolution) | 51 | copiedSolutions.put(solutionId, copiedSolution) |
40 | } else { | 52 | } else { |
41 | existingCopy.current = true | 53 | existingCopy.current = true |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionStoreWithCopy.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionStoreWithCopy.xtend new file mode 100644 index 00000000..4bd2c349 --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionStoreWithCopy.xtend | |||
@@ -0,0 +1,51 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse | ||
2 | |||
3 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation | ||
4 | import java.util.LinkedList | ||
5 | import java.util.List | ||
6 | import java.util.Map | ||
7 | import org.eclipse.emf.ecore.EObject | ||
8 | import org.eclipse.emf.ecore.util.EcoreUtil | ||
9 | import org.eclipse.viatra.dse.base.ThreadContext | ||
10 | |||
11 | class SolutionStoreWithCopy { | ||
12 | |||
13 | long runtime = 0 | ||
14 | List<PartialInterpretation> solutions = new LinkedList | ||
15 | //public List<SortedMap<String,Integer>> additionalMatches = new LinkedList | ||
16 | List<Map<EObject,EObject>> copyTraces = new LinkedList | ||
17 | |||
18 | long sartTime = System.nanoTime | ||
19 | List<Long> solutionTimes = new LinkedList | ||
20 | |||
21 | /*def newSolution(ThreadContext context, SortedMap<String,Integer> additonalMatch) { | ||
22 | additionalMatches+= additonalMatch | ||
23 | newSolution(context) | ||
24 | }*/ | ||
25 | |||
26 | def Map<EObject,EObject> newSolution(ThreadContext context) { | ||
27 | //print(System.nanoTime-initTime + ";") | ||
28 | val copyStart = System.nanoTime | ||
29 | val solution = context.model as PartialInterpretation | ||
30 | val copier = new EcoreUtil.Copier | ||
31 | val solutionCopy = copier.copy(solution) as PartialInterpretation | ||
32 | copier.copyReferences | ||
33 | solutions.add(solutionCopy) | ||
34 | copyTraces.add(copier) | ||
35 | runtime += System.nanoTime - copyStart | ||
36 | solutionTimes.add(System.nanoTime-sartTime) | ||
37 | return copier | ||
38 | } | ||
39 | def getSumRuntime() { | ||
40 | return runtime | ||
41 | } | ||
42 | def getAllRuntimes() { | ||
43 | return solutionTimes | ||
44 | } | ||
45 | def getSolutions() { | ||
46 | solutions | ||
47 | } | ||
48 | def getCopyTraces() { | ||
49 | return copyTraces | ||
50 | } | ||
51 | } \ No newline at end of file | ||
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/UnfinishedMultiplicityObjective.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/UnfinishedMultiplicityObjective.xtend index 9f0c642f..e1582d3b 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/UnfinishedMultiplicityObjective.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/UnfinishedMultiplicityObjective.xtend | |||
@@ -7,7 +7,7 @@ import org.eclipse.viatra.dse.objectives.Comparators | |||
7 | import org.eclipse.viatra.dse.objectives.IObjective | 7 | import org.eclipse.viatra.dse.objectives.IObjective |
8 | 8 | ||
9 | class UnfinishedMultiplicityObjective implements IObjective { | 9 | class UnfinishedMultiplicityObjective implements IObjective { |
10 | val MultiplicityGoalConstraintCalculator unfinishedMultiplicity; | 10 | val MultiplicityGoalConstraintCalculator unfinishedMultiplicity |
11 | 11 | ||
12 | new(MultiplicityGoalConstraintCalculator unfinishedMultiplicity) { | 12 | new(MultiplicityGoalConstraintCalculator unfinishedMultiplicity) { |
13 | this.unfinishedMultiplicity = unfinishedMultiplicity | 13 | this.unfinishedMultiplicity = unfinishedMultiplicity |
@@ -34,4 +34,8 @@ class UnfinishedMultiplicityObjective implements IObjective { | |||
34 | override setLevel(int level) { | 34 | override setLevel(int level) { |
35 | throw new UnsupportedOperationException | 35 | throw new UnsupportedOperationException |
36 | } | 36 | } |
37 | |||
38 | def isContainment() { | ||
39 | return this.unfinishedMultiplicity.containment | ||
40 | } | ||
37 | } | 41 | } |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend index 74500cc2..d879d4cc 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend | |||
@@ -14,9 +14,12 @@ import org.eclipse.xtend.lib.annotations.Accessors | |||
14 | 14 | ||
15 | /** | 15 | /** |
16 | * Based on {@link SolutionStore.BestSolutionSaver}. | 16 | * Based on {@link SolutionStore.BestSolutionSaver}. |
17 | * | ||
18 | * Will also automatically fill any missing numerical values in the saved solutions | ||
19 | * using the supplied {@link NumericSolver}. | ||
17 | */ | 20 | */ |
18 | class ViatraReasonerSolutionSaver implements ISolutionSaver { | 21 | class ViatraReasonerSolutionSaver implements ISolutionSaver { |
19 | @Accessors val solutionCopier = new SolutionCopier | 22 | @Accessors val SolutionCopier solutionCopier |
20 | @Accessors val DiversityChecker diversityChecker | 23 | @Accessors val DiversityChecker diversityChecker |
21 | val boolean hasExtremalObjectives | 24 | val boolean hasExtremalObjectives |
22 | val int numberOfRequiredSolutions | 25 | val int numberOfRequiredSolutions |
@@ -25,11 +28,12 @@ class ViatraReasonerSolutionSaver implements ISolutionSaver { | |||
25 | 28 | ||
26 | @Accessors(PUBLIC_SETTER) var Map<Object, Solution> solutionsCollection | 29 | @Accessors(PUBLIC_SETTER) var Map<Object, Solution> solutionsCollection |
27 | 30 | ||
28 | new(IObjective[][] leveledExtremalObjectives, int numberOfRequiredSolutions, DiversityChecker diversityChecker) { | 31 | new(IObjective[][] leveledExtremalObjectives, int numberOfRequiredSolutions, DiversityChecker diversityChecker, NumericSolver numericSolver) { |
29 | this.diversityChecker = diversityChecker | 32 | this.diversityChecker = diversityChecker |
30 | comparatorHelper = new ObjectiveComparatorHelper(leveledExtremalObjectives) | 33 | comparatorHelper = new ObjectiveComparatorHelper(leveledExtremalObjectives) |
31 | hasExtremalObjectives = leveledExtremalObjectives.exists[!empty] | 34 | hasExtremalObjectives = leveledExtremalObjectives.exists[!empty] |
32 | this.numberOfRequiredSolutions = numberOfRequiredSolutions | 35 | this.numberOfRequiredSolutions = numberOfRequiredSolutions |
36 | this.solutionCopier = new SolutionCopier(numericSolver) | ||
33 | } | 37 | } |
34 | 38 | ||
35 | override saveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) { | 39 | override saveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) { |
@@ -139,4 +143,8 @@ class ViatraReasonerSolutionSaver implements ISolutionSaver { | |||
139 | } | 143 | } |
140 | solutionsCollection.size < numberOfRequiredSolutions | 144 | solutionsCollection.size < numberOfRequiredSolutions |
141 | } | 145 | } |
146 | |||
147 | def getTotalCopierRuntime() { | ||
148 | solutionCopier.totalCopierRuntime | ||
149 | } | ||
142 | } | 150 | } |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/WF2ObjectiveConverter.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/WF2ObjectiveConverter.xtend index 63d78220..6d772f32 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/WF2ObjectiveConverter.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/WF2ObjectiveConverter.xtend | |||
@@ -13,12 +13,10 @@ import org.eclipse.viatra.query.runtime.api.IQuerySpecification | |||
13 | import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher | 13 | import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher |
14 | 14 | ||
15 | class WF2ObjectiveConverter { | 15 | class WF2ObjectiveConverter { |
16 | static val UNFINISHED_WFS_NAME = "unfinishedWFs" | ||
17 | static val INVALIDATED_WFS_NAME = "invalidatedWFs" | 16 | static val INVALIDATED_WFS_NAME = "invalidatedWFs" |
18 | 17 | ||
19 | def createCompletenessObjective( | 18 | def createCompletenessObjective( |
20 | Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedWF) { | 19 | Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedWF) { |
21 | // createConstraintObjective(UNFINISHED_WFS_NAME, unfinishedWF) | ||
22 | new UnfinishedWFObjective(unfinishedWF) | 20 | new UnfinishedWFObjective(unfinishedWF) |
23 | } | 21 | } |
24 | 22 | ||
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.visualisation/src/hu/bme/mit/inf/dslreasoner/visualisation/pi2graphviz/GraphvizV8WithMemory.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.visualisation/src/hu/bme/mit/inf/dslreasoner/visualisation/pi2graphviz/GraphvizV8WithMemory.xtend new file mode 100644 index 00000000..542289d4 --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.visualisation/src/hu/bme/mit/inf/dslreasoner/visualisation/pi2graphviz/GraphvizV8WithMemory.xtend | |||
@@ -0,0 +1,16 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.visualisation.pi2graphviz | ||
2 | |||
3 | import guru.nidi.graphviz.engine.GraphvizV8Engine | ||
4 | |||
5 | class GraphvizV8WithMemory extends GraphvizV8Engine { | ||
6 | val int memory; | ||
7 | new(int memory) { | ||
8 | this.memory = memory | ||
9 | //this. | ||
10 | } | ||
11 | |||
12 | override protected jsInitEnv() { | ||
13 | println super.jsInitEnv() | ||
14 | super.jsInitEnv() | ||
15 | } | ||
16 | } | ||
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.visualisation/src/hu/bme/mit/inf/dslreasoner/visualisation/pi2graphviz/PartialInterpretation2Graphviz.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.visualisation/src/hu/bme/mit/inf/dslreasoner/visualisation/pi2graphviz/PartialInterpretation2Graphviz.xtend index 78326207..cd0b3e00 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.visualisation/src/hu/bme/mit/inf/dslreasoner/visualisation/pi2graphviz/PartialInterpretation2Graphviz.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.visualisation/src/hu/bme/mit/inf/dslreasoner/visualisation/pi2graphviz/PartialInterpretation2Graphviz.xtend | |||
@@ -30,6 +30,7 @@ import org.eclipse.xtext.xbase.lib.Functions.Function1 | |||
30 | import static guru.nidi.graphviz.model.Factory.* | 30 | import static guru.nidi.graphviz.model.Factory.* |
31 | 31 | ||
32 | import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.* | 32 | import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.* |
33 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PrimitiveElement | ||
33 | 34 | ||
34 | class GraphvizVisualiser implements PartialInterpretationVisualiser { | 35 | class GraphvizVisualiser implements PartialInterpretationVisualiser { |
35 | 36 | ||
@@ -106,10 +107,10 @@ class GraphvizVisualiser implements PartialInterpretationVisualiser { | |||
106 | // elements2Node.put(newElement,image) | 107 | // elements2Node.put(newElement,image) |
107 | // } | 108 | // } |
108 | 109 | ||
109 | partialInterpretation.newElements.filter(BooleanElement).drawDataTypes([it.value.toString],elements2Node,elements2ID) | 110 | //partialInterpretation.newElements.filter(BooleanElement).drawDataTypes([it.value.toString],elements2Node,elements2ID) |
110 | partialInterpretation.newElements.filter(IntegerElement).drawDataTypes([it.value.toString],elements2Node,elements2ID) | 111 | //partialInterpretation.newElements.filter(IntegerElement).drawDataTypes([it.value.toString],elements2Node,elements2ID) |
111 | partialInterpretation.newElements.filter(StringElement).drawDataTypes(['''"«it.value.toString»"'''],elements2Node,elements2ID) | 112 | //partialInterpretation.newElements.filter(StringElement).drawDataTypes(['''"«it.value.toString»"'''],elements2Node,elements2ID) |
112 | partialInterpretation.newElements.filter(RealElement).drawDataTypes([it.value.toString],elements2Node,elements2ID) | 113 | //partialInterpretation.newElements.filter(RealElement).drawDataTypes([it.value.toString],elements2Node,elements2ID) |
113 | 114 | ||
114 | // Drawing the edges | 115 | // Drawing the edges |
115 | val edges = new HashMap | 116 | val edges = new HashMap |
@@ -135,35 +136,51 @@ class GraphvizVisualiser implements PartialInterpretationVisualiser { | |||
135 | return new GraphvizVisualisation(graph) | 136 | return new GraphvizVisualisation(graph) |
136 | } | 137 | } |
137 | 138 | ||
138 | def protected <T extends DefinedElement> void drawDataTypes(Iterable<T> collection, Function1<T,String> namer, HashMap<DefinedElement, Node> elements2Node, HashMap<DefinedElement, String> elements2ID) { | 139 | // def protected <T extends DefinedElement> void drawDataTypes(Iterable<T> collection, Function1<T,String> namer, HashMap<DefinedElement, Node> elements2Node, HashMap<DefinedElement, String> elements2ID) { |
139 | for(booleanElementIndex: 0..<collection.size) { | 140 | // for(booleanElementIndex: 0..<collection.size) { |
140 | val newElement = collection.get(booleanElementIndex) | 141 | // val newElement = collection.get(booleanElementIndex) |
141 | val id = namer.apply(newElement) | 142 | // val name = namer.apply(newElement) |
142 | val image = drawElement(newElement,id,false,emptySet,emptySet) | 143 | // val image = drawElement(newElement,name,newElement.lookup(elements2ID),false,emptySet,emptySet) |
143 | elements2ID.put(newElement,id) | 144 | // elements2Node.put(newElement,image) |
144 | elements2Node.put(newElement,image) | 145 | // } |
145 | } | 146 | // } |
146 | } | ||
147 | 147 | ||
148 | def protected drawElement(DefinedElement element, String ID, boolean old, Set<Type> mustTypes, Set<Type> mayTypes) { | 148 | def protected drawElement(DefinedElement element, String ID, boolean old, Set<Type> mustTypes, Set<Type> mayTypes) { |
149 | var tableStyle = ''' CELLSPACING="0" BORDER="2" CELLBORDER="0" CELLPADDING="1" STYLE="ROUNDED"''' | 149 | var tableStyle = ''' CELLSPACING="0" BORDER="2" CELLBORDER="0" CELLPADDING="1" STYLE="ROUNDED"''' |
150 | if(typeColoringStyle==TypeColoringStyle::AVERAGE) { | 150 | if(typeColoringStyle==TypeColoringStyle::AVERAGE) { |
151 | tableStyle += ''' BGCOLOR="#«typePredicateColor(mustTypes).toBackgroundColorString»"''' | 151 | tableStyle += ''' BGCOLOR="#«typePredicateColor(mustTypes).toBackgroundColorString»"''' |
152 | } | 152 | } |
153 | val mainLabel = if(element.name !== null) { | 153 | val mainLabel = if(element instanceof PrimitiveElement) { |
154 | if(element.isValueSet) { | ||
155 | if(element instanceof BooleanElement) { element.value.toString } | ||
156 | else if(element instanceof IntegerElement) { element.value.toString } | ||
157 | else if(element instanceof RealElement) { element.value.toString } | ||
158 | else if(element instanceof StringElement) { "\""+element.value.toString+"\"" } | ||
159 | } else { | ||
160 | "?" | ||
161 | } | ||
162 | }else if(element.name !== null) { | ||
154 | val parts = element.name.split("\\s+") | 163 | val parts = element.name.split("\\s+") |
155 | textWithSubSup(parts.getOrNull(0),parts.getOrNull(1),parts.getOrNull(2),null) | 164 | textWithSubSup(parts.getOrNull(0),parts.getOrNull(1),parts.getOrNull(2),null) |
156 | } else { | 165 | } else { |
157 | val parts = ID.split("\\s+") | 166 | val parts = ID.split("\\s+") |
158 | textWithSubSup(parts.get(0),parts.get(1),parts.getOrNull(2),null) | 167 | textWithSubSup(parts.getOrNull(0),parts.getOrNull(1),parts.getOrNull(2),null) |
159 | } | 168 | } |
160 | val label = Label.html( | 169 | val hasNoCompexType = (mustTypes.empty) && (mayTypes.empty) |
170 | |||
171 | val label = if(hasNoCompexType) { | ||
172 | Label.html( | ||
173 | '''<TABLE«tableStyle»>'''+ | ||
174 | '''<TR><TD COLSPAN="2"> «mainLabel» </TD></TR>'''+ | ||
175 | '''</TABLE>''') | ||
176 | } else { | ||
177 | Label.html( | ||
161 | '''<TABLE«tableStyle»>'''+ | 178 | '''<TABLE«tableStyle»>'''+ |
162 | '''<TR><TD COLSPAN="2" BORDER="2" SIDES="B">«mainLabel»</TD></TR>'''+ | 179 | '''<TR><TD COLSPAN="2" BORDER="2" SIDES="B">«mainLabel»</TD></TR>'''+ |
163 | '''«FOR mustTypeName : mustTypes.map[it.name].sort»«typePredicateDescription(mustTypeName,true)»«ENDFOR»'''+ | 180 | '''«FOR mustTypeName : mustTypes.map[it.name].sort»«typePredicateDescription(mustTypeName,true)»«ENDFOR»'''+ |
164 | '''«FOR mayTypeName : mayTypes.map[it.name].sort»«typePredicateDescription(mayTypeName,false)»«ENDFOR»'''+ | 181 | '''«FOR mayTypeName : mayTypes.map[it.name].sort»«typePredicateDescription(mayTypeName,false)»«ENDFOR»'''+ |
165 | '''</TABLE>''') | 182 | '''</TABLE>''') |
166 | 183 | } | |
167 | val node = node(ID).with(label).with( | 184 | val node = node(ID).with(label).with( |
168 | Shape.NONE | 185 | Shape.NONE |
169 | //, | 186 | //, |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.visualisation/src/hu/bme/mit/inf/dslreasoner/visualisation/pi2graphviz/VisualisationQueque.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.visualisation/src/hu/bme/mit/inf/dslreasoner/visualisation/pi2graphviz/VisualisationQueque.xtend index b067ba7d..6f003f80 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.visualisation/src/hu/bme/mit/inf/dslreasoner/visualisation/pi2graphviz/VisualisationQueque.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.visualisation/src/hu/bme/mit/inf/dslreasoner/visualisation/pi2graphviz/VisualisationQueque.xtend | |||
@@ -3,15 +3,15 @@ package hu.bme.mit.inf.dslreasoner.visualisation.pi2graphviz | |||
3 | import guru.nidi.graphviz.engine.Format | 3 | import guru.nidi.graphviz.engine.Format |
4 | import guru.nidi.graphviz.engine.Graphviz | 4 | import guru.nidi.graphviz.engine.Graphviz |
5 | import guru.nidi.graphviz.engine.GraphvizEngine | 5 | import guru.nidi.graphviz.engine.GraphvizEngine |
6 | import guru.nidi.graphviz.engine.GraphvizV8Engine | ||
7 | import guru.nidi.graphviz.model.Graph | 6 | import guru.nidi.graphviz.model.Graph |
8 | import java.io.File | 7 | import java.io.File |
9 | import java.io.IOException | 8 | import java.io.IOException |
10 | import java.util.concurrent.BlockingQueue | 9 | import java.util.concurrent.BlockingQueue |
11 | import java.util.concurrent.CompletableFuture | 10 | import java.util.concurrent.CompletableFuture |
12 | import java.util.concurrent.LinkedBlockingQueue | 11 | import java.util.concurrent.LinkedBlockingQueue |
13 | import org.eclipse.xtend.lib.annotations.Data | ||
14 | import java.util.function.Consumer | 12 | import java.util.function.Consumer |
13 | import org.eclipse.xtend.lib.annotations.Data | ||
14 | import guru.nidi.graphviz.engine.GraphvizV8Engine | ||
15 | 15 | ||
16 | class VisualisationQueque { | 16 | class VisualisationQueque { |
17 | val BlockingQueue<VisualisationQueueEntry> taskQueue = new LinkedBlockingQueue | 17 | val BlockingQueue<VisualisationQueueEntry> taskQueue = new LinkedBlockingQueue |
@@ -45,7 +45,7 @@ class VisualisationQueque { | |||
45 | } else { | 45 | } else { |
46 | runnerThread = new Thread(new Runnable() { | 46 | runnerThread = new Thread(new Runnable() { |
47 | override run() { | 47 | override run() { |
48 | val engine = new GraphvizV8Engine() | 48 | val engine = new GraphvizV8Engine |
49 | val nullConsumer = new Consumer<GraphvizEngine>() { | 49 | val nullConsumer = new Consumer<GraphvizEngine>() { |
50 | override accept(GraphvizEngine t) {} | 50 | override accept(GraphvizEngine t) {} |
51 | } | 51 | } |
@@ -69,7 +69,7 @@ class VisualisationQueque { | |||
69 | private def execute(GraphvizEngine engine, Graph document, File targetFile, Format format) { | 69 | private def execute(GraphvizEngine engine, Graph document, File targetFile, Format format) { |
70 | Graphviz.useEngine(engine); | 70 | Graphviz.useEngine(engine); |
71 | try { | 71 | try { |
72 | Graphviz.fromGraph(document).render(format).toFile(targetFile) | 72 | Graphviz.fromGraph(document).totalMemory(536870912).render(format).toFile(targetFile) |
73 | return null | 73 | return null |
74 | } catch(IOException e){ | 74 | } catch(IOException e){ |
75 | return e.message | 75 | return e.message |