aboutsummaryrefslogtreecommitdiffstats
path: root/Solvers
diff options
context:
space:
mode:
Diffstat (limited to 'Solvers')
-rw-r--r--Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/.classpath26
-rw-r--r--Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/META-INF/MANIFEST.MF7
-rw-r--r--Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/src/hu/bme/mit/inf/dlsreasoner/alloy/reasoner/AlloySolver.xtend2
-rw-r--r--Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/src/hu/bme/mit/inf/dlsreasoner/alloy/reasoner/builder/Alloy2LogicMapper.xtend2
-rw-r--r--Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/src/hu/bme/mit/inf/dlsreasoner/alloy/reasoner/builder/AlloyHandler.xtend17
-rw-r--r--Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/src/hu/bme/mit/inf/dlsreasoner/alloy/reasoner/builder/RunCommandMapper.xtend19
-rw-r--r--Solvers/Alloy-Solver/hu.bme.mit.inf.dslreasoner.alloy.language/.launch/Generate Language Infrastructure (hu.bme.mit.inf.dslreasoner.alloy.language).launch18
-rw-r--r--Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/.classpath15
-rw-r--r--Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/.gitignore2
-rw-r--r--Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/.project28
-rw-r--r--Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/META-INF/MANIFEST.MF10
-rw-r--r--Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/build.properties4
-rw-r--r--Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/cpp/CMakeLists.txt23
-rw-r--r--Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/cpp/viatracbc.cpp277
-rw-r--r--Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/cpp/viatracbc.hpp16
-rwxr-xr-xSolvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/lib/libviatracbc.sobin0 -> 33944 bytes
-rw-r--r--Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/src/hu/bme/mit/inf/dslreasoner/ilp/cbc/CbcException.java30
-rw-r--r--Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/src/hu/bme/mit/inf/dslreasoner/ilp/cbc/CbcResult.java54
-rw-r--r--Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/src/hu/bme/mit/inf/dslreasoner/ilp/cbc/CbcSolver.java71
-rw-r--r--Solvers/SMT-Solver/com.microsoft.z3/.classpath15
-rw-r--r--Solvers/SMT-Solver/com.microsoft.z3/.gitignore1
-rw-r--r--Solvers/SMT-Solver/com.microsoft.z3/.project28
-rw-r--r--Solvers/SMT-Solver/com.microsoft.z3/META-INF/MANIFEST.MF22
-rw-r--r--Solvers/SMT-Solver/com.microsoft.z3/build.properties3
-rw-r--r--Solvers/SMT-Solver/com.microsoft.z3/lib/libz3.dllbin0 -> 15446904 bytes
-rwxr-xr-xSolvers/SMT-Solver/com.microsoft.z3/lib/libz3.dylibbin0 -> 22033856 bytes
-rwxr-xr-xSolvers/SMT-Solver/com.microsoft.z3/lib/libz3.sobin0 -> 26036232 bytes
-rw-r--r--Solvers/SMT-Solver/com.microsoft.z3/lib/libz3java.dllbin0 -> 109432 bytes
-rwxr-xr-xSolvers/SMT-Solver/com.microsoft.z3/lib/libz3java.dylibbin0 -> 166568 bytes
-rwxr-xr-xSolvers/SMT-Solver/com.microsoft.z3/lib/libz3java.sobin0 -> 271560 bytes
-rw-r--r--Solvers/SMT-Solver/hu.bme.mit.inf.dslreasoner.smt.language/.launch/Generate Language Infrastructure (hu.bme.mit.inf.dslreasoner.smt.language).launch17
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/META-INF/MANIFEST.MF7
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/build.properties3
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/Modality.java31
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationMethodProvider.xtend187
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ScopePropagator.xtend166
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/AbstractPolyhedronSaturationOperator.xtend53
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/CbcPolyhedronSolver.xtend241
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/LinearTypeConstraintHint.xtend30
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/MultiplicityGoalConstraintCalculator.xtend (renamed from Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/MultiplicityGoalConstraintCalculator.xtend)21
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagator.xtend569
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronSolver.xtend179
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/RelationConstraintCalculator.xtend139
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ScopePropagator.xtend134
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ScopePropagatorStrategy.xtend71
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/TypeHierarchyScopePropagator.xtend85
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/Z3PolyhedronSolver.xtend272
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/Interval.xtend584
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/IntervalAggregationMode.java99
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/IntervalAggregationOperator.xtend48
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/IntervalHullAggregatorOperator.xtend87
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/IntervalRedBlackNode.xtend177
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/RedBlackNode.java1392
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/Reference.java51
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/aggregators/IntervalAggregatorFactory.xtend50
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/aggregators/intervalHull.xtend74
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/GenericTypeIndexer.xtend321
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/GenericTypeRefinementGenerator.xtend186
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PatternGenerator.xtend158
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PatternProvider.xtend146
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/RelationDefinitionIndexer.xtend6
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/RelationRefinementGenerator.xtend102
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/TypeIndexer.xtend126
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/TypeIndexerWithPreliminaryTypeAnalysis.xtend144
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/TypeRefinementGenerator.xtend83
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/TypeRefinementWithPreliminaryTypeAnalysis.xtend6
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/UnfinishedIndexer.xtend231
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/rules/GoalConstraintProvider.xtend96
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/rules/RefinementRuleProvider.xtend79
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/PartialInterpretation.java24
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/PartialinterpretationPackage.java60
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/Scope.java24
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/BinaryElementRelationLinkImpl.java4
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/BooleanElementImpl.java4
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/IntegerElementImpl.java4
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/NaryRelationLinkElementImpl.java6
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/NaryRelationLinkImpl.java1
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialComplexTypeInterpretationImpl.java3
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialConstantInterpretationImpl.java2
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialFunctionInterpretationImpl.java2
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialInterpretationImpl.java73
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialRelationInterpretationImpl.java7
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialTypeInterpratationImpl.java2
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialinterpretationFactoryImpl.java19
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialinterpretationPackageImpl.java88
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PrimitiveElementImpl.java4
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/RealElementImpl.java4
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/ScopeImpl.java64
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/StringElementImpl.java4
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/UnaryElementRelationLinkImpl.java2
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/model/PartialInterpretation.ecore6
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/model/PartialInterpretation.genmodel14
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretation2logic/InstanceModel2PartialInterpretation.xtend23
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/META-INF/MANIFEST.MF3
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ModelGenerationMethodBasedGlobalConstraint.xtend22
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasoner.xtend280
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasonerConfiguration.xtend55
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BasicScopeGlobalConstraint.xtend103
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BestFirstStrategyForModelGeneration.java131
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/DiversityChecker.xtend184
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/DseUtils.xtend66
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/InconsistentScopeGlobalConstraint.xtend25
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/LoggerSolutionFoundHandler.xtend24
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ModelGenerationCompositeObjective.xtend90
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/NumericSolver.xtend17
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/PartialModelAsLogicInterpretation.xtend2
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ScopeObjective.xtend6
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionCopier.xtend86
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionStoreWithCopy.xtend6
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionStoreWithDiversityDescriptor.xtend120
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SurelyViolatedObjectiveGlobalConstraint.xtend27
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/UnfinishedMultiplicityObjective.xtend15
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/UnfinishedWFObjective.xtend54
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend150
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/WF2ObjectiveConverter.xtend43
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/AbstractThreeValuedObjective.xtend35
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/CompositeDirectionalThresholdObjective.xtend62
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/DirectionalThresholdObjective.xtend164
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/IThreeValuedObjective.xtend10
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/MatchCostObjective.xtend52
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/ObjectiveKind.java60
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/QueryBasedObjective.xtend48
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/ThreeValuedCostObjective.xtend85
123 files changed, 8065 insertions, 1545 deletions
diff --git a/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/.classpath b/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/.classpath
index de68b5f7..25b7f16f 100644
--- a/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/.classpath
+++ b/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/.classpath
@@ -1,11 +1,15 @@
1<?xml version="1.0" encoding="UTF-8"?> 1<?xml version="1.0" encoding="UTF-8"?>
2<classpath> 2<classpath>
3 <classpathentry kind="src" path="xtend-gen"/> 3 <classpathentry kind="src" path="xtend-gen"/>
4 <classpathentry kind="src" path="queries"/> 4 <classpathentry kind="src" path="queries"/>
5 <classpathentry kind="src" path="vql-gen"/> 5 <classpathentry kind="src" path="vql-gen"/>
6 <classpathentry exported="true" kind="lib" path="lib/alloy4.2_2015-02-22.jar"/> 6 <classpathentry exported="true" kind="lib" path="lib/alloy4.2_2015-02-22.jar"/>
7 <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/> 7 <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
8 <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> 8 <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
9 <classpathentry kind="src" path="src"/> 9 <classpathentry kind="src" path="src">
10 <classpathentry kind="output" path="bin"/> 10 <attributes>
11</classpath> 11 <attribute name="org.eclipse.jdt.launching.CLASSPATH_ATTR_LIBRARY_PATH_ENTRY" value="hu.bme.mit.inf.dlsreasoner.alloy.reasoner/lib"/>
12 </attributes>
13 </classpathentry>
14 <classpathentry kind="output" path="bin"/>
15</classpath>
diff --git a/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/META-INF/MANIFEST.MF b/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/META-INF/MANIFEST.MF
index b944302b..75581def 100644
--- a/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/META-INF/MANIFEST.MF
+++ b/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/META-INF/MANIFEST.MF
@@ -20,7 +20,8 @@ Require-Bundle: com.google.guava,
20 org.eclipse.viatra.query.runtime.base.itc;bundle-version="1.3.0", 20 org.eclipse.viatra.query.runtime.base.itc;bundle-version="1.3.0",
21 hu.bme.mit.inf.dslreasoner.ecore2logic;bundle-version="1.0.0", 21 hu.bme.mit.inf.dslreasoner.ecore2logic;bundle-version="1.0.0",
22 org.eclipse.viatra.query.runtime;bundle-version="2.0.0" 22 org.eclipse.viatra.query.runtime;bundle-version="2.0.0"
23Import-Package: org.apache.log4j;version="1.2.15"
24Automatic-Module-Name: hu.bme.mit.inf.dlsreasoner.alloy.reasoner
25Bundle-ActivationPolicy: lazy
26Bundle-RequiredExecutionEnvironment: JavaSE-1.8 23Bundle-RequiredExecutionEnvironment: JavaSE-1.8
24Bundle-ActivationPolicy: lazy
25Bundle-NativeCode: libminisat.so;osname=Linux;processor=x86_64
26Automatic-Module-Name: hu.bme.mit.inf.dlsreasoner.alloy.reasoner
27Import-Package: org.apache.log4j;version="1.2.15"
diff --git a/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/src/hu/bme/mit/inf/dlsreasoner/alloy/reasoner/AlloySolver.xtend b/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/src/hu/bme/mit/inf/dlsreasoner/alloy/reasoner/AlloySolver.xtend
index f6b0b4a5..1eb6442b 100644
--- a/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/src/hu/bme/mit/inf/dlsreasoner/alloy/reasoner/AlloySolver.xtend
+++ b/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/src/hu/bme/mit/inf/dlsreasoner/alloy/reasoner/AlloySolver.xtend
@@ -62,7 +62,7 @@ class AlloySolver extends LogicReasoner{
62 val result2 = handler.callSolver(alloyProblem,workspace,alloyConfig,alloyCode) 62 val result2 = handler.callSolver(alloyProblem,workspace,alloyConfig,alloyCode)
63 alloyConfig.progressMonitor.workedSearchFinished 63 alloyConfig.progressMonitor.workedSearchFinished
64 64
65 val logicResult = backwardMapper.transformOutput(problem,configuration.solutionScope.numberOfRequiredSolution,result2,forwardTrace,transformationTime) 65 val logicResult = backwardMapper.transformOutput(problem,configuration.solutionScope.numberOfRequiredSolutions,result2,forwardTrace,transformationTime)
66 alloyConfig.progressMonitor.workedBackwardTransformationFinished 66 alloyConfig.progressMonitor.workedBackwardTransformationFinished
67 //val solverFinish = System.currentTimeMillis-solverStart 67 //val solverFinish = System.currentTimeMillis-solverStart
68 // Finish: Solving Alloy problem 68 // Finish: Solving Alloy problem
diff --git a/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/src/hu/bme/mit/inf/dlsreasoner/alloy/reasoner/builder/Alloy2LogicMapper.xtend b/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/src/hu/bme/mit/inf/dlsreasoner/alloy/reasoner/builder/Alloy2LogicMapper.xtend
index 2efd6b29..328ca176 100644
--- a/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/src/hu/bme/mit/inf/dlsreasoner/alloy/reasoner/builder/Alloy2LogicMapper.xtend
+++ b/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/src/hu/bme/mit/inf/dlsreasoner/alloy/reasoner/builder/Alloy2LogicMapper.xtend
@@ -9,7 +9,7 @@ class Alloy2LogicMapper {
9 public def transformOutput(LogicProblem problem, int requiredNumberOfSolution, MonitoredAlloySolution monitoredAlloySolution, Logic2AlloyLanguageMapperTrace trace, long transformationTime) { 9 public def transformOutput(LogicProblem problem, int requiredNumberOfSolution, MonitoredAlloySolution monitoredAlloySolution, Logic2AlloyLanguageMapperTrace trace, long transformationTime) {
10 val models = monitoredAlloySolution.aswers.map[it.key].toList 10 val models = monitoredAlloySolution.aswers.map[it.key].toList
11 11
12 if(!monitoredAlloySolution.finishedBeforeTimeout) { 12 if(models.empty || !monitoredAlloySolution.finishedBeforeTimeout) {
13 return createInsuficientResourcesResult => [ 13 return createInsuficientResourcesResult => [
14 it.problem = problem 14 it.problem = problem
15 it.representation += models 15 it.representation += models
diff --git a/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/src/hu/bme/mit/inf/dlsreasoner/alloy/reasoner/builder/AlloyHandler.xtend b/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/src/hu/bme/mit/inf/dlsreasoner/alloy/reasoner/builder/AlloyHandler.xtend
index 9b4265b9..451aad6e 100644
--- a/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/src/hu/bme/mit/inf/dlsreasoner/alloy/reasoner/builder/AlloyHandler.xtend
+++ b/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/src/hu/bme/mit/inf/dlsreasoner/alloy/reasoner/builder/AlloyHandler.xtend
@@ -101,15 +101,8 @@ class AlloyHandler {
101 try{ 101 try{
102 answers = future.get(configuration.runtimeLimit,TimeUnit.SECONDS) 102 answers = future.get(configuration.runtimeLimit,TimeUnit.SECONDS)
103 finished = true 103 finished = true
104 } catch (TimeoutException ex) { 104 } catch (TimeoutException | InterruptedException | ExecutionException e) {
105 // handle the timeout 105 future.cancel(true)
106 } catch (InterruptedException e) {
107 // handle the interrupts
108 } catch (ExecutionException e) {
109 // handle other exceptions
110 } finally {
111 future.cancel(true);
112
113 answers = callable.partialAnswers 106 answers = callable.partialAnswers
114 finished = false 107 finished = false
115 } 108 }
@@ -195,7 +188,7 @@ class AlloyCallerWithTimeout implements Callable<List<Pair<A4Solution,Long>>>{
195 } else { 188 } else {
196 lastAnswer = lastAnswer.next 189 lastAnswer = lastAnswer.next
197 } 190 }
198 configuration.progressMonitor.workedBackwardTransformation(configuration.solutionScope.numberOfRequiredSolution) 191 configuration.progressMonitor.workedBackwardTransformation(configuration.solutionScope.numberOfRequiredSolutions)
199 192
200 val runtime = System.currentTimeMillis -startTime 193 val runtime = System.currentTimeMillis -startTime
201 synchronized(this) { 194 synchronized(this) {
@@ -212,8 +205,8 @@ class AlloyCallerWithTimeout implements Callable<List<Pair<A4Solution,Long>>>{
212 } 205 }
213 206
214 def hasEnoughSolution(List<?> answers) { 207 def hasEnoughSolution(List<?> answers) {
215 if(configuration.solutionScope.numberOfRequiredSolution < 0) return false 208 if(configuration.solutionScope.numberOfRequiredSolutions < 0) return false
216 else return answers.size() == configuration.solutionScope.numberOfRequiredSolution 209 else return answers.size() == configuration.solutionScope.numberOfRequiredSolutions
217 } 210 }
218 211
219 public def getPartialAnswers() { 212 public def getPartialAnswers() {
diff --git a/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/src/hu/bme/mit/inf/dlsreasoner/alloy/reasoner/builder/RunCommandMapper.xtend b/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/src/hu/bme/mit/inf/dlsreasoner/alloy/reasoner/builder/RunCommandMapper.xtend
index 494197bc..b74017d8 100644
--- a/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/src/hu/bme/mit/inf/dlsreasoner/alloy/reasoner/builder/RunCommandMapper.xtend
+++ b/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/src/hu/bme/mit/inf/dlsreasoner/alloy/reasoner/builder/RunCommandMapper.xtend
@@ -9,8 +9,12 @@ import hu.bme.mit.inf.dslreasoner.alloyLanguage.ALSString
9import hu.bme.mit.inf.dslreasoner.alloyLanguage.ALSTerm 9import hu.bme.mit.inf.dslreasoner.alloyLanguage.ALSTerm
10import hu.bme.mit.inf.dslreasoner.alloyLanguage.AlloyLanguageFactory 10import hu.bme.mit.inf.dslreasoner.alloyLanguage.AlloyLanguageFactory
11import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicSolverConfiguration 11import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicSolverConfiguration
12import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type
13import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeDefinition
12import java.util.List 14import java.util.List
13 15
16import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.*
17
14class RunCommandMapper { 18class RunCommandMapper {
15 val extension AlloyLanguageFactory factory = AlloyLanguageFactory.eINSTANCE 19 val extension AlloyLanguageFactory factory = AlloyLanguageFactory.eINSTANCE
16 val Logic2AlloyLanguageMapper_Support support = new Logic2AlloyLanguageMapper_Support; 20 val Logic2AlloyLanguageMapper_Support support = new Logic2AlloyLanguageMapper_Support;
@@ -89,16 +93,18 @@ class RunCommandMapper {
89 ] 93 ]
90 94
91 for(upperLimit : config.typeScopes.maxNewElementsByType.entrySet) { 95 for(upperLimit : config.typeScopes.maxNewElementsByType.entrySet) {
92 val limit = upperLimit.value 96 val type = upperLimit.key
97 val limit = upperLimit.value + getExistingCount(type)
93 if(limit != LogicSolverConfiguration::Unlimited) { 98 if(limit != LogicSolverConfiguration::Unlimited) {
94 this.typeScopeMapping.addUpperMultiplicity(specification,upperLimit.key,limit,mapper,trace) 99 this.typeScopeMapping.addUpperMultiplicity(specification,type,limit,mapper,trace)
95 } 100 }
96 } 101 }
97 102
98 for(lowerLimit : config.typeScopes.minNewElementsByType.entrySet) { 103 for(lowerLimit : config.typeScopes.minNewElementsByType.entrySet) {
99 val limit = lowerLimit.value 104 val type = lowerLimit.key
105 val limit = lowerLimit.value + getExistingCount(type)
100 if(limit != 0) { 106 if(limit != 0) {
101 this.typeScopeMapping.addLowerMultiplicity(specification,lowerLimit.key,limit,mapper,trace) 107 this.typeScopeMapping.addLowerMultiplicity(specification,type,limit,mapper,trace)
102 } 108 }
103 } 109 }
104 110
@@ -106,6 +112,11 @@ class RunCommandMapper {
106 setStringScope(specification,config,specification.runCommand) 112 setStringScope(specification,config,specification.runCommand)
107 } 113 }
108 114
115 private def getExistingCount(Type type) {
116 val existing = type.transitiveClosureStar[it.subtypes].filter(TypeDefinition).map[elements].flatten.toSet
117 existing.size
118 }
119
109 protected def Boolean setStringScope(ALSDocument specification, AlloySolverConfiguration config, ALSRunCommand it) { 120 protected def Boolean setStringScope(ALSDocument specification, AlloySolverConfiguration config, ALSRunCommand it) {
110 if(config.typeScopes.maxNewStrings === LogicSolverConfiguration::Unlimited) { 121 if(config.typeScopes.maxNewStrings === LogicSolverConfiguration::Unlimited) {
111 throw new UnsupportedOperationException('''A string scope have to be specified for Alloy!''') 122 throw new UnsupportedOperationException('''A string scope have to be specified for Alloy!''')
diff --git a/Solvers/Alloy-Solver/hu.bme.mit.inf.dslreasoner.alloy.language/.launch/Generate Language Infrastructure (hu.bme.mit.inf.dslreasoner.alloy.language).launch b/Solvers/Alloy-Solver/hu.bme.mit.inf.dslreasoner.alloy.language/.launch/Generate Language Infrastructure (hu.bme.mit.inf.dslreasoner.alloy.language).launch
deleted file mode 100644
index 77031bf1..00000000
--- a/Solvers/Alloy-Solver/hu.bme.mit.inf.dslreasoner.alloy.language/.launch/Generate Language Infrastructure (hu.bme.mit.inf.dslreasoner.alloy.language).launch
+++ /dev/null
@@ -1,18 +0,0 @@
1<?xml version="1.0" encoding="UTF-8" standalone="no"?>
2<launchConfiguration type="org.eclipse.emf.mwe2.launch.Mwe2LaunchConfigurationType">
3<stringAttribute key="org.eclipse.debug.core.ATTR_REFRESH_SCOPE" value="${working_set:&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&#10;&lt;launchConfigurationWorkingSet factoryID=&quot;org.eclipse.ui.internal.WorkingSetFactory&quot; id=&quot;1299248699643_13&quot; label=&quot;working set&quot; name=&quot;working set&quot;&gt;&#10;&lt;item factoryID=&quot;org.eclipse.ui.internal.model.ResourceFactory&quot; path=&quot;/hu.bme.mit.inf.dslreasoner.alloy.language&quot; type=&quot;4&quot;/&gt;&#10;&lt;item factoryID=&quot;org.eclipse.ui.internal.model.ResourceFactory&quot; path=&quot;/hu.bme.mit.inf.dslreasoner.alloy.language.generator&quot; type=&quot;4&quot;/&gt;&#10;&lt;item factoryID=&quot;org.eclipse.ui.internal.model.ResourceFactory&quot; path=&quot;/hu.bme.mit.inf.dslreasoner.alloy.language.tests&quot; type=&quot;4&quot;/&gt;&#10;&lt;item factoryID=&quot;org.eclipse.ui.internal.model.ResourceFactory&quot; path=&quot;/hu.bme.mit.inf.dslreasoner.alloy.language.ui&quot; type=&quot;4&quot;/&gt;&#10;&lt;/launchConfigurationWorkingSet&gt;}"/>
4<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_PATHS">
5<listEntry value="/hu.bme.mit.inf.dslreasoner.alloy.language"/>
6</listAttribute>
7<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_TYPES">
8<listEntry value="4"/>
9</listAttribute>
10<listAttribute key="org.eclipse.debug.ui.favoriteGroups">
11<listEntry value="org.eclipse.debug.ui.launchGroup.debug"/>
12<listEntry value="org.eclipse.debug.ui.launchGroup.run"/>
13</listAttribute>
14<stringAttribute key="org.eclipse.jdt.launching.MAIN_TYPE" value="org.eclipse.emf.mwe2.launch.runtime.Mwe2Launcher"/>
15<stringAttribute key="org.eclipse.jdt.launching.PROGRAM_ARGUMENTS" value="src/hu/bme/mit/inf/dslreasoner/GenerateAlloyLanguage.mwe2"/>
16<stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value="hu.bme.mit.inf.dslreasoner.alloy.language"/>
17<stringAttribute key="org.eclipse.jdt.launching.VM_ARGUMENTS" value="-Xmx512m"/>
18</launchConfiguration>
diff --git a/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/.classpath b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/.classpath
new file mode 100644
index 00000000..e19039ae
--- /dev/null
+++ b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/.classpath
@@ -0,0 +1,15 @@
1<?xml version="1.0" encoding="UTF-8"?>
2<classpath>
3 <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
4 <attributes>
5 <attribute name="module" value="true"/>
6 </attributes>
7 </classpathentry>
8 <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
9 <classpathentry kind="src" path="src">
10 <attributes>
11 <attribute name="org.eclipse.jdt.launching.CLASSPATH_ATTR_LIBRARY_PATH_ENTRY" value="hu.bme.mit.inf.dslreasoner.ilp.cbc/lib"/>
12 </attributes>
13 </classpathentry>
14 <classpathentry kind="output" path="bin"/>
15</classpath>
diff --git a/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/.gitignore b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/.gitignore
new file mode 100644
index 00000000..0cc6a59e
--- /dev/null
+++ b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/.gitignore
@@ -0,0 +1,2 @@
1/bin/
2/cpp/build/
diff --git a/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/.project b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/.project
new file mode 100644
index 00000000..6c32e464
--- /dev/null
+++ b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/.project
@@ -0,0 +1,28 @@
1<?xml version="1.0" encoding="UTF-8"?>
2<projectDescription>
3 <name>hu.bme.mit.inf.dslreasoner.ilp.cbc</name>
4 <comment></comment>
5 <projects>
6 </projects>
7 <buildSpec>
8 <buildCommand>
9 <name>org.eclipse.jdt.core.javabuilder</name>
10 <arguments>
11 </arguments>
12 </buildCommand>
13 <buildCommand>
14 <name>org.eclipse.pde.ManifestBuilder</name>
15 <arguments>
16 </arguments>
17 </buildCommand>
18 <buildCommand>
19 <name>org.eclipse.pde.SchemaBuilder</name>
20 <arguments>
21 </arguments>
22 </buildCommand>
23 </buildSpec>
24 <natures>
25 <nature>org.eclipse.pde.PluginNature</nature>
26 <nature>org.eclipse.jdt.core.javanature</nature>
27 </natures>
28</projectDescription>
diff --git a/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/META-INF/MANIFEST.MF b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..04478746
--- /dev/null
+++ b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/META-INF/MANIFEST.MF
@@ -0,0 +1,10 @@
1Manifest-Version: 1.0
2Bundle-ManifestVersion: 2
3Bundle-Name: Cbc
4Bundle-SymbolicName: hu.bme.mit.inf.dslreasoner.ilp.cbc
5Bundle-Version: 1.0.0.qualifier
6Automatic-Module-Name: hu.bme.mit.inf.dslreasoner.ilp.cbc
7Export-Package: hu.bme.mit.inf.dslreasoner.ilp.cbc
8Bundle-NativeCode: libviatracbc.so;
9 osname=Linux;
10 processor=x86_64
diff --git a/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/build.properties b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/build.properties
new file mode 100644
index 00000000..34d2e4d2
--- /dev/null
+++ b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/build.properties
@@ -0,0 +1,4 @@
1source.. = src/
2output.. = bin/
3bin.includes = META-INF/,\
4 .
diff --git a/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/cpp/CMakeLists.txt b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/cpp/CMakeLists.txt
new file mode 100644
index 00000000..6169ae8f
--- /dev/null
+++ b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/cpp/CMakeLists.txt
@@ -0,0 +1,23 @@
1cmake_minimum_required(VERSION 3.10.2)
2project(hu.bme.mit.inf.dslreasoner.ilp.cbc)
3
4set(CMAKE_CXX_STANDARD 14)
5
6find_package(JNI REQUIRED)
7find_package(PkgConfig REQUIRED)
8
9pkg_check_modules(CBC REQUIRED cbc)
10
11add_library(viatracbc SHARED viatracbc.cpp)
12
13target_link_libraries(viatracbc
14 ${JAVA_JVM_LIBRARY}
15 ${CBC_LIBRARIES})
16target_include_directories(viatracbc
17 PUBLIC ${JNI_INCLUDE_DIRS}
18 PRIVATE ${CBC_INCLUDE_DIRS})
19
20set(VIATRACBC_NATIVES_DIR ${CMAKE_SOURCE_DIR}/../lib)
21add_custom_command(TARGET viatracbc POST_BUILD
22 COMMAND ${CMAKE_COMMAND} -E make_directory ${VIATRACBC_NATIVES_DIR}
23 COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:viatracbc> ${VIATRACBC_NATIVES_DIR})
diff --git a/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/cpp/viatracbc.cpp b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/cpp/viatracbc.cpp
new file mode 100644
index 00000000..34cab1dd
--- /dev/null
+++ b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/cpp/viatracbc.cpp
@@ -0,0 +1,277 @@
1
2#include <cmath>
3#include <cstdlib>
4#include <iostream>
5#include <stdexcept>
6
7#include <jni.h>
8
9#include "CbcBranchDefaultDecision.hpp"
10#include "CbcCompareDefault.hpp"
11#include "CbcHeuristic.hpp"
12#include "CbcHeuristicLocal.hpp"
13#include "CbcModel.hpp"
14#include "CglClique.hpp"
15#include "CglFlowCover.hpp"
16#include "CglGomory.hpp"
17#include "CglKnapsackCover.hpp"
18#include "CglMixedIntegerRounding.hpp"
19#include "CglOddHole.hpp"
20#include "CglProbing.hpp"
21#include "CoinModel.hpp"
22#include "OsiClpSolverInterface.hpp"
23
24#include "viatracbc.hpp"
25
26static const char *const kCbcExceptionClassName = "hu/bme/mit/inf/dslreasoner/ilp/cbc/CbcException";
27static const char *const kRuntimeExceptionClassName = "java/lang/RuntimeException";
28
29static const jint kCbcSolutionBounded = 0;
30static const jint kCbcSolutionUnbounded = 1;
31static const jint kCbcUnsat = 2;
32static const jint kCbcAbandoned = 3;
33static const jint kCbcTimeout = 4;
34static const jint kCbcError = 5;
35
36static CoinModel CreateModel(JNIEnv *env, jdoubleArray columnLowerBoundsArray,
37 jdoubleArray columnUpperBoundsArray, jintArray rowStartsArray, jintArray columnIndicesArray,
38 jdoubleArray entriedArray, jdoubleArray rowLowerBoundsArray, jdoubleArray rowUpperBoundsArray,
39 jdoubleArray objectiveArray, jboolean lpRelaxation);
40static void CreateModelColumns(JNIEnv *env, jdoubleArray columnLowerBoundsArray,
41 jdoubleArray columnUpperBoundsArray, jdoubleArray objectiveArray, jboolean lpRelaxation,
42 CoinModel &build);
43static void CreateModelRows(JNIEnv *env, jintArray rowStartsArray, jintArray columnIndicesArray,
44 jdoubleArray entriesArray, jdoubleArray rowLowerBoundsArray, jdoubleArray rowUpperBoundsArray,
45 CoinModel &build);
46static jint SolveModel(CoinModel &build, jdouble timeoutSeconds, jboolean silent, jdouble &value);
47static void ThrowException(JNIEnv *env, const char *message);
48
49template <
50 typename Array,
51 typename Element,
52 Element *(JNIEnv::*GetElementsPtr)(Array, jboolean *),
53 void (JNIEnv::*ReleaseElementsPtr)(Array, Element *, jint)
54>
55class PinnedArray {
56public:
57 PinnedArray(JNIEnv *env, Array array)
58 : env_{env}, array_{array}, elements_{(env->*GetElementsPtr)(array, nullptr)} {
59 if (elements_ == nullptr) {
60 throw std::runtime_error("Failed to pin array elements");
61 }
62 }
63 PinnedArray(const PinnedArray &) = delete;
64 PinnedArray(PinnedArray &&) = delete;
65 PinnedArray &operator=(const PinnedArray &) = delete;
66 PinnedArray &operator=(PinnedArray &&) = delete;
67 ~PinnedArray() {
68 (env_->*ReleaseElementsPtr)(array_, elements_, 0);
69 }
70
71 operator Element *() { return elements_; }
72 operator const Element *() const { return elements_; }
73
74private:
75 JNIEnv *env_;
76 Array array_;
77 Element *elements_;
78};
79
80using PinnedIntArray = PinnedArray<jintArray, jint, &JNIEnv::GetIntArrayElements, &JNIEnv::ReleaseIntArrayElements>;
81using PinnedDoubleArray = PinnedArray<jdoubleArray, jdouble, &JNIEnv::GetDoubleArrayElements, &JNIEnv::ReleaseDoubleArrayElements>;
82
83jint Java_hu_bme_mit_inf_dslreasoner_ilp_cbc_CbcSolver_solveIlpProblem(
84 JNIEnv *env, jclass klazz, jdoubleArray columnLowerBoundsArray, jdoubleArray columnUpperBoundsArray,
85 jintArray rowStartsArray, jintArray columnIndicesArray, jdoubleArray entriesArray,
86 jdoubleArray rowLowerBoundsArray, jdoubleArray rowUpperBoundsArray, jdoubleArray objectiveArray,
87 jdoubleArray outputArray, jboolean lpRelaxation, jdouble timeoutSeconds, jboolean silent) {
88 try {
89 auto build = CreateModel(env, columnLowerBoundsArray, columnUpperBoundsArray,
90 rowStartsArray, columnIndicesArray, entriesArray, rowLowerBoundsArray, rowUpperBoundsArray,
91 objectiveArray, lpRelaxation);
92 double value;
93 jint result = SolveModel(build, timeoutSeconds, silent, value);
94 if (result == kCbcSolutionBounded) {
95 PinnedDoubleArray output{env, outputArray};
96 *output = value;
97 }
98 return result;
99 } catch (const std::exception &e) {
100 ThrowException(env, e.what());
101 } catch (...) {
102 ThrowException(env, "Unknown solver error");
103 }
104 return kCbcError;
105}
106
107CoinModel CreateModel(JNIEnv *env, jdoubleArray columnLowerBoundsArray,
108 jdoubleArray columnUpperBoundsArray, jintArray rowStartsArray, jintArray columnIndicesArray,
109 jdoubleArray entriesArray, jdoubleArray rowLowerBoundsArray, jdoubleArray rowUpperBoundsArray,
110 jdoubleArray objectiveArray, jboolean lpRelaxation) {
111 CoinModel build;
112 CreateModelColumns(env, columnLowerBoundsArray, columnUpperBoundsArray, objectiveArray,
113 lpRelaxation, build);
114 CreateModelRows(env, rowStartsArray, columnIndicesArray, entriesArray, rowLowerBoundsArray,
115 rowUpperBoundsArray, build);
116 return build;
117}
118
119void CreateModelColumns(JNIEnv *env, jdoubleArray columnLowerBoundsArray,
120 jdoubleArray columnUpperBoundsArray, jdoubleArray objectiveArray, jboolean lpRelaxation,
121 CoinModel &build) {
122 int numColumns = env->GetArrayLength(columnLowerBoundsArray);
123 PinnedDoubleArray columnLowerBounds{env, columnLowerBoundsArray};
124 PinnedDoubleArray columnUpperBounds{env, columnUpperBoundsArray};
125 PinnedDoubleArray objective{env, objectiveArray};
126 for (int i = 0; i < numColumns; i++) {
127 build.setColumnBounds(i, columnLowerBounds[i], columnUpperBounds[i]);
128 build.setObjective(i, objective[i]);
129 if (!lpRelaxation) {
130 build.setInteger(i);
131 }
132 }
133}
134
135void CreateModelRows(JNIEnv *env, jintArray rowStartsArray, jintArray columnIndicesArray,
136 jdoubleArray entriesArray, jdoubleArray rowLowerBoundsArray, jdoubleArray rowUpperBoundsArray,
137 CoinModel &build) {
138 int numRows = env->GetArrayLength(rowLowerBoundsArray);
139 PinnedIntArray rowStarts{env, rowStartsArray};
140 PinnedIntArray columnIndices{env, columnIndicesArray};
141 PinnedDoubleArray entries{env, entriesArray};
142 PinnedDoubleArray rowLowerBounds{env, rowLowerBoundsArray};
143 PinnedDoubleArray rowUpperBounds{env, rowUpperBoundsArray};
144 for (int i = 0; i < numRows; i++) {
145 int rowStart = rowStarts[i];
146 int numbersInRow = rowStarts[i + 1] - rowStart;
147 build.addRow(numbersInRow, &columnIndices[rowStart], &entries[rowStart],
148 rowLowerBounds[i], rowUpperBounds[i]);
149 }
150}
151
152jint SolveModel(CoinModel &build, jdouble timeoutSeconds, jboolean silent, jdouble &value) {
153 OsiClpSolverInterface solver;
154 solver.loadFromCoinModel(build);
155 CbcModel model{solver};
156
157 if (timeoutSeconds >= 0) {
158 model.setDblParam(CbcModel::CbcMaximumSeconds, timeoutSeconds);
159 }
160 if (silent == JNI_FALSE) {
161 model.messageHandler()->setLogLevel(2);
162 model.solver()->messageHandler()->setLogLevel(1);
163 } else {
164 model.solver()->setHintParam(OsiDoReducePrint, true, OsiHintTry);
165 model.messageHandler()->setLogLevel(0);
166 model.solver()->messageHandler()->setLogLevel(0);
167 }
168
169 // Cut generators and heuristics are used according to
170 // https://github.com/coin-or/Cbc/blob/6b977b6707f1755520c64fea57b95891c1f3ddc0/Cbc/examples/sample2.cpp
171
172 CglProbing probing;
173 probing.setUsingObjective(true);
174 probing.setMaxPass(1);
175 probing.setMaxPassRoot(5);
176 probing.setMaxProbe(10);
177 probing.setMaxProbeRoot(1000);
178 probing.setMaxLook(50);
179 probing.setMaxLookRoot(500);
180 probing.setMaxElements(200);
181 probing.setRowCuts(3);
182 model.addCutGenerator(&probing, -1, "Probing");
183
184 CglGomory gomory;
185 gomory.setLimit(300);
186 model.addCutGenerator(&gomory, -1, "Gomory");
187
188 CglKnapsackCover knapsackCover;
189 model.addCutGenerator(&knapsackCover, -1, "KnapsackCover");
190
191 CglClique clique;
192 clique.setStarCliqueReport(false);
193 clique.setRowCliqueReport(false);
194 model.addCutGenerator(&clique, -1, "Clique");
195
196 CglFlowCover flowCover;
197 model.addCutGenerator(&flowCover, -1, "FlowCover");
198
199 CglMixedIntegerRounding mixedIntegerRounding;
200 model.addCutGenerator(&mixedIntegerRounding, -1, "MixedIntegerRounding");
201
202 OsiClpSolverInterface *osiClp = dynamic_cast<OsiClpSolverInterface *>(model.solver());
203 if (osiClp != nullptr) {
204 osiClp->setSpecialOptions(128);
205 osiClp->setupForRepeatedUse(0, 0);
206 }
207
208 CbcRounding rounding;
209 model.addHeuristic(&rounding);
210
211 CbcHeuristicLocal localHeuristic;
212 model.addHeuristic(&localHeuristic);
213
214 CbcBranchDefaultDecision branchDecision;
215 model.setBranchingMethod(&branchDecision);
216
217 CbcCompareDefault nodeComparison;
218 model.setNodeComparison(nodeComparison);
219
220 model.initialSolve();
221
222 if (model.isInitialSolveProvenPrimalInfeasible()) {
223 return kCbcUnsat;
224 }
225 if (model.isInitialSolveProvenDualInfeasible()) {
226 return kCbcSolutionUnbounded;
227 }
228 if (model.isInitialSolveAbandoned()) {
229 return kCbcTimeout;
230 }
231
232 model.setMinimumDrop(CoinMin(1.0, fabs(model.getMinimizationObjValue()) * 1.0e-3 + 1.0e-4));
233 model.setMaximumCutPassesAtRoot(-100);
234 model.setNumberStrong(10);
235 model.solver()->setIntParam(OsiMaxNumIterationHotStart, 100);
236
237 model.branchAndBound();
238
239 switch (model.status()) {
240 case 0:
241 if (model.isProvenInfeasible()) {
242 return kCbcUnsat;
243 }
244 if (model.isProvenDualInfeasible()) {
245 return kCbcSolutionUnbounded;
246 }
247 if (model.isProvenOptimal()) {
248 value = model.getMinimizationObjValue();
249 return kCbcSolutionBounded;
250 }
251 throw std::runtime_error("CBC status is 0, but no solution is found");
252 case 1:
253 return kCbcTimeout;
254 case 2:
255 return kCbcAbandoned;
256 default:
257 throw std::runtime_error("Unknown CBC status");
258 }
259}
260
261void ThrowException(JNIEnv *env, const char *message) {
262 jclass exceptionClass = env->FindClass(kCbcExceptionClassName);
263 if (exceptionClass == nullptr) {
264 std::cerr << "WARNING: " << kCbcExceptionClassName << " class was not found" << std::endl;
265 exceptionClass = env->FindClass(kRuntimeExceptionClassName);
266 if (exceptionClass == nullptr) {
267 std::cerr << "FATAL: " << kRuntimeExceptionClassName << " class was not found" << std::endl;
268 std::cerr << "FATAL: " << message << std::endl;
269 std::exit(EXIT_FAILURE);
270 }
271 }
272 if (env->ThrowNew(exceptionClass, message) < 0) {
273 std::cerr << "FATAL: Could not throw java exception" << std::endl;
274 std::cerr << "FATAL: " << message << std::endl;
275 std::exit(EXIT_FAILURE);
276 }
277}
diff --git a/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/cpp/viatracbc.hpp b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/cpp/viatracbc.hpp
new file mode 100644
index 00000000..12198c8b
--- /dev/null
+++ b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/cpp/viatracbc.hpp
@@ -0,0 +1,16 @@
1#ifndef HU_BME_MIT_INF_DSLREASONER_ILP_CBC_
2#define HU_BME_MIT_INF_DSLREASONER_ILP_CBC_
3
4#include <jni.h>
5
6extern "C" {
7
8JNIEXPORT jint JNICALL Java_hu_bme_mit_inf_dslreasoner_ilp_cbc_CbcSolver_solveIlpProblem(
9 JNIEnv *env, jclass klazz, jdoubleArray columnLowerBoundsArray, jdoubleArray columnUpperBoundsArray,
10 jintArray rowStartsArray, jintArray columnIndicesArray, jdoubleArray entriesArray,
11 jdoubleArray rowLowerBoundsArray, jdoubleArray rowUpperBoundsArray, jdoubleArray objectiveArray,
12 jdoubleArray outputArray, jboolean lpRelaxation, jdouble timeoutSeconds, jboolean silent);
13
14}
15
16#endif // HU_BME_MIT_INF_DSLREASONER_ILP_CBC_
diff --git a/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/lib/libviatracbc.so b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/lib/libviatracbc.so
new file mode 100755
index 00000000..96289216
--- /dev/null
+++ b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/lib/libviatracbc.so
Binary files differ
diff --git a/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/src/hu/bme/mit/inf/dslreasoner/ilp/cbc/CbcException.java b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/src/hu/bme/mit/inf/dslreasoner/ilp/cbc/CbcException.java
new file mode 100644
index 00000000..26846958
--- /dev/null
+++ b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/src/hu/bme/mit/inf/dslreasoner/ilp/cbc/CbcException.java
@@ -0,0 +1,30 @@
1package hu.bme.mit.inf.dslreasoner.ilp.cbc;
2
3public class CbcException extends RuntimeException {
4
5 /**
6 *
7 */
8 private static final long serialVersionUID = 2691773509078511887L;
9
10 public CbcException() {
11 super();
12 }
13
14 public CbcException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
15 super(message, cause, enableSuppression, writableStackTrace);
16 }
17
18 public CbcException(String message, Throwable cause) {
19 super(message, cause);
20 }
21
22 public CbcException(String message) {
23 super(message);
24 }
25
26 public CbcException(Throwable cause) {
27 super(cause);
28 }
29
30}
diff --git a/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/src/hu/bme/mit/inf/dslreasoner/ilp/cbc/CbcResult.java b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/src/hu/bme/mit/inf/dslreasoner/ilp/cbc/CbcResult.java
new file mode 100644
index 00000000..dae3a447
--- /dev/null
+++ b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/src/hu/bme/mit/inf/dslreasoner/ilp/cbc/CbcResult.java
@@ -0,0 +1,54 @@
1package hu.bme.mit.inf.dslreasoner.ilp.cbc;
2
3public abstract class CbcResult {
4 public static final CbcResult SOLUTION_UNBOUNDED = new CbcResult() {
5 };
6
7 public static final CbcResult UNSAT = new CbcResult() {
8 };
9
10 public static final CbcResult ABANDONED = new CbcResult() {
11 };
12
13 public static final CbcResult TIMEOUT = new CbcResult() {
14 };
15
16 private CbcResult() {
17 }
18
19 public static class SolutionBounded extends CbcResult {
20 public final double value;
21
22 public SolutionBounded(double value) {
23 this.value = value;
24 }
25
26 public double getValue() {
27 return value;
28 }
29
30 @Override
31 public int hashCode() {
32 final int prime = 31;
33 int result = 1;
34 long temp;
35 temp = Double.doubleToLongBits(value);
36 result = prime * result + (int) (temp ^ (temp >>> 32));
37 return result;
38 }
39
40 @Override
41 public boolean equals(Object obj) {
42 if (this == obj)
43 return true;
44 if (obj == null)
45 return false;
46 if (getClass() != obj.getClass())
47 return false;
48 SolutionBounded other = (SolutionBounded) obj;
49 if (Double.doubleToLongBits(value) != Double.doubleToLongBits(other.value))
50 return false;
51 return true;
52 }
53 }
54}
diff --git a/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/src/hu/bme/mit/inf/dslreasoner/ilp/cbc/CbcSolver.java b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/src/hu/bme/mit/inf/dslreasoner/ilp/cbc/CbcSolver.java
new file mode 100644
index 00000000..085d4448
--- /dev/null
+++ b/Solvers/ILP-Solver/hu.bme.mit.inf.dslreasoner.ilp.cbc/src/hu/bme/mit/inf/dslreasoner/ilp/cbc/CbcSolver.java
@@ -0,0 +1,71 @@
1package hu.bme.mit.inf.dslreasoner.ilp.cbc;
2
3public class CbcSolver {
4 private static int CBC_SOLUTION_BOUNDED = 0;
5 private static int CBC_SOLUTION_UNBOUNDED = 1;
6 private static int CBC_UNSAT = 2;
7 private static int CBC_ABANDONED = 3;
8 private static int CBC_TIMEOUT = 4;
9 private static int CBC_ERROR = 5;
10
11 private static boolean nativesLoaded = false;
12
13 private CbcSolver() {
14 throw new IllegalStateException("This is a static utility class and should not be instantiated directly.");
15 }
16
17 public static CbcResult solve(double[] columnLowerBounds, double[] columnUpperBounds, int[] rowStarts,
18 int[] columnIndices, double[] entries, double[] rowLowerBounds, double[] rowUpperBounds, double[] objective,
19 boolean lpRelaxation, double timeoutSeconds, boolean silent) {
20 loadNatives();
21 validate(columnLowerBounds, columnUpperBounds, rowStarts, columnIndices, entries, rowLowerBounds,
22 rowUpperBounds, objective);
23 double[] output = new double[1];
24 int result = solveIlpProblem(columnLowerBounds, columnUpperBounds, rowStarts, columnIndices, entries,
25 rowLowerBounds, rowUpperBounds, objective, output, lpRelaxation, timeoutSeconds, silent);
26 if (result == CBC_SOLUTION_BOUNDED) {
27 return new CbcResult.SolutionBounded(output[0]);
28 } else if (result == CBC_SOLUTION_UNBOUNDED) {
29 return CbcResult.SOLUTION_UNBOUNDED;
30 } else if (result == CBC_UNSAT) {
31 return CbcResult.UNSAT;
32 } else if (result == CBC_ABANDONED) {
33 return CbcResult.ABANDONED;
34 } else if (result == CBC_TIMEOUT) {
35 return CbcResult.TIMEOUT;
36 } else if (result == CBC_ERROR) {
37 throw new CbcException("Solver signalled error, but no exception was thrown");
38 } else {
39 throw new CbcException("Unknown return value: " + result);
40 }
41 }
42
43 private static void loadNatives() {
44 if (!nativesLoaded) {
45 synchronized (CbcSolver.class) {
46 System.loadLibrary("viatracbc");
47 nativesLoaded = true;
48 }
49 }
50 }
51
52 private static void validate(double[] columnLowerBounds, double[] columnUpperBounds, int[] rowStarts,
53 int[] columnIndices, double[] entries, double[] rowLowerBounds, double[] rowUpperBounds,
54 double[] objective) {
55 int numColumns = columnLowerBounds.length;
56 if (columnUpperBounds.length != numColumns) {
57 throw new CbcException("Lengths of columnLowerBounds and columnUpperBounds must match");
58 }
59 if (objective.length != numColumns) {
60 throw new CbcException("Lengths of columnLowerBounds and objective must match");
61 }
62 int numRows = rowLowerBounds.length;
63 if (rowUpperBounds.length != numRows) {
64 throw new CbcException("Lengths of rowLowerBounds and rowUpperBounds must match");
65 }
66 }
67
68 private static native int solveIlpProblem(double[] columnLowerBounds, double[] columnUpperBounds, int[] rowStarts,
69 int[] columnIndices, double[] entries, double[] rowLowerBounds, double[] rowUpperBounds, double[] objective,
70 double[] output, boolean lpRelaxation, double timeoutSeconds, boolean silent);
71}
diff --git a/Solvers/SMT-Solver/com.microsoft.z3/.classpath b/Solvers/SMT-Solver/com.microsoft.z3/.classpath
new file mode 100644
index 00000000..ffdc022a
--- /dev/null
+++ b/Solvers/SMT-Solver/com.microsoft.z3/.classpath
@@ -0,0 +1,15 @@
1<?xml version="1.0" encoding="UTF-8"?>
2<classpath>
3 <classpathentry exported="true" kind="lib" path="com.microsoft.z3.jar">
4 <attributes>
5 <attribute name="org.eclipse.jdt.launching.CLASSPATH_ATTR_LIBRARY_PATH_ENTRY" value="com.microsoft.z3/lib"/>
6 </attributes>
7 </classpathentry>
8 <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
9 <attributes>
10 <attribute name="module" value="true"/>
11 </attributes>
12 </classpathentry>
13 <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
14 <classpathentry kind="output" path="bin"/>
15</classpath>
diff --git a/Solvers/SMT-Solver/com.microsoft.z3/.gitignore b/Solvers/SMT-Solver/com.microsoft.z3/.gitignore
new file mode 100644
index 00000000..ae3c1726
--- /dev/null
+++ b/Solvers/SMT-Solver/com.microsoft.z3/.gitignore
@@ -0,0 +1 @@
/bin/
diff --git a/Solvers/SMT-Solver/com.microsoft.z3/.project b/Solvers/SMT-Solver/com.microsoft.z3/.project
new file mode 100644
index 00000000..ec5bbc58
--- /dev/null
+++ b/Solvers/SMT-Solver/com.microsoft.z3/.project
@@ -0,0 +1,28 @@
1<?xml version="1.0" encoding="UTF-8"?>
2<projectDescription>
3 <name>com.microsoft.z3</name>
4 <comment></comment>
5 <projects>
6 </projects>
7 <buildSpec>
8 <buildCommand>
9 <name>org.eclipse.jdt.core.javabuilder</name>
10 <arguments>
11 </arguments>
12 </buildCommand>
13 <buildCommand>
14 <name>org.eclipse.pde.ManifestBuilder</name>
15 <arguments>
16 </arguments>
17 </buildCommand>
18 <buildCommand>
19 <name>org.eclipse.pde.SchemaBuilder</name>
20 <arguments>
21 </arguments>
22 </buildCommand>
23 </buildSpec>
24 <natures>
25 <nature>org.eclipse.pde.PluginNature</nature>
26 <nature>org.eclipse.jdt.core.javanature</nature>
27 </natures>
28</projectDescription>
diff --git a/Solvers/SMT-Solver/com.microsoft.z3/META-INF/MANIFEST.MF b/Solvers/SMT-Solver/com.microsoft.z3/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..d91e3272
--- /dev/null
+++ b/Solvers/SMT-Solver/com.microsoft.z3/META-INF/MANIFEST.MF
@@ -0,0 +1,22 @@
1Manifest-Version: 1.0
2Bundle-ManifestVersion: 2
3Bundle-Name: Z3
4Bundle-SymbolicName: com.microsoft.z3
5Bundle-Version: 4.8.8.qualifier
6Bundle-Vendor: Microsoft
7Automatic-Module-Name: com.microsoft.z3
8Bundle-ClassPath: com.microsoft.z3.jar
9Bundle-NativeCode: lib/libz3.so;
10 lib/libz3java.so;
11 osname=Linux;
12 processor=x86_64,
13 lib/libz3.dylib;
14 lib/libz3java.dylib;
15 osname=MacOSX;
16 processor=x86_64,
17 lib/libz3.dll;
18 lib/libz3java.dll;
19 osname=win32;
20 processor=x86_64
21Export-Package: com.microsoft.z3,
22 com.microsoft.z3.enumerations
diff --git a/Solvers/SMT-Solver/com.microsoft.z3/build.properties b/Solvers/SMT-Solver/com.microsoft.z3/build.properties
new file mode 100644
index 00000000..87f4e73f
--- /dev/null
+++ b/Solvers/SMT-Solver/com.microsoft.z3/build.properties
@@ -0,0 +1,3 @@
1bin.includes = META-INF/,\
2 lib/,\
3 com.microsoft.z3.jar
diff --git a/Solvers/SMT-Solver/com.microsoft.z3/lib/libz3.dll b/Solvers/SMT-Solver/com.microsoft.z3/lib/libz3.dll
new file mode 100644
index 00000000..46b1e7c2
--- /dev/null
+++ b/Solvers/SMT-Solver/com.microsoft.z3/lib/libz3.dll
Binary files differ
diff --git a/Solvers/SMT-Solver/com.microsoft.z3/lib/libz3.dylib b/Solvers/SMT-Solver/com.microsoft.z3/lib/libz3.dylib
new file mode 100755
index 00000000..6ca9aea8
--- /dev/null
+++ b/Solvers/SMT-Solver/com.microsoft.z3/lib/libz3.dylib
Binary files differ
diff --git a/Solvers/SMT-Solver/com.microsoft.z3/lib/libz3.so b/Solvers/SMT-Solver/com.microsoft.z3/lib/libz3.so
new file mode 100755
index 00000000..0a9853ae
--- /dev/null
+++ b/Solvers/SMT-Solver/com.microsoft.z3/lib/libz3.so
Binary files differ
diff --git a/Solvers/SMT-Solver/com.microsoft.z3/lib/libz3java.dll b/Solvers/SMT-Solver/com.microsoft.z3/lib/libz3java.dll
new file mode 100644
index 00000000..615bf3b8
--- /dev/null
+++ b/Solvers/SMT-Solver/com.microsoft.z3/lib/libz3java.dll
Binary files differ
diff --git a/Solvers/SMT-Solver/com.microsoft.z3/lib/libz3java.dylib b/Solvers/SMT-Solver/com.microsoft.z3/lib/libz3java.dylib
new file mode 100755
index 00000000..73e02b97
--- /dev/null
+++ b/Solvers/SMT-Solver/com.microsoft.z3/lib/libz3java.dylib
Binary files differ
diff --git a/Solvers/SMT-Solver/com.microsoft.z3/lib/libz3java.so b/Solvers/SMT-Solver/com.microsoft.z3/lib/libz3java.so
new file mode 100755
index 00000000..54b05d9a
--- /dev/null
+++ b/Solvers/SMT-Solver/com.microsoft.z3/lib/libz3java.so
Binary files differ
diff --git a/Solvers/SMT-Solver/hu.bme.mit.inf.dslreasoner.smt.language/.launch/Generate Language Infrastructure (hu.bme.mit.inf.dslreasoner.smt.language).launch b/Solvers/SMT-Solver/hu.bme.mit.inf.dslreasoner.smt.language/.launch/Generate Language Infrastructure (hu.bme.mit.inf.dslreasoner.smt.language).launch
deleted file mode 100644
index e448edbe..00000000
--- a/Solvers/SMT-Solver/hu.bme.mit.inf.dslreasoner.smt.language/.launch/Generate Language Infrastructure (hu.bme.mit.inf.dslreasoner.smt.language).launch
+++ /dev/null
@@ -1,17 +0,0 @@
1<?xml version="1.0" encoding="UTF-8" standalone="no"?>
2<launchConfiguration type="org.eclipse.emf.mwe2.launch.Mwe2LaunchConfigurationType">
3<stringAttribute key="org.eclipse.debug.core.ATTR_REFRESH_SCOPE" value="${working_set:&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&#10;&lt;launchConfigurationWorkingSet factoryID=&quot;org.eclipse.ui.internal.WorkingSetFactory&quot; id=&quot;1299248699643_13&quot; label=&quot;working set&quot; name=&quot;working set&quot;&gt;&#10;&lt;item factoryID=&quot;org.eclipse.ui.internal.model.ResourceFactory&quot; path=&quot;/hu.bme.mit.inf.dslreasoner.smt.language&quot; type=&quot;4&quot;/&gt;&#10;&lt;item factoryID=&quot;org.eclipse.ui.internal.model.ResourceFactory&quot; path=&quot;/hu.bme.mit.inf.dslreasoner.smt.language.generator&quot; type=&quot;4&quot;/&gt;&#10;&lt;item factoryID=&quot;org.eclipse.ui.internal.model.ResourceFactory&quot; path=&quot;/hu.bme.mit.inf.dslreasoner.smt.language.tests&quot; type=&quot;4&quot;/&gt;&#10;&lt;item factoryID=&quot;org.eclipse.ui.internal.model.ResourceFactory&quot; path=&quot;/hu.bme.mit.inf.dslreasoner.smt.language.ui&quot; type=&quot;4&quot;/&gt;&#10;&lt;/launchConfigurationWorkingSet&gt;}"/>
4<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_PATHS">
5<listEntry value="/hu.bme.mit.inf.dslreasoner.smt.language"/>
6</listAttribute>
7<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_TYPES">
8<listEntry value="4"/>
9</listAttribute>
10<listAttribute key="org.eclipse.debug.ui.favoriteGroups">
11<listEntry value="org.eclipse.debug.ui.launchGroup.run"/>
12</listAttribute>
13<stringAttribute key="org.eclipse.jdt.launching.MAIN_TYPE" value="org.eclipse.emf.mwe2.launch.runtime.Mwe2Launcher"/>
14<stringAttribute key="org.eclipse.jdt.launching.PROGRAM_ARGUMENTS" value="src/hu/bme/mit/inf/dslreasoner/GenerateSmtLanguage.mwe2"/>
15<stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value="hu.bme.mit.inf.dslreasoner.smt.language"/>
16<stringAttribute key="org.eclipse.jdt.launching.VM_ARGUMENTS" value="-Xmx512m"/>
17</launchConfiguration>
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/META-INF/MANIFEST.MF b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/META-INF/MANIFEST.MF
index 23e3ad13..f9090901 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/META-INF/MANIFEST.MF
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/META-INF/MANIFEST.MF
@@ -4,6 +4,9 @@ Bundle-Name: Logic2viatra
4Bundle-SymbolicName: hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatraquery;singleton:=true 4Bundle-SymbolicName: hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatraquery;singleton:=true
5Bundle-Version: 1.0.0.qualifier 5Bundle-Version: 1.0.0.qualifier
6Export-Package: hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra, 6Export-Package: hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra,
7 hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality,
8 hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval,
9 hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval.aggregators,
7 hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns, 10 hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns,
8 hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.queries 11 hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.queries
9Require-Bundle: hu.bme.mit.inf.dslreasoner.logic.model;bundle-version="1.0.0", 12Require-Bundle: hu.bme.mit.inf.dslreasoner.logic.model;bundle-version="1.0.0",
@@ -20,7 +23,9 @@ Require-Bundle: hu.bme.mit.inf.dslreasoner.logic.model;bundle-version="1.0.0",
20 com.google.inject;bundle-version="3.0.0", 23 com.google.inject;bundle-version="3.0.0",
21 org.eclipse.xtext;bundle-version="2.10.0", 24 org.eclipse.xtext;bundle-version="2.10.0",
22 org.eclipse.viatra.transformation.runtime.emf;bundle-version="1.5.0", 25 org.eclipse.viatra.transformation.runtime.emf;bundle-version="1.5.0",
23 org.eclipse.xtext.xbase;bundle-version="2.10.0" 26 org.eclipse.xtext.xbase;bundle-version="2.10.0",
27 com.microsoft.z3;bundle-version="4.8.5",
28 hu.bme.mit.inf.dslreasoner.ilp.cbc;bundle-version="1.0.0"
24Bundle-RequiredExecutionEnvironment: JavaSE-1.8 29Bundle-RequiredExecutionEnvironment: JavaSE-1.8
25Import-Package: org.apache.log4j 30Import-Package: org.apache.log4j
26Automatic-Module-Name: hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatraquery 31Automatic-Module-Name: hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatraquery
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/build.properties b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/build.properties
index 585df5ce..9ffc994a 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/build.properties
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/build.properties
@@ -4,6 +4,5 @@ bin.includes = META-INF/,\
4source.. = src/,\ 4source.. = src/,\
5 patterns/,\ 5 patterns/,\
6 vql-gen/,\ 6 vql-gen/,\
7 xtend-gen/,\ 7 xtend-gen/
8 src-gen/
9output.. = bin/ 8output.. = bin/
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/Modality.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/Modality.java
index d2132cea..f3a6ec32 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/Modality.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/Modality.java
@@ -2,21 +2,46 @@ package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra;
2 2
3public enum Modality { 3public enum Modality {
4 MUST, MAY, CURRENT; 4 MUST, MAY, CURRENT;
5
5 public boolean isMust() { 6 public boolean isMust() {
6 return this == MUST; 7 return this == MUST;
7 } 8 }
9
8 public boolean isMay() { 10 public boolean isMay() {
9 return this == MAY; 11 return this == MAY;
10 } 12 }
13
11 public boolean isCurrent() { 14 public boolean isCurrent() {
12 return this == CURRENT; 15 return this == CURRENT;
13 } 16 }
17
14 public boolean isMustOrCurrent() { 18 public boolean isMustOrCurrent() {
15 return isMust() || isCurrent(); 19 return isMust() || isCurrent();
16 } 20 }
21
17 public Modality getDual() { 22 public Modality getDual() {
18 if(this.isCurrent()) return CURRENT; 23 switch (this) {
19 else if(this.isMust())return MAY; 24 case CURRENT:
20 else return MUST; 25 return CURRENT;
26 case MUST:
27 return MAY;
28 case MAY:
29 return MUST;
30 default:
31 throw new UnsupportedOperationException("Unknown Modality: " + this);
32 }
33 }
34
35 public Modality toBase() {
36 if (this.isCurrent()) {
37 return MUST;
38 } else {
39 return this;
40 }
41 }
42
43 @Override
44 public String toString() {
45 return super.toString().toLowerCase();
21 } 46 }
22} 47}
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 b63607f7..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
@@ -1,8 +1,20 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra 1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra
2 2
3import com.google.common.collect.ImmutableMap
3import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel 4import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel
4import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem 5import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem
5import hu.bme.mit.inf.dslreasoner.viatra2logic.viatra2logicannotations.TransfomedViatraQuery 6import hu.bme.mit.inf.dslreasoner.viatra2logic.viatra2logicannotations.TransfomedViatraQuery
7import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.CbcPolyhedronSolver
8import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint
9import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.MultiplicityGoalConstraintCalculator
10import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronScopePropagator
11import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.RelationConstraintCalculator
12import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagator
13import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy
14import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.TypeHierarchyScopePropagator
15import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Z3PolyhedronSolver
16import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.GeneratedPatterns
17import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.ModalPatternQueries
6import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternProvider 18import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternProvider
7import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules.GoalConstraintProvider 19import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules.GoalConstraintProvider
8import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules.RefinementRuleProvider 20import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules.RefinementRuleProvider
@@ -10,82 +22,131 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.par
10import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace 22import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace
11import java.util.Collection 23import java.util.Collection
12import java.util.List 24import java.util.List
25import java.util.Map
13import java.util.Set 26import java.util.Set
14import org.eclipse.viatra.query.runtime.api.IPatternMatch 27import org.eclipse.viatra.query.runtime.api.IPatternMatch
15import org.eclipse.viatra.query.runtime.api.IQuerySpecification 28import org.eclipse.viatra.query.runtime.api.IQuerySpecification
16import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher 29import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher
30import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint
17import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery 31import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery
18import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRule 32import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRule
19import org.eclipse.xtend.lib.annotations.Data 33import org.eclipse.xtend.lib.annotations.Data
20import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint
21import java.util.Map
22 34
23class ModelGenerationStatistics { 35class ModelGenerationStatistics {
24 public var long transformationExecutionTime = 0 36 public var long transformationExecutionTime = 0
37
25 synchronized def addExecutionTime(long amount) { 38 synchronized def addExecutionTime(long amount) {
26 transformationExecutionTime+=amount 39 transformationExecutionTime += amount
40 }
41
42 public var long scopePropagationTime = 0
43
44 synchronized def addScopePropagationTime(long amount) {
45 scopePropagationTime += amount
46 }
47
48 public var long preliminaryTypeAnalisisTime = 0
49
50 public var int decisionsTried = 0
51
52 synchronized def incrementDecisionCount() {
53 decisionsTried++
54 }
55
56 public var int transformationInvocations
57
58 synchronized def incrementTransformationCount() {
59 transformationInvocations++
60 }
61
62 public var int scopePropagatorInvocations
63
64 synchronized def incrementScopePropagationCount() {
65 scopePropagatorInvocations++
66 }
67
68 public var int scopePropagatorSolverInvocations
69
70 synchronized def incrementScopePropagationSolverCount() {
71 scopePropagatorSolverInvocations++
27 } 72 }
28 public var long PreliminaryTypeAnalisisTime = 0
29} 73}
74
30@Data class ModelGenerationMethod { 75@Data class ModelGenerationMethod {
31 ModelGenerationStatistics statistics 76 ModelGenerationStatistics statistics
32 77
33 Collection<? extends BatchTransformationRule<?,?>> objectRefinementRules 78 Collection<? extends BatchTransformationRule<?, ?>> objectRefinementRules
34 Collection<? extends BatchTransformationRule<?,?>> relationRefinementRules 79 Collection<? extends BatchTransformationRule<?, ?>> relationRefinementRules
35 80
36 List<MultiplicityGoalConstraintCalculator> unfinishedMultiplicities 81 List<MultiplicityGoalConstraintCalculator> unfinishedMultiplicities
37 Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedWF 82
38 83 Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedWF
39 Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> invalidWF 84
40 85 Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> invalidWF
41 Map<PConstraint, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> mustUnitPropagationPreconditions 86
42 Map<PConstraint, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> currentUnitPropagationPreconditions 87 Map<PConstraint, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> mustUnitPropagationPreconditions
43 88 Map<PConstraint, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> currentUnitPropagationPreconditions
44 Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> allPatterns 89
90 Map<String, ModalPatternQueries> modalRelationQueries
91
92 Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> allPatterns
45} 93}
94
46enum TypeInferenceMethod { 95enum TypeInferenceMethod {
47 Generic, PreliminaryAnalysis 96 Generic,
97 PreliminaryAnalysis
48} 98}
49 99
50class ModelGenerationMethodProvider { 100class ModelGenerationMethodProvider {
51 private val PatternProvider patternProvider = new PatternProvider 101 val PatternProvider patternProvider = new PatternProvider
52 private val RefinementRuleProvider refinementRuleProvider = new RefinementRuleProvider 102 val RefinementRuleProvider refinementRuleProvider = new RefinementRuleProvider
53 private val GoalConstraintProvider goalConstraintProvider = new GoalConstraintProvider 103 val GoalConstraintProvider goalConstraintProvider = new GoalConstraintProvider
54 104 val relationConstraintCalculator = new RelationConstraintCalculator
55 public def ModelGenerationMethod createModelGenerationMethod( 105
106 def ModelGenerationMethod createModelGenerationMethod(
56 LogicProblem logicProblem, 107 LogicProblem logicProblem,
57 PartialInterpretation emptySolution, 108 PartialInterpretation emptySolution,
58 ReasonerWorkspace workspace, 109 ReasonerWorkspace workspace,
59 boolean nameNewElements, 110 boolean nameNewElements,
60 TypeInferenceMethod typeInferenceMethod, 111 TypeInferenceMethod typeInferenceMethod,
61 ScopePropagator scopePropagator, 112 ScopePropagatorStrategy scopePropagatorStrategy,
62 DocumentationLevel debugLevel, 113 Collection<LinearTypeConstraintHint> hints,
63 boolean objectCreationCosts 114 DocumentationLevel debugLevel
64 ) { 115 ) {
65 val statistics = new ModelGenerationStatistics 116 val statistics = new ModelGenerationStatistics
66 val writeFiles = (debugLevel === DocumentationLevel.NORMAL || debugLevel === DocumentationLevel.FULL) 117 val writeFiles = (debugLevel === DocumentationLevel.NORMAL || debugLevel === DocumentationLevel.FULL)
67 118
68 val Set<PQuery> existingQueries = logicProblem 119 val Set<PQuery> existingQueries = logicProblem.relations.map[annotations].flatten.filter(TransfomedViatraQuery).
69 .relations 120 map[it.patternPQuery as PQuery].toSet
70 .map[annotations] 121
71 .flatten 122 val relationConstraints = relationConstraintCalculator.calculateRelationConstraints(logicProblem)
72 .filter(TransfomedViatraQuery) 123 val queries = patternProvider.generateQueries(logicProblem, emptySolution, statistics, existingQueries,
73 .map[it.patternPQuery as PQuery] 124 workspace, typeInferenceMethod, scopePropagatorStrategy, relationConstraints, hints, writeFiles)
74 .toSet 125 val scopePropagator = createScopePropagator(scopePropagatorStrategy, emptySolution, hints, queries, statistics)
75 126 scopePropagator.propagateAllScopeConstraints
76 val queries = patternProvider.generateQueries(logicProblem,emptySolution,statistics,existingQueries,workspace,typeInferenceMethod,writeFiles) 127 val objectRefinementRules = refinementRuleProvider.createObjectRefinementRules(logicProblem, emptySolution,
77 val //LinkedHashMap<Pair<Relation, ? extends Type>, BatchTransformationRule<GenericPatternMatch, ViatraQueryMatcher<GenericPatternMatch>>> 128 queries, scopePropagator, nameNewElements, statistics)
78 objectRefinementRules = refinementRuleProvider.createObjectRefinementRules(logicProblem, emptySolution, queries,scopePropagator,nameNewElements,statistics) 129 val relationRefinementRules = refinementRuleProvider.createRelationRefinementRules(queries, scopePropagator,
79 val relationRefinementRules = refinementRuleProvider.createRelationRefinementRules(queries,statistics) 130 statistics)
80 131
81 val unfinishedMultiplicities = goalConstraintProvider.getUnfinishedMultiplicityQueries(logicProblem,queries,objectCreationCosts) 132 val unfinishedMultiplicities = goalConstraintProvider.getUnfinishedMultiplicityQueries(logicProblem,queries)
133
82 val unfinishedWF = queries.getUnfinishedWFQueries.values 134 val unfinishedWF = queries.getUnfinishedWFQueries.values
83 135
136 val modalRelationQueriesBuilder = ImmutableMap.builder
137 for (entry : queries.modalRelationQueries.entrySet) {
138 val annotation = entry.key.annotations.filter(TransfomedViatraQuery).head
139 if (annotation !== null) {
140 modalRelationQueriesBuilder.put(annotation.patternFullyQualifiedName, entry.value)
141 }
142 }
143 val modalRelationQueries = modalRelationQueriesBuilder.build
144
84 val invalidWF = queries.getInvalidWFQueries.values 145 val invalidWF = queries.getInvalidWFQueries.values
85 146
86 val mustUnitPropagationPreconditions = queries.getMustUnitPropagationPreconditionPatterns 147 val mustUnitPropagationPreconditions = queries.getMustUnitPropagationPreconditionPatterns
87 val currentUnitPropagationPreconditions = queries.getCurrentUnitPropagationPreconditionPatterns 148 val currentUnitPropagationPreconditions = queries.getCurrentUnitPropagationPreconditionPatterns
88 149
89 return new ModelGenerationMethod( 150 return new ModelGenerationMethod(
90 statistics, 151 statistics,
91 objectRefinementRules.values, 152 objectRefinementRules.values,
@@ -95,7 +156,45 @@ class ModelGenerationMethodProvider {
95 invalidWF, 156 invalidWF,
96 mustUnitPropagationPreconditions, 157 mustUnitPropagationPreconditions,
97 currentUnitPropagationPreconditions, 158 currentUnitPropagationPreconditions,
159 modalRelationQueries,
98 queries.allQueries 160 queries.allQueries
99 ) 161 )
100 } 162 }
163
164 private def createScopePropagator(ScopePropagatorStrategy scopePropagatorStrategy,
165 PartialInterpretation emptySolution, Collection<LinearTypeConstraintHint> hints, GeneratedPatterns queries,
166 ModelGenerationStatistics statistics) {
167 if (!hints.empty && !(scopePropagatorStrategy instanceof ScopePropagatorStrategy.Polyhedral)) {
168 throw new IllegalArgumentException("Only the Polyhedral scope propagator strategy can use hints.")
169 }
170 switch (scopePropagatorStrategy) {
171 case ScopePropagatorStrategy.None,
172 case ScopePropagatorStrategy.Basic:
173 new ScopePropagator(emptySolution, statistics)
174 case ScopePropagatorStrategy.BasicTypeHierarchy:
175 new TypeHierarchyScopePropagator(emptySolution, statistics)
176 ScopePropagatorStrategy.Polyhedral: {
177 val types = queries.refineObjectQueries.keySet.map[newType].toSet
178 val allPatternsByName = queries.allQueries.toMap[fullyQualifiedName]
179 val solver = switch (scopePropagatorStrategy.solver) {
180 case Z3Integer:
181 new Z3PolyhedronSolver(false, scopePropagatorStrategy.timeoutSeconds)
182 case Z3Real:
183 new Z3PolyhedronSolver(true, scopePropagatorStrategy.timeoutSeconds)
184 case Cbc:
185 new CbcPolyhedronSolver(false, scopePropagatorStrategy.timeoutSeconds, true)
186 case Clp:
187 new CbcPolyhedronSolver(true, scopePropagatorStrategy.timeoutSeconds, true)
188 default:
189 throw new IllegalArgumentException("Unknown polyhedron solver: " +
190 scopePropagatorStrategy.solver)
191 }
192 new PolyhedronScopePropagator(emptySolution, statistics, types, queries.multiplicityConstraintQueries,
193 queries.hasElementInContainmentQuery, allPatternsByName, hints, solver,
194 scopePropagatorStrategy.requiresUpperBoundIndexing, scopePropagatorStrategy.updateHeuristic)
195 }
196 default:
197 throw new IllegalArgumentException("Unknown scope propagator strategy: " + scopePropagatorStrategy)
198 }
199 }
101} 200}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ScopePropagator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ScopePropagator.xtend
deleted file mode 100644
index 8012776f..00000000
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ScopePropagator.xtend
+++ /dev/null
@@ -1,166 +0,0 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra
2
3import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
4import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialTypeInterpratation
5import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope
6import java.util.HashMap
7import java.util.Map
8import java.util.Set
9import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialComplexTypeInterpretation
10import java.util.HashSet
11import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialPrimitiveInterpretation
12
13class ScopePropagator {
14 PartialInterpretation partialInterpretation
15 Map<PartialTypeInterpratation,Scope> type2Scope
16
17 val Map<Scope, Set<Scope>> superScopes
18 val Map<Scope, Set<Scope>> subScopes
19
20 public new(PartialInterpretation p) {
21 partialInterpretation = p
22 type2Scope = new HashMap
23 for(scope : p.scopes) {
24 type2Scope.put(scope.targetTypeInterpretation,scope)
25 }
26
27 superScopes = new HashMap
28 subScopes = new HashMap
29 for(scope : p.scopes) {
30 superScopes.put(scope,new HashSet)
31 subScopes.put(scope,new HashSet)
32 }
33
34 for(scope : p.scopes) {
35 val target = scope.targetTypeInterpretation
36 if(target instanceof PartialComplexTypeInterpretation) {
37 val supertypeInterpretations = target.supertypeInterpretation
38 for(supertypeInterpretation : supertypeInterpretations) {
39 val supertypeScope = type2Scope.get(supertypeInterpretation)
40 superScopes.get(scope).add(supertypeScope)
41 subScopes.get(supertypeScope).add(scope)
42 }
43 }
44 }
45 }
46
47 def public propagateAllScopeConstraints() {
48 var boolean hadChanged
49 do{
50 hadChanged = false
51 for(superScopeEntry : superScopes.entrySet) {
52 val sub = superScopeEntry.key
53 hadChanged = propagateLowerLimitUp(sub,partialInterpretation) || hadChanged
54 hadChanged = propagateUpperLimitDown(sub,partialInterpretation) || hadChanged
55 for(sup: superScopeEntry.value) {
56 hadChanged = propagateLowerLimitUp(sub,sup) || hadChanged
57 hadChanged = propagateUpperLimitDown(sub,sup) || hadChanged
58 }
59 }
60 } while(hadChanged)
61// println('''All constraints are propagated.''')
62 }
63
64 def public propagateAdditionToType(PartialTypeInterpratation t) {
65 val isPrimitive = t instanceof PartialPrimitiveInterpretation || t === null
66 if(!isPrimitive) {
67 // println('''Adding to «(t as PartialComplexTypeInterpretation).interpretationOf.name»''')
68 val targetScope = type2Scope.get(t)
69 if(targetScope!==null) {
70 targetScope.removeOne
71 val sups = superScopes.get(targetScope)
72 sups.forEach[removeOne]
73 }
74
75
76 if(this.partialInterpretation.minNewElements > 0 ) {
77 this.partialInterpretation.minNewElements = this.partialInterpretation.minNewElements-1
78 }
79 if(this.partialInterpretation.maxNewElements > 0) {
80 this.partialInterpretation.maxNewElements = this.partialInterpretation.maxNewElements-1
81 } else if(this.partialInterpretation.maxNewElements === 0) {
82 this.partialInterpretation.maxNewElements = 0
83 //throw new IllegalArgumentException('''Inconsistent object creation: lower node limit is 0!''')
84 }
85
86 // subScopes.get(targetScope).forEach[propagateUpperLimitDown(it,targetScope)]
87 // for(sup: sups) {
88 // subScopes.get(sup).forEach[propagateUpperLimitDown(it,sup)]
89 // }
90 // for(scope : type2Scope.values) {
91 // propagateUpperLimitDown(scope,partialInterpretation)
92 // }
93
94 propagateAllScopeConstraints
95
96 // println('''Target Scope: «targetScope.minNewElements» - «targetScope.maxNewElements»''')
97 // println(''' «this.partialInterpretation.minNewElements» - «this.partialInterpretation.maxNewElements»''')
98 // this.partialInterpretation.scopes.forEach[println(''' «(it.targetTypeInterpretation as PartialComplexTypeInterpretation).interpretationOf.name»: «it.minNewElements»-«it.maxNewElements»''')]
99 // println('''All constraints are propagated upon increasing «(t as PartialComplexTypeInterpretation).interpretationOf.name»''')
100 }
101 }
102
103 private def propagateLowerLimitUp(Scope subScope, Scope superScope) {
104 if(subScope.minNewElements>superScope.minNewElements) {
105// println('''
106// «(subScope.targetTypeInterpretation as PartialComplexTypeInterpretation).interpretationOf.name» -> «(superScope.targetTypeInterpretation as PartialComplexTypeInterpretation).interpretationOf.name»
107// superScope.minNewElements «superScope.minNewElements» = subScope.minNewElements «subScope.minNewElements»
108// ''')
109 superScope.minNewElements = subScope.minNewElements
110 return true
111 } else {
112 return false
113 }
114 }
115
116 private def propagateUpperLimitDown(Scope subScope, Scope superScope) {
117 if(superScope.maxNewElements>=0 && (superScope.maxNewElements<subScope.maxNewElements || subScope.maxNewElements<0)) {
118// println('''
119// «(subScope.targetTypeInterpretation as PartialComplexTypeInterpretation).interpretationOf.name» -> «(superScope.targetTypeInterpretation as PartialComplexTypeInterpretation).interpretationOf.name»
120// subScope.maxNewElements «subScope.maxNewElements» = superScope.maxNewElements «superScope.maxNewElements»
121// ''')
122 subScope.maxNewElements = superScope.maxNewElements
123 return true
124 } else {
125 return false
126 }
127 }
128
129 private def propagateLowerLimitUp(Scope subScope, PartialInterpretation p) {
130 if(subScope.minNewElements>p.minNewElements) {
131// println('''
132// «(subScope.targetTypeInterpretation as PartialComplexTypeInterpretation).interpretationOf.name» -> nodes
133// p.minNewElements «p.minNewElements» = subScope.minNewElements «subScope.minNewElements»
134// ''')
135 p.minNewElements = subScope.minNewElements
136 return true
137 } else {
138 return false
139 }
140 }
141
142 private def propagateUpperLimitDown(Scope subScope, PartialInterpretation p) {
143 if(p.maxNewElements>=0 && (p.maxNewElements<subScope.maxNewElements || subScope.maxNewElements<0)) {
144// println('''
145// «(subScope.targetTypeInterpretation as PartialComplexTypeInterpretation).interpretationOf.name» -> nodes
146// subScope.maxNewElements «subScope.maxNewElements» = p.maxNewElements «p.maxNewElements»
147// ''')
148 subScope.maxNewElements = p.maxNewElements
149 return true
150 } else {
151 return false
152 }
153 }
154 private def removeOne(Scope scope) {
155 if(scope.maxNewElements===0) {
156 scope.maxNewElements=0
157 //throw new IllegalArgumentException('''Inconsistent object creation: «scope.targetTypeInterpretation»''')
158 } else if(scope.maxNewElements>0) {
159 scope.maxNewElements= scope.maxNewElements-1
160 }
161 if(scope.minNewElements>0) {
162 scope.minNewElements= scope.minNewElements-1
163 }
164 }
165}
166 \ 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/cardinality/AbstractPolyhedronSaturationOperator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/AbstractPolyhedronSaturationOperator.xtend
new file mode 100644
index 00000000..94f97e94
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/AbstractPolyhedronSaturationOperator.xtend
@@ -0,0 +1,53 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality
2
3import com.google.common.collect.ImmutableList
4import org.eclipse.xtend.lib.annotations.Accessors
5
6abstract class AbstractPolyhedronSaturationOperator implements PolyhedronSaturationOperator {
7 @Accessors val Polyhedron polyhedron
8
9 new(Polyhedron polyhedron) {
10 if (polyhedron.dimensions.empty) {
11 throw new IllegalArgumentException("Polyhedron must have at least one dimension.")
12 }
13 this.polyhedron = polyhedron
14 }
15
16 override saturate() {
17 if (polyhedron.expressionsToSaturate.empty) {
18 return PolyhedronSaturationResult.SATURATED
19 }
20 for (constraint : polyhedron.constraints) {
21 if (constraint.zero) {
22 if (constraint.lowerBound !== null && constraint.lowerBound > 0) {
23 return PolyhedronSaturationResult.EMPTY
24 }
25 if (constraint.upperBound !== null && constraint.upperBound < 0) {
26 return PolyhedronSaturationResult.EMPTY
27 }
28 } else {
29 if (constraint.lowerBound !== null && constraint.upperBound !== null &&
30 constraint.upperBound < constraint.lowerBound) {
31 return PolyhedronSaturationResult.EMPTY
32 }
33 }
34 }
35 doSaturate()
36 }
37
38 protected def PolyhedronSaturationResult doSaturate()
39
40 protected def getNonTrivialConstraints() {
41 ImmutableList.copyOf(polyhedron.constraints.filter [ constraint |
42 (constraint.lowerBound !== null || constraint.upperBound !== null) && !constraint.zero
43 ])
44 }
45
46 private static def isZero(LinearConstraint constraint) {
47 constraint.coefficients.values.forall[it == 0]
48 }
49
50 override close() throws Exception {
51 // Nothing to close by default.
52 }
53}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/CbcPolyhedronSolver.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/CbcPolyhedronSolver.xtend
new file mode 100644
index 00000000..708f93dc
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/CbcPolyhedronSolver.xtend
@@ -0,0 +1,241 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality
2
3import com.google.common.collect.ImmutableList
4import com.google.common.collect.ImmutableMap
5import hu.bme.mit.inf.dslreasoner.ilp.cbc.CbcResult
6import hu.bme.mit.inf.dslreasoner.ilp.cbc.CbcSolver
7import java.util.HashSet
8import java.util.List
9import java.util.Map
10import java.util.Set
11import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor
12
13@FinalFieldsConstructor
14class CbcPolyhedronSolver implements PolyhedronSolver {
15 val boolean lpRelaxation
16 val double timeoutSeconds
17 val boolean silent
18
19 new() {
20 this(false, -1, true)
21 }
22
23 override createSaturationOperator(Polyhedron polyhedron) {
24 new CbcSaturationOperator(polyhedron, lpRelaxation, timeoutSeconds, silent)
25 }
26}
27
28class CbcSaturationOperator extends AbstractPolyhedronSaturationOperator {
29 static val EPSILON = 1e-6
30
31 val boolean lpRelaxation
32 val double timeoutSeconds
33 val boolean silent
34 val double[] columnLowerBounds
35 val double[] columnUpperBounds
36 val double[] objective
37 val Map<Dimension, Integer> dimensionsToIndicesMap
38
39 new(Polyhedron polyhedron, boolean lpRelaxation, double timeoutSeconds, boolean silent) {
40 super(polyhedron)
41 this.lpRelaxation = lpRelaxation
42 this.timeoutSeconds = timeoutSeconds
43 this.silent = silent
44 val numDimensions = polyhedron.dimensions.size
45 columnLowerBounds = newDoubleArrayOfSize(numDimensions)
46 columnUpperBounds = newDoubleArrayOfSize(numDimensions)
47 objective = newDoubleArrayOfSize(numDimensions)
48 dimensionsToIndicesMap = ImmutableMap.copyOf(polyhedron.dimensions.indexed.toMap([value], [key]))
49 }
50
51 override doSaturate() {
52 val numDimensions = polyhedron.dimensions.size
53 for (var int j = 0; j < numDimensions; j++) {
54 val dimension = polyhedron.dimensions.get(j)
55 columnLowerBounds.set(j, dimension.lowerBound.toDouble(Double.NEGATIVE_INFINITY))
56 columnUpperBounds.set(j, dimension.upperBound.toDouble(Double.POSITIVE_INFINITY))
57 }
58 val constraints = nonTrivialConstraints
59 val numConstraints = constraints.size
60 val rowStarts = newIntArrayOfSize(numConstraints + 1)
61 val rowLowerBounds = newDoubleArrayOfSize(numConstraints)
62 val rowUpperBounds = newDoubleArrayOfSize(numConstraints)
63 val numEntries = constraints.map[coefficients.size].reduce[a, b|a + b] ?: 0
64 rowStarts.set(numConstraints, numEntries)
65 val columnIndices = newIntArrayOfSize(numEntries)
66 val entries = newDoubleArrayOfSize(numEntries)
67 val unconstrainedDimensions = new HashSet
68 for (dimension : polyhedron.dimensions) {
69 if (dimension.lowerBound === null && dimension.upperBound === null) {
70 unconstrainedDimensions += dimension
71 }
72 }
73 var int index = 0
74 for (var int i = 0; i < numConstraints; i++) {
75 rowStarts.set(i, index)
76 val constraint = constraints.get(i)
77 rowLowerBounds.set(i, constraint.lowerBound.toDouble(Double.NEGATIVE_INFINITY))
78 rowUpperBounds.set(i, constraint.upperBound.toDouble(Double.POSITIVE_INFINITY))
79 if (!dimensionsToIndicesMap.keySet.containsAll(constraint.coefficients.keySet)) {
80 throw new IllegalArgumentException("Constrains has unknown dimensions")
81 }
82 for (var int j = 0; j < numDimensions; j++) {
83 val dimension = polyhedron.dimensions.get(j)
84 val coefficient = constraint.coefficients.get(dimension)
85 if (coefficient !== null && coefficient != 0) {
86 unconstrainedDimensions -= dimension
87 columnIndices.set(index, j)
88 entries.set(index, coefficient)
89 index++
90 }
91 }
92 }
93 if (index != numEntries) {
94 throw new AssertionError("Last entry does not equal the number of entries in the constraint matrix")
95 }
96 for (expressionToSaturate : polyhedron.expressionsToSaturate) {
97 val result = saturate(expressionToSaturate, rowStarts, columnIndices, entries, rowLowerBounds,
98 rowUpperBounds, unconstrainedDimensions, constraints)
99 if (result != PolyhedronSaturationResult.SATURATED) {
100 return result
101 }
102 }
103 PolyhedronSaturationResult.SATURATED
104 }
105
106 protected def saturate(LinearBoundedExpression expressionToSaturate, int[] rowStarts, int[] columnIndices,
107 double[] entries, double[] rowLowerBounds, double[] rowUpperBounds, Set<Dimension> unconstrainedDimensions,
108 ImmutableList<LinearConstraint> constraints) {
109 val numDimensions = objective.size
110 for (var int j = 0; j < numDimensions; j++) {
111 objective.set(j, 0)
112 }
113 switch (expressionToSaturate) {
114 Dimension: {
115 // CBC will return nonsensical results or call free() with invalid arguments if
116 // it is passed a fully unconstrained (-Inf lower and +Int upper bound, no inequalities) variable
117 // in the objective function.
118 if (unconstrainedDimensions.contains(expressionToSaturate)) {
119 return PolyhedronSaturationResult.SATURATED
120 }
121 val j = getIndex(expressionToSaturate)
122 objective.set(j, 1)
123 }
124 LinearConstraint: {
125 for (pair : expressionToSaturate.coefficients.entrySet) {
126 val dimension = pair.key
127 // We also have to check for unconstrained dimensions here to avoid crashing.
128 if (unconstrainedDimensions.contains(dimension)) {
129 expressionToSaturate.lowerBound = null
130 expressionToSaturate.upperBound = null
131 return PolyhedronSaturationResult.SATURATED
132 }
133 val j = getIndex(dimension)
134 objective.set(j, pair.value)
135 }
136 }
137 default:
138 throw new IllegalArgumentException("Unknown expression: " + expressionToSaturate)
139 }
140 val minimizationResult = CbcSolver.solve(columnLowerBounds, columnUpperBounds, rowStarts, columnIndices,
141 entries, rowLowerBounds, rowUpperBounds, objective, lpRelaxation, timeoutSeconds, silent)
142 switch (minimizationResult) {
143 CbcResult.SolutionBounded: {
144 val doubleValue = minimizationResult.value
145 val roundedValue = Math.ceil(doubleValue - EPSILON)
146 val intValue = roundedValue as int
147 val oldBound = expressionToSaturate.lowerBound
148 if (oldBound === null || intValue >= oldBound) {
149 expressionToSaturate.lowerBound = intValue
150 setBound(expressionToSaturate, constraints, roundedValue, columnLowerBounds, rowLowerBounds)
151 } else {
152 throw new IllegalStateException("Unexpected decrease of lower bound by " + (oldBound - doubleValue))
153 }
154 }
155 case CbcResult.SOLUTION_UNBOUNDED: {
156 if (expressionToSaturate.lowerBound !== null) {
157 throw new IllegalStateException("Finite lower bound became infinite")
158 }
159 setBound(expressionToSaturate, constraints, Double.NEGATIVE_INFINITY, columnLowerBounds, rowLowerBounds)
160 }
161 case CbcResult.UNSAT:
162 return PolyhedronSaturationResult.EMPTY
163 case CbcResult.ABANDONED,
164 case CbcResult.TIMEOUT:
165 return PolyhedronSaturationResult.UNKNOWN
166 default:
167 throw new RuntimeException("Unknown CbcResult: " + minimizationResult)
168 }
169 for (var int j = 0; j < numDimensions; j++) {
170 val objectiveCoefficient = objective.get(j)
171 objective.set(j, -objectiveCoefficient)
172 }
173 val maximizationResult = CbcSolver.solve(columnLowerBounds, columnUpperBounds, rowStarts, columnIndices,
174 entries, rowLowerBounds, rowUpperBounds, objective, lpRelaxation, timeoutSeconds, silent)
175 switch (maximizationResult) {
176 CbcResult.SolutionBounded: {
177 val doubleValue = -maximizationResult.value
178 val roundedValue = Math.floor(doubleValue + EPSILON)
179 val intValue = roundedValue as int
180 val oldBound = expressionToSaturate.upperBound
181 if (oldBound === null || intValue <= oldBound) {
182 expressionToSaturate.upperBound = intValue
183 setBound(expressionToSaturate, constraints, roundedValue, columnUpperBounds, rowUpperBounds)
184 } else {
185 throw new IllegalStateException("Unexpected increase of upper bound by " + (doubleValue - oldBound))
186 }
187 }
188 case CbcResult.SOLUTION_UNBOUNDED: {
189 if (expressionToSaturate.lowerBound !== null) {
190 throw new IllegalStateException("Finite upper bound became infinite")
191 }
192 expressionToSaturate.upperBound = null
193 setBound(expressionToSaturate, constraints, Double.POSITIVE_INFINITY, columnUpperBounds, rowUpperBounds)
194 }
195 case CbcResult.UNSAT:
196 if (lpRelaxation) {
197 return PolyhedronSaturationResult.EMPTY
198 } else {
199 throw new RuntimeException("Minimization was SAT, but maximization is UNSAT")
200 }
201 case CbcResult.ABANDONED,
202 case CbcResult.TIMEOUT:
203 return PolyhedronSaturationResult.UNKNOWN
204 default:
205 throw new RuntimeException("Unknown CbcResult: " + maximizationResult)
206 }
207 return PolyhedronSaturationResult.SATURATED
208 }
209
210 private def toDouble(Integer nullableInt, double defaultValue) {
211 if (nullableInt === null) {
212 defaultValue
213 } else {
214 nullableInt.doubleValue
215 }
216 }
217
218 private def int getIndex(Dimension dimension) {
219 val index = dimensionsToIndicesMap.get(dimension)
220 if (index === null) {
221 throw new IllegalArgumentException("Unknown dimension: " + dimension)
222 }
223 index
224 }
225
226 private def void setBound(LinearBoundedExpression expression, List<LinearConstraint> constraints, double bound,
227 double[] columnBounds, double[] rowBounds) {
228 switch (expression) {
229 Dimension: {
230 val j = getIndex(expression)
231 columnBounds.set(j, bound)
232 }
233 LinearConstraint: {
234 val i = constraints.indexOf(expression)
235 if (i >= 0) {
236 rowBounds.set(i, bound)
237 }
238 }
239 }
240 }
241}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/LinearTypeConstraintHint.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/LinearTypeConstraintHint.xtend
new file mode 100644
index 00000000..8c21ca1d
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/LinearTypeConstraintHint.xtend
@@ -0,0 +1,30 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality
2
3import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type
4import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternGenerator
5import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
6import org.eclipse.viatra.query.runtime.api.IPatternMatch
7import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher
8
9interface LinearTypeExpressionBuilderFactory {
10 def ViatraQueryMatcher<? extends IPatternMatch> createMatcher(String queryName)
11
12 def LinearTypeExpressionBuilder createBuilder()
13}
14
15interface LinearTypeExpressionBuilder {
16 def LinearTypeExpressionBuilder add(int scale, Type type)
17
18 def LinearBoundedExpression build()
19}
20
21@FunctionalInterface
22interface RelationConstraintUpdater {
23 def void update(PartialInterpretation p)
24}
25
26interface LinearTypeConstraintHint {
27 def CharSequence getAdditionalPatterns(PatternGenerator patternGenerator)
28
29 def RelationConstraintUpdater createConstraintUpdater(LinearTypeExpressionBuilderFactory builderFactory)
30}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/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 05ce4f6e..034420d6 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/MultiplicityGoalConstraintCalculator.xtend
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/MultiplicityGoalConstraintCalculator.xtend
@@ -1,4 +1,4 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra 1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality
2 2
3import org.eclipse.emf.common.notify.Notifier 3import org.eclipse.emf.common.notify.Notifier
4import org.eclipse.viatra.query.runtime.api.IQuerySpecification 4import org.eclipse.viatra.query.runtime.api.IQuerySpecification
@@ -7,9 +7,9 @@ import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher
7import org.eclipse.viatra.query.runtime.emf.EMFScope 7import org.eclipse.viatra.query.runtime.emf.EMFScope
8 8
9class MultiplicityGoalConstraintCalculator { 9class 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 13 val int minValue
14 val boolean containment 14 val boolean containment
15 val int cost 15 val int cost
@@ -23,7 +23,7 @@ class MultiplicityGoalConstraintCalculator {
23 this.cost = cost 23 this.cost = cost
24 } 24 }
25 25
26 public new(MultiplicityGoalConstraintCalculator other) { 26 new(MultiplicityGoalConstraintCalculator other) {
27 this.targetRelationName = other.targetRelationName 27 this.targetRelationName = other.targetRelationName
28 this.querySpecification = other.querySpecification 28 this.querySpecification = other.querySpecification
29 this.matcher = null 29 this.matcher = null
@@ -32,24 +32,23 @@ class MultiplicityGoalConstraintCalculator {
32 this.cost = other.cost 32 this.cost = other.cost
33 } 33 }
34 34
35 def public getName() { 35 def getName() {
36 targetRelationName 36 targetRelationName
37 } 37 }
38 38
39 def isContainment() { 39 def isContainment() {
40 return containment 40 return containment
41 } 41 }
42 42
43 def public init(Notifier notifier) { 43 def init(Notifier notifier) {
44 val engine = ViatraQueryEngine.on(new EMFScope(notifier)) 44 val engine = ViatraQueryEngine.on(new EMFScope(notifier))
45 matcher = querySpecification.getMatcher(engine) 45 matcher = querySpecification.getMatcher(engine)
46 } 46 }
47 47
48 def public calculateValue() { 48 def calculateValue() {
49 var res = 0 49 var res = 0
50 val allMatches = this.matcher.allMatches 50 val allMatches = this.matcher.allMatches
51 for(match : allMatches) { 51 for(match : allMatches) {
52
53 val existingMultiplicity = match.get(4) as Integer 52 val existingMultiplicity = match.get(4) as Integer
54 if(existingMultiplicity < this.minValue) { 53 if(existingMultiplicity < this.minValue) {
55 val missingMultiplicity = this.minValue-existingMultiplicity 54 val missingMultiplicity = this.minValue-existingMultiplicity
@@ -63,4 +62,4 @@ class MultiplicityGoalConstraintCalculator {
63// println(targetRelationName+ " all missing multiplicities: "+res + "*"+cost+"="+res*cost) 62// println(targetRelationName+ " all missing multiplicities: "+res + "*"+cost+"="+res*cost)
64 return res*cost 63 return res*cost
65 } 64 }
66} \ No newline at end of file 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
new file mode 100644
index 00000000..120fb18a
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagator.xtend
@@ -0,0 +1,569 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality
2
3import com.google.common.cache.Cache
4import com.google.common.cache.CacheBuilder
5import com.google.common.collect.ImmutableList
6import com.google.common.collect.ImmutableMap
7import com.google.common.collect.ImmutableSet
8import com.google.common.collect.Maps
9import com.google.common.collect.Sets
10import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Relation
11import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type
12import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationStatistics
13import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.UnifinishedMultiplicityQueries
14import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialComplexTypeInterpretation
15import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
16import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialPrimitiveInterpretation
17import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope
18import java.util.ArrayDeque
19import java.util.ArrayList
20import java.util.Collection
21import java.util.HashMap
22import java.util.HashSet
23import java.util.List
24import java.util.Map
25import java.util.Set
26import javax.naming.OperationNotSupportedException
27import org.eclipse.viatra.query.runtime.api.IPatternMatch
28import org.eclipse.viatra.query.runtime.api.IQuerySpecification
29import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine
30import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher
31import org.eclipse.viatra.query.runtime.emf.EMFScope
32import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor
33
34class PolyhedronScopePropagator extends TypeHierarchyScopePropagator {
35 static val CACHE_SIZE = 10000
36
37 val boolean updateHeuristic
38 val Map<Scope, LinearBoundedExpression> scopeBounds
39 val LinearBoundedExpression topLevelBounds
40 val Polyhedron polyhedron
41 val PolyhedronSaturationOperator operator
42 val Set<Relation> relevantRelations
43 val Cache<PolyhedronSignature, PolyhedronSignature> cache = CacheBuilder.newBuilder.maximumSize(CACHE_SIZE).build
44 List<RelationConstraintUpdater> updaters = emptyList
45
46 new(PartialInterpretation p, ModelGenerationStatistics statistics, Set<? extends Type> possibleNewDynamicTypes,
47 Map<RelationMultiplicityConstraint, UnifinishedMultiplicityQueries> unfinishedMultiplicityQueries,
48 IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> hasElementInContainmentQuery,
49 Map<String, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> allPatternsByName,
50 Collection<LinearTypeConstraintHint> hints, PolyhedronSolver solver, boolean propagateRelations,
51 boolean updateHeuristic) {
52 super(p, statistics)
53 this.updateHeuristic = updateHeuristic
54 val builder = new PolyhedronBuilder(p)
55 builder.buildPolyhedron(possibleNewDynamicTypes)
56 scopeBounds = builder.scopeBounds
57 topLevelBounds = builder.topLevelBounds
58 polyhedron = builder.polyhedron
59 operator = solver.createSaturationOperator(polyhedron)
60 propagateAllScopeConstraints()
61 if (propagateRelations) {
62 val maximumNumberOfNewNodes = topLevelBounds.upperBound
63 if (maximumNumberOfNewNodes === null) {
64 throw new IllegalStateException("Could not determine maximum number of new nodes, it may be unbounded")
65 }
66 if (maximumNumberOfNewNodes <= 0) {
67 throw new IllegalStateException("Maximum number of new nodes is not positive")
68 }
69 builder.buildMultiplicityConstraints(unfinishedMultiplicityQueries, hasElementInContainmentQuery,
70 allPatternsByName, hints, maximumNumberOfNewNodes)
71 relevantRelations = builder.relevantRelations
72 updaters = builder.updaters
73 } else {
74 relevantRelations = emptySet
75 }
76 }
77
78 override void doPropagateAllScopeConstraints() {
79 super.doPropagateAllScopeConstraints()
80 resetBounds()
81 populatePolyhedronFromScope()
82// println(polyhedron)
83 val signature = polyhedron.createSignature
84 val cachedSignature = cache.getIfPresent(signature)
85 switch (cachedSignature) {
86 case null: {
87 statistics.incrementScopePropagationSolverCount
88 val result = operator.saturate()
89 if (result == PolyhedronSaturationResult.EMPTY) {
90 cache.put(signature, PolyhedronSignature.EMPTY)
91 setScopesInvalid()
92 } else {
93 val resultSignature = polyhedron.createSignature
94 cache.put(signature, resultSignature)
95 populateScopesFromPolyhedron()
96 }
97 }
98 case PolyhedronSignature.EMPTY:
99 setScopesInvalid()
100 PolyhedronSignature.Bounds: {
101 polyhedron.applySignature(signature)
102 populateScopesFromPolyhedron()
103 }
104 default:
105 throw new IllegalStateException("Unknown polyhedron signature: " + signature)
106 }
107// println(polyhedron)
108 if (updateHeuristic) {
109 copyScopeBoundsToHeuristic()
110 }
111 }
112
113 override propagateAdditionToRelation(Relation r) {
114 super.propagateAdditionToRelation(r)
115 if (relevantRelations.contains(r)) {
116 propagateAllScopeConstraints()
117 }
118 }
119
120 def resetBounds() {
121 for (dimension : polyhedron.dimensions) {
122 dimension.lowerBound = 0
123 dimension.upperBound = null
124 }
125 for (constraint : polyhedron.constraints) {
126 constraint.lowerBound = null
127 constraint.upperBound = null
128 }
129 }
130
131 private def populatePolyhedronFromScope() {
132 topLevelBounds.tightenLowerBound(partialInterpretation.minNewElements)
133 if (partialInterpretation.maxNewElements >= 0) {
134 topLevelBounds.tightenUpperBound(partialInterpretation.maxNewElements)
135 }
136 for (pair : scopeBounds.entrySet) {
137 val scope = pair.key
138 val bounds = pair.value
139 bounds.tightenLowerBound(scope.minNewElements)
140 if (scope.maxNewElements >= 0) {
141 bounds.tightenUpperBound(scope.maxNewElements)
142 }
143 }
144 for (updater : updaters) {
145 updater.update(partialInterpretation)
146 }
147 }
148
149 private def populateScopesFromPolyhedron() {
150 checkBounds(topLevelBounds)
151 if (partialInterpretation.minNewElements > topLevelBounds.lowerBound) {
152 throw new IllegalArgumentException('''Lower bound of «topLevelBounds» smaller than top-level scope: «partialInterpretation.minNewElements»''')
153 } else if (partialInterpretation.minNewElements != topLevelBounds.lowerBound) {
154 partialInterpretation.minNewElements = topLevelBounds.lowerBound
155 }
156 val topLevelUpperBound = topLevelBounds.upperBound ?: -1
157 if (partialInterpretation.maxNewElements >= 0 && topLevelUpperBound >= 0 &&
158 partialInterpretation.maxNewElements < topLevelUpperBound) {
159 throw new IllegalArgumentException('''Upper bound of «topLevelBounds» larger than top-level scope: «partialInterpretation.maxNewElements»''')
160 } else if (partialInterpretation.maxNewElements != topLevelUpperBound) {
161 partialInterpretation.maxNewElements = topLevelUpperBound
162 }
163 for (pair : scopeBounds.entrySet) {
164 val scope = pair.key
165 val bounds = pair.value
166 checkBounds(bounds)
167 if (scope.minNewElements > bounds.lowerBound) {
168 throw new IllegalArgumentException('''Lower bound of «bounds» smaller than «scope.targetTypeInterpretation» scope: «scope.minNewElements»''')
169 } else if (scope.minNewElements != bounds.lowerBound) {
170 scope.minNewElements = bounds.lowerBound
171 }
172 val upperBound = bounds.upperBound ?: -1
173 if (scope.maxNewElements >= 0 && upperBound >= 0 && scope.maxNewElements < upperBound) {
174 throw new IllegalArgumentException('''Upper bound of «bounds» larger than «scope.targetTypeInterpretation» scope: «scope.maxNewElements»''')
175 } else if (scope.maxNewElements != upperBound) {
176 scope.maxNewElements = upperBound
177 }
178 }
179 }
180
181 private def checkBounds(LinearBoundedExpression bounds) {
182 if (bounds.lowerBound === null) {
183 throw new IllegalArgumentException("Infinite lower bound: " + bounds)
184 } else if (bounds.lowerBound < 0) {
185 throw new IllegalArgumentException("Negative lower bound: " + bounds)
186 }
187 if (bounds.upperBound !== null && bounds.upperBound < 0) {
188 throw new IllegalArgumentException("Negative upper bound: " + bounds)
189 }
190 }
191
192 private static def <T extends IPatternMatch> getCalculatedMultiplicity(ViatraQueryMatcher<T> matcher,
193 PartialInterpretation p) {
194 val match = matcher.newEmptyMatch
195 match.set(0, p.problem)
196 match.set(1, p)
197 val iterator = matcher.streamAllMatches(match).iterator
198 if (!iterator.hasNext) {
199 return null
200 }
201 val value = iterator.next.get(2) as Integer
202 if (iterator.hasNext) {
203 throw new IllegalArgumentException("Multiplicity calculation query has more than one match")
204 }
205 value
206 }
207
208 @FinalFieldsConstructor
209 private static class PolyhedronBuilder implements LinearTypeExpressionBuilderFactory {
210 static val INFINITY_SCALE = 10
211
212 val PartialInterpretation p
213
214 Map<Type, Dimension> instanceCounts
215 Map<Type, Map<Dimension, Integer>> subtypeDimensions
216 Map<Map<Dimension, Integer>, LinearBoundedExpression> expressionsCache
217 Map<Type, LinearBoundedExpression> typeBounds
218 int infinity
219 ViatraQueryEngine queryEngine
220 Map<String, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> allPatternsByName
221 ImmutableList.Builder<RelationConstraintUpdater> updatersBuilder
222
223 Map<Scope, LinearBoundedExpression> scopeBounds
224 LinearBoundedExpression topLevelBounds
225 Polyhedron polyhedron
226 Set<Relation> relevantRelations
227 List<RelationConstraintUpdater> updaters
228
229 def buildPolyhedron(Set<? extends Type> possibleNewDynamicTypes) {
230 instanceCounts = possibleNewDynamicTypes.toInvertedMap[new Dimension(name, 0, null)]
231 val types = p.problem.types
232 expressionsCache = Maps.newHashMapWithExpectedSize(types.size)
233 subtypeDimensions = types.toInvertedMap[findSubtypeDimensions.toInvertedMap[1]]
234 typeBounds = ImmutableMap.copyOf(subtypeDimensions.mapValues[toExpression])
235 scopeBounds = buildScopeBounds
236 topLevelBounds = instanceCounts.values.toInvertedMap[1].toExpression
237 val dimensions = ImmutableList.copyOf(instanceCounts.values)
238 val expressionsToSaturate = ImmutableList.copyOf(scopeBounds.values)
239 polyhedron = new Polyhedron(dimensions, new ArrayList, expressionsToSaturate)
240 addCachedConstraintsToPolyhedron()
241 }
242
243 def buildMultiplicityConstraints(
244 Map<RelationMultiplicityConstraint, UnifinishedMultiplicityQueries> constraints,
245 IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> hasElementInContainmentQuery,
246 Map<String, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> allPatternsByName,
247 Collection<LinearTypeConstraintHint> hints, int maximumNuberOfNewNodes) {
248 infinity = maximumNuberOfNewNodes * INFINITY_SCALE
249 queryEngine = ViatraQueryEngine.on(new EMFScope(p))
250 this.allPatternsByName = allPatternsByName
251 updatersBuilder = ImmutableList.builder
252 val containmentConstraints = constraints.entrySet.filter[key.containment].groupBy[key.targetType]
253 for (pair : containmentConstraints.entrySet) {
254 buildContainmentConstraints(pair.key, pair.value)
255 }
256 buildConstainmentRootConstraints(containmentConstraints.keySet, hasElementInContainmentQuery)
257 for (pair : constraints.entrySet) {
258 val constraint = pair.key
259 if (!constraint.containment) {
260 buildNonContainmentConstraints(constraint, pair.value)
261 }
262 }
263 buildRelevantRelations(constraints.keySet)
264 for (hint : hints) {
265 updatersBuilder.add(hint.createConstraintUpdater(this))
266 }
267 updaters = updatersBuilder.build
268 addCachedConstraintsToPolyhedron()
269 }
270
271 private def buildRelevantRelations(Set<RelationMultiplicityConstraint> constraints) {
272 val builder = ImmutableSet.builder
273 for (constraint : constraints) {
274 builder.add(constraint.relation)
275 if (constraint.inverseRelation !== null) {
276 builder.add(constraint.inverseRelation)
277 }
278 }
279 relevantRelations = builder.build
280 }
281
282 private def addCachedConstraintsToPolyhedron() {
283 val constraints = new HashSet
284 constraints.addAll(expressionsCache.values.filter(LinearConstraint))
285 constraints.removeAll(polyhedron.constraints)
286 polyhedron.constraints.addAll(constraints)
287 }
288
289 private def buildContainmentConstraints(Type containedType,
290 List<Map.Entry<RelationMultiplicityConstraint, UnifinishedMultiplicityQueries>> constraints) {
291 val typeCoefficients = subtypeDimensions.get(containedType)
292 val orphansLowerBoundCoefficients = new HashMap(typeCoefficients)
293 val orphansUpperBoundCoefficients = new HashMap(typeCoefficients)
294 val unfinishedMultiplicitiesMatchersBuilder = ImmutableList.builder
295 val remainingContentsQueriesBuilder = ImmutableList.builder
296 for (pair : constraints) {
297 val constraint = pair.key
298 val containerCoefficients = subtypeDimensions.get(constraint.sourceType)
299 if (constraint.isUpperBoundFinite) {
300 orphansLowerBoundCoefficients.addCoefficients(-constraint.upperBound, containerCoefficients)
301 } else {
302 orphansLowerBoundCoefficients.addCoefficients(-infinity, containerCoefficients)
303 }
304 orphansUpperBoundCoefficients.addCoefficients(-constraint.lowerBound, containerCoefficients)
305 val queries = pair.value
306 if (constraint.constrainsUnfinished) {
307 if (queries.unfinishedMultiplicityQuery === null) {
308 throw new IllegalArgumentException(
309 "Containment constraints need unfinished multiplicity queries")
310 }
311 unfinishedMultiplicitiesMatchersBuilder.add(
312 queries.unfinishedMultiplicityQuery.getMatcher(queryEngine))
313 }
314 if (queries.remainingContentsQuery === null) {
315 throw new IllegalArgumentException("Containment constraints need remaining contents queries")
316 }
317 remainingContentsQueriesBuilder.add(queries.remainingContentsQuery.getMatcher(queryEngine))
318 }
319 val orphanLowerBound = orphansLowerBoundCoefficients.toExpression
320 val orphanUpperBound = orphansUpperBoundCoefficients.toExpression
321 val updater = new ContainmentConstraintUpdater(containedType.name, orphanLowerBound, orphanUpperBound,
322 unfinishedMultiplicitiesMatchersBuilder.build, remainingContentsQueriesBuilder.build)
323 updatersBuilder.add(updater)
324 }
325
326 private def buildConstainmentRootConstraints(Set<Type> containedTypes,
327 IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> hasElementInContainmentQuery) {
328 val matcher = hasElementInContainmentQuery.getMatcher(queryEngine)
329 val rootDimensions = Sets.newHashSet(instanceCounts.values)
330 for (type : containedTypes) {
331 val containedDimensions = subtypeDimensions.get(type).keySet
332 rootDimensions.removeAll(containedDimensions)
333 }
334 for (dimension : rootDimensions) {
335 updatersBuilder.add(new ContainmentRootConstraintUpdater(dimension, matcher))
336 }
337 }
338
339 private def buildNonContainmentConstraints(RelationMultiplicityConstraint constraint,
340 UnifinishedMultiplicityQueries queries) {
341 if (constraint.constrainsRemainingInverse) {
342 if (queries.unfinishedMultiplicityQuery === null) {
343 throw new IllegalArgumentException("Reference constraints need unfinished multiplicity queries")
344 }
345 val unfinishedMultiplicityMatcher = queries.unfinishedMultiplicityQuery.getMatcher(queryEngine)
346 if (queries.remainingInverseMultiplicityQuery === null) {
347 throw new IllegalArgumentException(
348 "Reference constraints need remaining inverse multiplicity queries")
349 }
350 val remainingInverseMultiplicityMatcher = queries.remainingInverseMultiplicityQuery.getMatcher(
351 queryEngine)
352 val availableMultiplicityCoefficients = new HashMap
353 availableMultiplicityCoefficients.addCoefficients(constraint.inverseUpperBound,
354 subtypeDimensions.get(constraint.targetType))
355 availableMultiplicityCoefficients.addCoefficients(-constraint.lowerBound,
356 subtypeDimensions.get(constraint.targetType))
357 val availableMultiplicity = availableMultiplicityCoefficients.toExpression
358 updatersBuilder.add(
359 new UnfinishedMultiplicityConstraintUpdater(constraint.relation.name, availableMultiplicity,
360 unfinishedMultiplicityMatcher, remainingInverseMultiplicityMatcher))
361 }
362 if (constraint.constrainsUnrepairable) {
363 if (queries.unrepairableMultiplicityQuery === null) {
364 throw new IllegalArgumentException("Reference constraints need unrepairable multiplicity queries")
365 }
366 val unrepairableMultiplicityMatcher = queries.unrepairableMultiplicityQuery.getMatcher(queryEngine)
367 val targetTypeCardinality = typeBounds.get(constraint.targetType)
368 updatersBuilder.add(
369 new UnrepairableMultiplicityConstraintUpdater(constraint.relation.name, targetTypeCardinality,
370 unrepairableMultiplicityMatcher))
371 }
372 }
373
374 private static def addCoefficients(Map<Dimension, Integer> accumulator, int scale, Map<Dimension, Integer> a) {
375 for (pair : a.entrySet) {
376 val dimension = pair.key
377 val currentValue = accumulator.get(pair.key) ?: 0
378 val newValue = currentValue + scale * pair.value
379 if (newValue == 0) {
380 accumulator.remove(dimension)
381 } else {
382 accumulator.put(dimension, newValue)
383 }
384 }
385 }
386
387 private def findSubtypeDimensions(Type type) {
388 val subtypes = new HashSet
389 val dimensions = new HashSet
390 val stack = new ArrayDeque
391 stack.addLast(type)
392 while (!stack.empty) {
393 val subtype = stack.removeLast
394 if (subtypes.add(subtype)) {
395 val dimension = instanceCounts.get(subtype)
396 if (dimension !== null) {
397 dimensions.add(dimension)
398 }
399 stack.addAll(subtype.subtypes)
400 }
401 }
402 dimensions
403 }
404
405 private def toExpression(Map<Dimension, Integer> coefficients) {
406 expressionsCache.computeIfAbsent(coefficients) [ c |
407 if (c.size == 1 && c.entrySet.head.value == 1) {
408 c.entrySet.head.key
409 } else {
410 new LinearConstraint(c, null, null)
411 }
412 ]
413 }
414
415 private def buildScopeBounds() {
416 val scopeBoundsBuilder = ImmutableMap.builder
417 for (scope : p.scopes) {
418 switch (targetTypeInterpretation : scope.targetTypeInterpretation) {
419 PartialPrimitiveInterpretation:
420 throw new OperationNotSupportedException("Primitive type scopes are not yet implemented")
421 PartialComplexTypeInterpretation: {
422 val complexType = targetTypeInterpretation.interpretationOf
423 val typeBound = typeBounds.get(complexType)
424 if (typeBound === null) {
425 if (scope.minNewElements > 0) {
426 throw new IllegalArgumentException("Found scope for " + complexType.name +
427 ", but the type cannot be instantiated")
428 }
429 } else {
430 scopeBoundsBuilder.put(scope, typeBound)
431 }
432 }
433 default:
434 throw new IllegalArgumentException("Unknown PartialTypeInterpretation: " +
435 targetTypeInterpretation)
436 }
437 }
438 scopeBoundsBuilder.build
439 }
440
441 override createMatcher(String queryName) {
442 val querySpecification = allPatternsByName.get(queryName)
443 if (querySpecification === null) {
444 throw new IllegalArgumentException("Unknown pattern: " + queryName)
445 }
446 querySpecification.getMatcher(queryEngine)
447 }
448
449 override createBuilder() {
450 new PolyhedronBuilderLinearTypeExpressionBuilder(this)
451 }
452 }
453
454 @FinalFieldsConstructor
455 private static class PolyhedronBuilderLinearTypeExpressionBuilder implements LinearTypeExpressionBuilder {
456 val PolyhedronBuilder polyhedronBuilder
457 val Map<Dimension, Integer> coefficients = new HashMap
458
459 override add(int scale, Type type) {
460 val typeCoefficients = polyhedronBuilder.subtypeDimensions.get(type)
461 if (typeCoefficients === null) {
462 throw new IllegalArgumentException("Unknown type: " + type)
463 }
464 PolyhedronBuilder.addCoefficients(coefficients, scale, typeCoefficients)
465 this
466 }
467
468 override build() {
469 polyhedronBuilder.toExpression(coefficients)
470 }
471 }
472
473 @FinalFieldsConstructor
474 private static class ContainmentConstraintUpdater implements RelationConstraintUpdater {
475 val String name
476 val LinearBoundedExpression orphansLowerBound
477 val LinearBoundedExpression orphansUpperBound
478 val List<ViatraQueryMatcher<? extends IPatternMatch>> unfinishedMultiplicitiesMatchers
479 val List<ViatraQueryMatcher<? extends IPatternMatch>> remainingContentsQueries
480
481 override update(PartialInterpretation p) {
482 tightenLowerBound(p)
483 tightenUpperBound(p)
484 }
485
486 private def tightenLowerBound(PartialInterpretation p) {
487 var int sum = 0
488 for (matcher : remainingContentsQueries) {
489 val value = matcher.getCalculatedMultiplicity(p)
490 if (value === null) {
491 throw new IllegalArgumentException("Remaining contents count is missing for " + name)
492 }
493 if (value == -1) {
494 // Infinite upper bound, no need to tighten.
495 return
496 }
497 sum += value
498 }
499 orphansLowerBound.tightenUpperBound(sum)
500 }
501
502 private def tightenUpperBound(PartialInterpretation p) {
503 var int sum = 0
504 for (matcher : unfinishedMultiplicitiesMatchers) {
505 val value = matcher.getCalculatedMultiplicity(p)
506 if (value === null) {
507 throw new IllegalArgumentException("Unfinished multiplicity is missing for " + name)
508 }
509 sum += value
510 }
511 orphansUpperBound.tightenLowerBound(sum)
512 }
513 }
514
515 @FinalFieldsConstructor
516 private static class ContainmentRootConstraintUpdater implements RelationConstraintUpdater {
517 val LinearBoundedExpression typeCardinality
518 val ViatraQueryMatcher<? extends IPatternMatch> hasElementInContainmentMatcher
519
520 override update(PartialInterpretation p) {
521 if (hasElementInContainmentMatcher.hasMatch(p)) {
522 typeCardinality.tightenUpperBound(0)
523 } else {
524 typeCardinality.tightenUpperBound(1)
525 }
526 }
527
528 private static def <T extends IPatternMatch> hasMatch(ViatraQueryMatcher<T> matcher, PartialInterpretation p) {
529 val match = matcher.newMatch(p.problem, p)
530 matcher.countMatches(match) != 0
531 }
532 }
533
534 @FinalFieldsConstructor
535 private static class UnfinishedMultiplicityConstraintUpdater implements RelationConstraintUpdater {
536 val String name
537 val LinearBoundedExpression availableMultiplicityExpression
538 val ViatraQueryMatcher<? extends IPatternMatch> unfinishedMultiplicityMatcher
539 val ViatraQueryMatcher<? extends IPatternMatch> remainingInverseMultiplicityMatcher
540
541 override update(PartialInterpretation p) {
542 val unfinishedMultiplicity = unfinishedMultiplicityMatcher.getCalculatedMultiplicity(p)
543 if (unfinishedMultiplicity === null) {
544 throw new IllegalArgumentException("Unfinished multiplicity is missing for " + name)
545 }
546 val remainingInverseMultiplicity = remainingInverseMultiplicityMatcher.getCalculatedMultiplicity(p)
547 if (remainingInverseMultiplicity === null) {
548 throw new IllegalArgumentException("Remaining inverse multiplicity is missing for " + name)
549 }
550 val int requiredMultiplicity = unfinishedMultiplicity - remainingInverseMultiplicity
551 availableMultiplicityExpression.tightenLowerBound(requiredMultiplicity)
552 }
553 }
554
555 @FinalFieldsConstructor
556 private static class UnrepairableMultiplicityConstraintUpdater implements RelationConstraintUpdater {
557 val String name
558 val LinearBoundedExpression targetCardinalityExpression
559 val ViatraQueryMatcher<? extends IPatternMatch> unrepairableMultiplicityMatcher
560
561 override update(PartialInterpretation p) {
562 val value = unrepairableMultiplicityMatcher.getCalculatedMultiplicity(p)
563 if (value === null) {
564 throw new IllegalArgumentException("Unrepairable multiplicity is missing for " + name)
565 }
566 targetCardinalityExpression.tightenLowerBound(value)
567 }
568 }
569}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronSolver.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronSolver.xtend
new file mode 100644
index 00000000..4e046190
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronSolver.xtend
@@ -0,0 +1,179 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality
2
3import java.util.List
4import java.util.Map
5import org.eclipse.xtend.lib.annotations.Accessors
6import org.eclipse.xtend.lib.annotations.Data
7import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor
8
9interface PolyhedronSolver {
10 def PolyhedronSaturationOperator createSaturationOperator(Polyhedron polyhedron)
11}
12
13enum PolyhedronSaturationResult {
14 SATURATED,
15 EMPTY,
16 UNKNOWN
17}
18
19interface PolyhedronSaturationOperator extends AutoCloseable {
20 def Polyhedron getPolyhedron()
21
22 def PolyhedronSaturationResult saturate()
23}
24
25@FinalFieldsConstructor
26@Accessors
27class Polyhedron {
28 /**
29 * The list of dimensions (variables) for this polyhedron.
30 *
31 * This list must not be modified after the polyhedron was created.
32 * However, lower and upper bounds of the dimensions may be changed.
33 *
34 * Names of dimensions in this list are assumed to be unique.
35 */
36 val List<Dimension> dimensions
37
38 /**
39 * The list of constraints defining this polyhedron.
40 *
41 * The list and its elements may be freely modified.
42 */
43 val List<LinearConstraint> constraints
44
45 /**
46 * The list of constraints that should be saturated (tightened)
47 * when a {@link PolyhedronSaturationOperator} is invoked.
48 *
49 * This list may be freely modified.
50 *
51 * Place all dimensions and constraints here to saturate all the bounds.
52 */
53 val List<LinearBoundedExpression> expressionsToSaturate
54
55 override toString() '''
56 Dimensions:
57 «FOR dimension : dimensions»
58 «dimension»
59 «ENDFOR»
60 Constraints:
61 «FOR constraint : constraints»
62 «constraint»
63 «ENDFOR»
64 '''
65
66 def createSignature() {
67 val size = dimensions.size + constraints.size
68 val lowerBounds = newArrayOfSize(size)
69 val upperBounds = newArrayOfSize(size)
70 var int i = 0
71 for (dimension : dimensions) {
72 lowerBounds.set(i, dimension.lowerBound)
73 upperBounds.set(i, dimension.upperBound)
74 i++
75 }
76 for (constraint : constraints) {
77 lowerBounds.set(i, constraint.lowerBound)
78 upperBounds.set(i, constraint.upperBound)
79 i++
80 }
81 new PolyhedronSignature.Bounds(lowerBounds, upperBounds)
82 }
83
84 def applySignature(PolyhedronSignature.Bounds signature) {
85 val lowerBounds = signature.lowerBounds
86 val upperBounds = signature.upperBounds
87 var int i = 0
88 for (dimension : dimensions) {
89 dimension.lowerBound = lowerBounds.get(i)
90 dimension.upperBound = upperBounds.get(i)
91 i++
92 }
93 for (constraint : constraints) {
94 constraint.lowerBound = lowerBounds.get(i)
95 constraint.upperBound = upperBounds.get(i)
96 i++
97 }
98 }
99}
100
101abstract class PolyhedronSignature {
102 public static val EMPTY = new PolyhedronSignature {
103 override toString() {
104 "PolyhedronSignature.EMPTY"
105 }
106 }
107
108 private new() {
109 }
110
111 @Data
112 static class Bounds extends PolyhedronSignature {
113 val Integer[] lowerBounds
114 val Integer[] upperBounds
115 }
116}
117
118@Accessors
119abstract class LinearBoundedExpression {
120 var Integer lowerBound
121 var Integer upperBound
122
123 def void tightenLowerBound(Integer tighterBound) {
124 if (lowerBound === null || (tighterBound !== null && lowerBound < tighterBound)) {
125 lowerBound = tighterBound
126 }
127 }
128
129 def void tightenUpperBound(Integer tighterBound) {
130 if (upperBound === null || (tighterBound !== null && upperBound > tighterBound)) {
131 upperBound = tighterBound
132 }
133 }
134
135 def void assertEqualsTo(int bound) {
136 tightenLowerBound(bound)
137 tightenUpperBound(bound)
138 }
139}
140
141@Accessors
142class Dimension extends LinearBoundedExpression {
143 val String name
144
145 @FinalFieldsConstructor
146 new() {
147 }
148
149 new(String name, Integer lowerBound, Integer upperBound) {
150 this(name)
151 this.lowerBound = lowerBound
152 this.upperBound = upperBound
153 }
154
155 override toString() {
156 '''«IF lowerBound !== null»«lowerBound» <= «ENDIF»«name»«IF upperBound !== null» <= «upperBound»«ENDIF»'''
157 }
158
159}
160
161@Accessors
162class LinearConstraint extends LinearBoundedExpression {
163 val Map<Dimension, Integer> coefficients
164
165 @FinalFieldsConstructor
166 new() {
167 }
168
169 new(Map<Dimension, Integer> coefficients, Integer lowerBound, Integer upperBound) {
170 this(coefficients)
171 this.lowerBound = lowerBound
172 this.upperBound = upperBound
173 }
174
175 override toString() {
176 '''«IF lowerBound !== null»«lowerBound» <= «ENDIF»«FOR pair : coefficients.entrySet SEPARATOR " + "»«IF pair.value != 1»«pair.value» * «ENDIF»«pair.key.name»«ENDFOR»«IF upperBound !== null» <= «upperBound»«ENDIF»'''
177 }
178
179}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/RelationConstraintCalculator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/RelationConstraintCalculator.xtend
new file mode 100644
index 00000000..3e4fea8a
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/RelationConstraintCalculator.xtend
@@ -0,0 +1,139 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality
2
3import com.google.common.collect.ImmutableList
4import com.google.common.collect.ImmutableSet
5import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.InverseRelationAssertion
6import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.LowerMultiplicityAssertion
7import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.UpperMultiplicityAssertion
8import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.ComplexTypeReference
9import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Relation
10import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem
11import java.util.HashMap
12import java.util.List
13import org.eclipse.xtend.lib.annotations.Data
14
15@Data
16class RelationConstraints {
17 val List<RelationMultiplicityConstraint> multiplicityConstraints
18}
19
20@Data
21class RelationMultiplicityConstraint {
22 Relation relation
23 Relation inverseRelation
24 boolean containment
25 boolean container
26 int lowerBound
27 int upperBound
28 int inverseUpperBound
29
30 def isUpperBoundFinite() {
31 upperBound >= 0
32 }
33
34 private def isInverseUpperBoundFinite() {
35 inverseUpperBound >= 0
36 }
37
38 private def canHaveMultipleSourcesPerTarget() {
39 inverseUpperBound != 1
40 }
41
42 def constrainsUnfinished() {
43 lowerBound >= 1 && (!container || lowerBound >= 2)
44 }
45
46 def constrainsUnrepairable() {
47 // TODO Optimize the unrepairable matches computation,
48 // or come up with a heuristic when does computing unrepairables worth the overhead.
49 constrainsUnfinished && canHaveMultipleSourcesPerTarget && false
50 }
51
52 def constrainsRemainingInverse() {
53 lowerBound >= 1 && !containment && inverseUpperBoundFinite
54 }
55
56 def constrainsRemainingContents() {
57 containment
58 }
59
60 def isActive() {
61 constrainsUnfinished || constrainsUnrepairable || constrainsRemainingInverse || constrainsRemainingContents
62 }
63
64 def getSourceType() {
65 getParamType(0)
66 }
67
68 def getTargetType() {
69 getParamType(1)
70 }
71
72 private def getParamType(int i) {
73 val parameters = relation.parameters
74 if (i < parameters.size) {
75 val firstParam = parameters.get(i)
76 if (firstParam instanceof ComplexTypeReference) {
77 return firstParam.referred
78 }
79 }
80 throw new IllegalArgumentException("Constraint with unknown source type")
81 }
82}
83
84class RelationConstraintCalculator {
85 def calculateRelationConstraints(LogicProblem problem) {
86 val containmentRelations = switch (problem.containmentHierarchies.size) {
87 case 0:
88 <Relation>emptySet
89 case 1:
90 ImmutableSet.copyOf(problem.containmentHierarchies.head.containmentRelations)
91 default:
92 throw new IllegalArgumentException("Only a single containment hierarchy is supported")
93 }
94 val inverseRelations = new HashMap<Relation, Relation>
95 val lowerMultiplicities = new HashMap<Relation, Integer>
96 val upperMultiplicities = new HashMap<Relation, Integer>
97 for (relation : problem.relations) {
98 lowerMultiplicities.put(relation, 0)
99 upperMultiplicities.put(relation, -1)
100 }
101 for (annotation : problem.annotations) {
102 switch (annotation) {
103 InverseRelationAssertion: {
104 inverseRelations.put(annotation.inverseA, annotation.inverseB)
105 inverseRelations.put(annotation.inverseB, annotation.inverseA)
106 }
107 LowerMultiplicityAssertion:
108 lowerMultiplicities.put(annotation.relation, annotation.lower)
109 UpperMultiplicityAssertion:
110 upperMultiplicities.put(annotation.relation, annotation.upper)
111 }
112 }
113 val multiplicityConstraintsBuilder = ImmutableList.builder()
114 for (relation : problem.relations) {
115 val containment = containmentRelations.contains(relation)
116 val lowerMultiplicity = lowerMultiplicities.get(relation)
117 val upperMultiplicity = upperMultiplicities.get(relation)
118 var container = false
119 var inverseUpperMultiplicity = -1
120 val inverseRelation = inverseRelations.get(relation)
121 if (inverseRelation !== null) {
122 inverseUpperMultiplicity = upperMultiplicities.get(inverseRelation)
123 container = containmentRelations.contains(inverseRelation)
124 }
125 if (containment) {
126 inverseUpperMultiplicity = 1
127 }
128 val constraint = new RelationMultiplicityConstraint(relation, inverseRelation, containment, container,
129 lowerMultiplicity, upperMultiplicity, inverseUpperMultiplicity)
130 if (constraint.isActive) {
131 if (relation.parameters.size != 2) {
132 throw new IllegalArgumentException('''Relation «relation.name» has multiplicity or containment constraints, but it is not binary''')
133 }
134 multiplicityConstraintsBuilder.add(constraint)
135 }
136 }
137 new RelationConstraints(multiplicityConstraintsBuilder.build)
138 }
139}
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
new file mode 100644
index 00000000..8f3a5bb0
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ScopePropagator.xtend
@@ -0,0 +1,134 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality
2
3import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Relation
4import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationStatistics
5import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialComplexTypeInterpretation
6import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
7import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialTypeInterpratation
8import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope
9import java.util.HashMap
10import java.util.HashSet
11import java.util.Map
12import java.util.Set
13import org.eclipse.xtend.lib.annotations.Accessors
14
15class ScopePropagator {
16 @Accessors(PROTECTED_GETTER) val PartialInterpretation partialInterpretation
17 @Accessors(PROTECTED_GETTER) val ModelGenerationStatistics statistics
18 val Map<PartialTypeInterpratation, Scope> type2Scope
19 @Accessors(PROTECTED_GETTER) val Map<Scope, Set<Scope>> superScopes
20 @Accessors(PROTECTED_GETTER) val Map<Scope, Set<Scope>> subScopes
21
22 new(PartialInterpretation p, ModelGenerationStatistics statistics) {
23 partialInterpretation = p
24 this.statistics = statistics
25 type2Scope = new HashMap
26 for (scope : p.scopes) {
27 type2Scope.put(scope.targetTypeInterpretation, scope)
28 }
29
30 superScopes = new HashMap
31 subScopes = new HashMap
32 for (scope : p.scopes) {
33 superScopes.put(scope, new HashSet)
34 subScopes.put(scope, new HashSet)
35 }
36
37 for (scope : p.scopes) {
38 val target = scope.targetTypeInterpretation
39 if (target instanceof PartialComplexTypeInterpretation) {
40 val supertypeInterpretations = target.supertypeInterpretation
41 for (supertypeInterpretation : supertypeInterpretations) {
42 val supertypeScope = type2Scope.get(supertypeInterpretation)
43 superScopes.get(scope).add(supertypeScope)
44 subScopes.get(supertypeScope).add(scope)
45 }
46 }
47 }
48 var boolean changed
49 do {
50 changed = false
51 for (scope : p.scopes) {
52 val subScopeSet = subScopes.get(scope)
53 val superScopeSet = superScopes.get(scope)
54 for (subScope : subScopeSet) {
55 changed = changed || superScopes.get(subScope).addAll(superScopeSet)
56 }
57 for (superScope : superScopeSet) {
58 changed = changed || subScopes.get(superScope).addAll(subScopeSet)
59 }
60 }
61 } while (changed)
62
63 copyScopeBoundsToHeuristic()
64 }
65
66 def propagateAllScopeConstraints() {
67 statistics.incrementScopePropagationCount()
68 doPropagateAllScopeConstraints()
69 }
70
71 protected def copyScopeBoundsToHeuristic() {
72 partialInterpretation.minNewElementsHeuristic = partialInterpretation.minNewElements
73 for (scope : partialInterpretation.scopes) {
74 scope.minNewElementsHeuristic = scope.minNewElements
75 }
76 }
77
78 protected def void doPropagateAllScopeConstraints() {
79 // Nothing to propagate.
80 }
81
82 def decrementTypeScope(PartialTypeInterpratation t) {
83// println('''Adding to «(t as PartialComplexTypeInterpretation).interpretationOf.name»''')
84 val targetScope = type2Scope.get(t)
85 if (targetScope !== null) {
86 targetScope.removeOne
87 val sups = superScopes.get(targetScope)
88 sups.forEach[removeOne]
89 }
90 if (this.partialInterpretation.minNewElements > 0) {
91 this.partialInterpretation.minNewElements = this.partialInterpretation.minNewElements - 1
92 }
93 if (this.partialInterpretation.minNewElementsHeuristic > 0) {
94 this.partialInterpretation.minNewElementsHeuristic = this.partialInterpretation.minNewElementsHeuristic - 1
95 }
96 if (this.partialInterpretation.maxNewElements > 0) {
97 this.partialInterpretation.maxNewElements = this.partialInterpretation.maxNewElements - 1
98 } else if (this.partialInterpretation.maxNewElements === 0) {
99 setScopesInvalid()
100 }
101
102// println('''Target Scope: «targetScope.minNewElements» - «targetScope.maxNewElements»''')
103// println(''' «this.partialInterpretation.minNewElements» - «this.partialInterpretation.maxNewElements»''')
104// this.partialInterpretation.scopes.forEach[println(''' «(it.targetTypeInterpretation as PartialComplexTypeInterpretation).interpretationOf.name»: «it.minNewElements»-«it.maxNewElements»''')]
105// println('''All constraints are propagated upon increasing «(t as PartialComplexTypeInterpretation).interpretationOf.name»''')
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 }
116
117 def void propagateAdditionToRelation(Relation r) {
118 // Nothing to propagate.
119 }
120
121 private def removeOne(Scope scope) {
122 if (scope.maxNewElements === 0) {
123 throw new IllegalArgumentException('''Inconsistent object creation: «scope.targetTypeInterpretation»''')
124 } else if (scope.maxNewElements > 0) {
125 scope.maxNewElements = scope.maxNewElements - 1
126 }
127 if (scope.minNewElements > 0) {
128 scope.minNewElements = scope.minNewElements - 1
129 }
130 if (scope.minNewElementsHeuristic > 0) {
131 scope.minNewElementsHeuristic = scope.minNewElementsHeuristic - 1
132 }
133 }
134}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ScopePropagatorStrategy.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ScopePropagatorStrategy.xtend
new file mode 100644
index 00000000..3165917a
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ScopePropagatorStrategy.xtend
@@ -0,0 +1,71 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality
2
3import org.eclipse.xtend.lib.annotations.Data
4import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor
5
6enum PolyhedralScopePropagatorConstraints {
7 TypeHierarchy,
8 Relational
9}
10
11enum PolyhedralScopePropagatorSolver {
12 Z3Real,
13 Z3Integer,
14 Cbc,
15 Clp
16}
17
18abstract class ScopePropagatorStrategy {
19 public static val None = new Simple("None")
20
21 public static val Basic = new Simple("Basic")
22
23 public static val BasicTypeHierarchy = new Simple("BasicTypeHierarchy")
24
25 private new() {
26 }
27
28 def boolean requiresUpperBoundIndexing()
29
30 static class Simple extends ScopePropagatorStrategy {
31 val String name
32
33 @FinalFieldsConstructor
34 private new() {
35 }
36
37 override requiresUpperBoundIndexing() {
38 false
39 }
40
41 override toString() {
42 name
43 }
44 }
45
46 @Data
47 static class Polyhedral extends ScopePropagatorStrategy {
48 public static val UNLIMITED_TIME = -1
49
50 val PolyhedralScopePropagatorConstraints constraints
51 val PolyhedralScopePropagatorSolver solver
52 val boolean updateHeuristic
53 val double timeoutSeconds
54
55 @FinalFieldsConstructor
56 new() {
57 }
58
59 new(PolyhedralScopePropagatorConstraints constraints, PolyhedralScopePropagatorSolver solver, boolean updateHeuristic) {
60 this(constraints, solver, updateHeuristic, UNLIMITED_TIME)
61 }
62
63 new(PolyhedralScopePropagatorConstraints constraints, PolyhedralScopePropagatorSolver solver) {
64 this(constraints, solver, true)
65 }
66
67 override requiresUpperBoundIndexing() {
68 constraints == PolyhedralScopePropagatorConstraints.Relational
69 }
70 }
71}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/TypeHierarchyScopePropagator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/TypeHierarchyScopePropagator.xtend
new file mode 100644
index 00000000..d1704b39
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/TypeHierarchyScopePropagator.xtend
@@ -0,0 +1,85 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality
2
3import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationStatistics
4import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
5import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope
6
7class TypeHierarchyScopePropagator extends ScopePropagator {
8
9 new(PartialInterpretation p, ModelGenerationStatistics statistics) {
10 super(p, statistics)
11 }
12
13 protected override doPropagateAllScopeConstraints() {
14 var boolean hadChanged
15 do {
16 hadChanged = false
17 for (superScopeEntry : superScopes.entrySet) {
18 val sub = superScopeEntry.key
19 hadChanged = propagateLowerLimitUp(sub, partialInterpretation) || hadChanged
20 hadChanged = propagateUpperLimitDown(sub, partialInterpretation) || hadChanged
21 for (sup : superScopeEntry.value) {
22 hadChanged = propagateLowerLimitUp(sub, sup) || hadChanged
23 hadChanged = propagateUpperLimitDown(sub, sup) || hadChanged
24 }
25 }
26 } while (hadChanged)
27 }
28
29 private def propagateLowerLimitUp(Scope subScope, Scope superScope) {
30 var changed = false
31 if (subScope.minNewElements > superScope.minNewElements) {
32 superScope.minNewElements = subScope.minNewElements
33 changed = true
34 }
35 if (subScope.minNewElementsHeuristic > superScope.minNewElementsHeuristic) {
36 superScope.minNewElementsHeuristic = subScope.minNewElementsHeuristic
37 changed = true
38 }
39 changed
40 }
41
42 private def propagateUpperLimitDown(Scope subScope, Scope superScope) {
43 if (superScope.maxNewElements >= 0 &&
44 (superScope.maxNewElements < subScope.maxNewElements || subScope.maxNewElements < 0)) {
45// println('''
46// «(subScope.targetTypeInterpretation as PartialComplexTypeInterpretation).interpretationOf.name» -> «(superScope.targetTypeInterpretation as PartialComplexTypeInterpretation).interpretationOf.name»
47// subScope.maxNewElements «subScope.maxNewElements» = superScope.maxNewElements «superScope.maxNewElements»
48// ''')
49 subScope.maxNewElements = superScope.maxNewElements
50 return true
51 } else {
52 return false
53 }
54 }
55
56 private def propagateLowerLimitUp(Scope subScope, PartialInterpretation p) {
57 var changed = false
58 if (subScope.minNewElements > p.minNewElements) {
59// println('''
60// «(subScope.targetTypeInterpretation as PartialComplexTypeInterpretation).interpretationOf.name» -> nodes
61// p.minNewElements «p.minNewElements» = subScope.minNewElements «subScope.minNewElements»
62// ''')
63 p.minNewElements = subScope.minNewElements
64 changed = true
65 }
66 if (subScope.minNewElementsHeuristic > p.minNewElementsHeuristic) {
67 p.minNewElementsHeuristic = subScope.minNewElementsHeuristic
68 changed = true
69 }
70 changed
71 }
72
73 private def propagateUpperLimitDown(Scope subScope, PartialInterpretation p) {
74 if (p.maxNewElements >= 0 && (p.maxNewElements < subScope.maxNewElements || subScope.maxNewElements < 0)) {
75// println('''
76// «(subScope.targetTypeInterpretation as PartialComplexTypeInterpretation).interpretationOf.name» -> nodes
77// subScope.maxNewElements «subScope.maxNewElements» = p.maxNewElements «p.maxNewElements»
78// ''')
79 subScope.maxNewElements = p.maxNewElements
80 return true
81 } else {
82 return false
83 }
84 }
85}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/Z3PolyhedronSolver.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/Z3PolyhedronSolver.xtend
new file mode 100644
index 00000000..3b831433
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/Z3PolyhedronSolver.xtend
@@ -0,0 +1,272 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality
2
3import com.microsoft.z3.AlgebraicNum
4import com.microsoft.z3.ArithExpr
5import com.microsoft.z3.Context
6import com.microsoft.z3.Expr
7import com.microsoft.z3.IntNum
8import com.microsoft.z3.Optimize
9import com.microsoft.z3.RatNum
10import com.microsoft.z3.Status
11import com.microsoft.z3.Symbol
12import java.math.BigDecimal
13import java.math.MathContext
14import java.math.RoundingMode
15import java.util.Map
16import org.eclipse.xtend.lib.annotations.Accessors
17import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor
18
19class Z3PolyhedronSolver implements PolyhedronSolver {
20 val boolean lpRelaxation
21 val double timeoutSeconds
22
23 @FinalFieldsConstructor
24 new() {
25 }
26
27 new() {
28 this(false, -1)
29 }
30
31 override createSaturationOperator(Polyhedron polyhedron) {
32 new DisposingZ3SaturationOperator(this, polyhedron)
33 }
34
35 def createPersistentSaturationOperator(Polyhedron polyhedron) {
36 new Z3SaturationOperator(polyhedron, lpRelaxation, timeoutSeconds)
37 }
38}
39
40@FinalFieldsConstructor
41class DisposingZ3SaturationOperator implements PolyhedronSaturationOperator {
42 val Z3PolyhedronSolver solver
43 @Accessors val Polyhedron polyhedron
44
45 override saturate() {
46 val persistentOperator = solver.createPersistentSaturationOperator(polyhedron)
47 try {
48 persistentOperator.saturate
49 } finally {
50 persistentOperator.close
51 }
52 }
53
54 override close() throws Exception {
55 // Nothing to close.
56 }
57}
58
59class Z3SaturationOperator extends AbstractPolyhedronSaturationOperator {
60 static val INFINITY_SYMBOL_NAME = "oo"
61 static val MULT_SYMBOL_NAME = "*"
62 static val TIMEOUT_SYMBOL_NAME = "timeout"
63 static val INTEGER_PRECISION = new BigDecimal(Integer.MAX_VALUE).precision
64 static val ROUND_DOWN = new MathContext(INTEGER_PRECISION, RoundingMode.FLOOR)
65 static val ROUND_UP = new MathContext(INTEGER_PRECISION, RoundingMode.CEILING)
66 // The interval isolating the number is smaller than 1/10^precision.
67 static val ALGEBRAIC_NUMBER_ROUNDING = 0
68
69 extension val Context context
70 val Symbol infinitySymbol
71 val Symbol multSymbol
72 val Map<Dimension, ArithExpr> variables
73 val int timeoutMilliseconds
74
75 new(Polyhedron polyhedron, boolean lpRelaxation, double timeoutSeconds) {
76 super(polyhedron)
77 context = new Context
78 infinitySymbol = context.mkSymbol(INFINITY_SYMBOL_NAME)
79 multSymbol = context.mkSymbol(MULT_SYMBOL_NAME)
80 variables = polyhedron.dimensions.toInvertedMap [ dimension |
81 val name = dimension.name
82 if (lpRelaxation) {
83 mkRealConst(name)
84 } else {
85 mkIntConst(name)
86 }
87 ]
88 timeoutMilliseconds = Math.ceil(timeoutSeconds * 1000) as int
89 }
90
91 override doSaturate() {
92 val status = executeSolver()
93 convertStatusToSaturationResult(status)
94 }
95
96 private def convertStatusToSaturationResult(Status status) {
97 switch (status) {
98 case SATISFIABLE:
99 PolyhedronSaturationResult.SATURATED
100 case UNSATISFIABLE:
101 PolyhedronSaturationResult.EMPTY
102 case UNKNOWN:
103 PolyhedronSaturationResult.UNKNOWN
104 default:
105 throw new IllegalArgumentException("Unknown Status: " + status)
106 }
107 }
108
109 private def executeSolver() {
110 for (expressionToSaturate : polyhedron.expressionsToSaturate) {
111 val expr = expressionToSaturate.toExpr
112 val lowerResult = saturateLowerBound(expr, expressionToSaturate)
113 if (lowerResult != Status.SATISFIABLE) {
114 return lowerResult
115 }
116 val upperResult = saturateUpperBound(expr, expressionToSaturate)
117 if (upperResult != Status.SATISFIABLE) {
118 return upperResult
119 }
120 }
121 Status.SATISFIABLE
122 }
123
124 private def saturateLowerBound(ArithExpr expr, LinearBoundedExpression expressionToSaturate) {
125 val optimize = prepareOptimize
126 val handle = optimize.MkMinimize(expr)
127 val status = optimize.Check()
128 if (status == Status.SATISFIABLE) {
129 val value = switch (resultExpr : handle.lower) {
130 IntNum:
131 resultExpr.getInt()
132 RatNum:
133 ceil(resultExpr)
134 AlgebraicNum:
135 ceil(resultExpr.toUpper(ALGEBRAIC_NUMBER_ROUNDING))
136 default:
137 if (isNegativeInfinity(resultExpr)) {
138 null
139 } else {
140 throw new IllegalArgumentException("Integer result expected, got: " + resultExpr)
141 }
142 }
143 expressionToSaturate.lowerBound = value
144 }
145 status
146 }
147
148 private def floor(RatNum ratNum) {
149 val numerator = new BigDecimal(ratNum.numerator.bigInteger)
150 val denominator = new BigDecimal(ratNum.denominator.bigInteger)
151 numerator.divide(denominator, ROUND_DOWN).setScale(0, RoundingMode.FLOOR).intValue
152 }
153
154 private def saturateUpperBound(ArithExpr expr, LinearBoundedExpression expressionToSaturate) {
155 val optimize = prepareOptimize
156 val handle = optimize.MkMaximize(expr)
157 val status = optimize.Check()
158 if (status == Status.SATISFIABLE) {
159 val value = switch (resultExpr : handle.upper) {
160 IntNum:
161 resultExpr.getInt()
162 RatNum:
163 floor(resultExpr)
164 AlgebraicNum:
165 floor(resultExpr.toLower(ALGEBRAIC_NUMBER_ROUNDING))
166 default:
167 if (isPositiveInfinity(resultExpr)) {
168 null
169 } else {
170 throw new IllegalArgumentException("Integer result expected, got: " + resultExpr)
171 }
172 }
173 expressionToSaturate.upperBound = value
174 }
175 status
176 }
177
178 private def ceil(RatNum ratNum) {
179 val numerator = new BigDecimal(ratNum.numerator.bigInteger)
180 val denominator = new BigDecimal(ratNum.denominator.bigInteger)
181 numerator.divide(denominator, ROUND_UP).setScale(0, RoundingMode.CEILING).intValue
182 }
183
184 private def isPositiveInfinity(Expr expr) {
185 expr.app && expr.getFuncDecl.name == infinitySymbol
186 }
187
188 private def isNegativeInfinity(Expr expr) {
189 // Negative infinity is represented as (* (- 1) oo)
190 if (!expr.app || expr.getFuncDecl.name != multSymbol || expr.numArgs != 2) {
191 return false
192 }
193 isPositiveInfinity(expr.args.get(1))
194 }
195
196 private def prepareOptimize() {
197 val optimize = mkOptimize()
198 if (timeoutMilliseconds >= 0) {
199 val params = mkParams()
200 // We cannot turn TIMEOUT_SYMBOL_NAME into a Symbol in the constructor,
201 // because there is no add(Symbol, int) overload.
202 params.add(TIMEOUT_SYMBOL_NAME, timeoutMilliseconds)
203 optimize.parameters = params
204 }
205 assertConstraints(optimize)
206 optimize
207 }
208
209 private def assertConstraints(Optimize it) {
210 for (pair : variables.entrySet) {
211 assertBounds(pair.value, pair.key)
212 }
213 for (constraint : nonTrivialConstraints) {
214 val expr = createLinearCombination(constraint.coefficients)
215 assertBounds(expr, constraint)
216 }
217 }
218
219 private def assertBounds(Optimize it, ArithExpr expression, LinearBoundedExpression bounds) {
220 val lowerBound = bounds.lowerBound
221 val upperBound = bounds.upperBound
222 if (lowerBound == upperBound) {
223 if (lowerBound === null) {
224 return
225 }
226 Assert(mkEq(expression, mkInt(lowerBound)))
227 } else {
228 if (lowerBound !== null) {
229 Assert(mkGe(expression, mkInt(lowerBound)))
230 }
231 if (upperBound !== null) {
232 Assert(mkLe(expression, mkInt(upperBound)))
233 }
234 }
235 }
236
237 private def toExpr(LinearBoundedExpression linearBoundedExpression) {
238 switch (linearBoundedExpression) {
239 Dimension: variables.get(linearBoundedExpression)
240 LinearConstraint: createLinearCombination(linearBoundedExpression.coefficients)
241 default: throw new IllegalArgumentException("Unknown linear bounded expression:" + linearBoundedExpression)
242 }
243 }
244
245 private def createLinearCombination(Map<Dimension, Integer> coefficients) {
246 val size = coefficients.size
247 if (size == 0) {
248 return mkInt(0)
249 }
250 val array = newArrayOfSize(size)
251 var int i = 0
252 for (pair : coefficients.entrySet) {
253 val variable = variables.get(pair.key)
254 if (variable === null) {
255 throw new IllegalArgumentException("Unknown dimension: " + pair.key.name)
256 }
257 val coefficient = pair.value
258 val term = if (coefficient == 1) {
259 variable
260 } else {
261 mkMul(mkInt(coefficient), variable)
262 }
263 array.set(i, term)
264 i++
265 }
266 mkAdd(array)
267 }
268
269 override close() throws Exception {
270 context.close()
271 }
272}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/Interval.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/Interval.xtend
new file mode 100644
index 00000000..691c8783
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/Interval.xtend
@@ -0,0 +1,584 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval
2
3import java.math.BigDecimal
4import java.math.MathContext
5import java.math.RoundingMode
6import org.eclipse.xtend.lib.annotations.Data
7
8abstract class Interval implements Comparable<Interval> {
9 static val PRECISION = 32
10 package static val ROUND_DOWN = new MathContext(PRECISION, RoundingMode.FLOOR)
11 package static val ROUND_UP = new MathContext(PRECISION, RoundingMode.CEILING)
12
13 private new() {
14 }
15
16 abstract def boolean mustEqual(Interval other)
17
18 abstract def boolean mayEqual(Interval other)
19
20 def mustNotEqual(Interval other) {
21 !mayEqual(other)
22 }
23
24 def mayNotEqual(Interval other) {
25 !mustEqual(other)
26 }
27
28 abstract def boolean mustBeLessThan(Interval other)
29
30 abstract def boolean mayBeLessThan(Interval other)
31
32 def mustBeLessThanOrEqual(Interval other) {
33 !mayBeGreaterThan(other)
34 }
35
36 def mayBeLessThanOrEqual(Interval other) {
37 !mustBeGreaterThan(other)
38 }
39
40 def mustBeGreaterThan(Interval other) {
41 other.mustBeLessThan(this)
42 }
43
44 def mayBeGreaterThan(Interval other) {
45 other.mayBeLessThan(this)
46 }
47
48 def mustBeGreaterThanOrEqual(Interval other) {
49 other.mustBeLessThanOrEqual(this)
50 }
51
52 def mayBeGreaterThanOrEqual(Interval other) {
53 other.mayBeLessThanOrEqual(this)
54 }
55
56 abstract def Interval min(Interval other)
57
58 abstract def Interval max(Interval other)
59
60 abstract def Interval join(Interval other)
61
62 def +() {
63 this
64 }
65
66 abstract def Interval -()
67
68 abstract def Interval +(Interval other)
69
70 abstract def Interval -(Interval other)
71
72 abstract def Interval *(int count)
73
74 abstract def Interval *(Interval other)
75
76 abstract def Interval /(Interval other)
77
78 abstract def Interval **(Interval other)
79
80 public static val EMPTY = new Interval {
81 override mustEqual(Interval other) {
82 true
83 }
84
85 override mayEqual(Interval other) {
86 false
87 }
88
89 override mustBeLessThan(Interval other) {
90 true
91 }
92
93 override mayBeLessThan(Interval other) {
94 false
95 }
96
97 override min(Interval other) {
98 EMPTY
99 }
100
101 override max(Interval other) {
102 EMPTY
103 }
104
105 override join(Interval other) {
106 other
107 }
108
109 override -() {
110 EMPTY
111 }
112
113 override +(Interval other) {
114 EMPTY
115 }
116
117 override -(Interval other) {
118 EMPTY
119 }
120
121 override *(int count) {
122 EMPTY
123 }
124
125 override *(Interval other) {
126 EMPTY
127 }
128
129 override /(Interval other) {
130 EMPTY
131 }
132
133 override **(Interval other) {
134 EMPTY
135 }
136
137 override toString() {
138 "∅"
139 }
140
141 override compareTo(Interval o) {
142 if (o == EMPTY) {
143 0
144 } else {
145 -1
146 }
147 }
148
149 }
150
151 public static val Interval ZERO = new NonEmpty(BigDecimal.ZERO, BigDecimal.ZERO)
152
153 public static val Interval UNBOUNDED = new NonEmpty(null, null)
154
155 static def Interval of(BigDecimal lower, BigDecimal upper) {
156 new NonEmpty(lower, upper)
157 }
158
159 static def between(double lower, double upper) {
160 of(new BigDecimal(lower, ROUND_DOWN), new BigDecimal(upper, ROUND_UP))
161 }
162
163 static def upTo(double upper) {
164 of(null, new BigDecimal(upper, ROUND_UP))
165 }
166
167 static def above(double lower) {
168 of(new BigDecimal(lower, ROUND_DOWN), null)
169 }
170
171 @Data
172 private static class NonEmpty extends Interval {
173 val BigDecimal lower
174 val BigDecimal upper
175
176 /**
177 * Construct a new non-empty interval.
178 *
179 * @param lower The lower bound of the interval. Use <code>null</code> for negative infinity.
180 * @param upper The upper bound of the interval. Use <code>null</code> for positive infinity.
181 */
182 new(BigDecimal lower, BigDecimal upper) {
183 if (lower !== null && upper !== null && lower > upper) {
184 throw new IllegalArgumentException("Lower bound of interval must not be larger than upper bound")
185 }
186 this.lower = lower
187 this.upper = upper
188 }
189
190 override mustEqual(Interval other) {
191 switch (other) {
192 case EMPTY: true
193 NonEmpty: lower == upper && lower == other.lower && lower == other.upper
194 default: throw new IllegalArgumentException("Unknown interval: " + other)
195 }
196 }
197
198 override mayEqual(Interval other) {
199 if (other instanceof NonEmpty) {
200 (lower === null || other.upper === null || lower <= other.upper) &&
201 (other.lower === null || upper === null || other.lower <= upper)
202 } else {
203 false
204 }
205 }
206
207 override mustBeLessThan(Interval other) {
208 switch (other) {
209 case EMPTY: true
210 NonEmpty: upper !== null && other.lower !== null && upper < other.lower
211 default: throw new IllegalArgumentException("Unknown interval: " + other)
212 }
213 }
214
215 override mayBeLessThan(Interval other) {
216 if (other instanceof NonEmpty) {
217 lower === null || other.upper === null || lower < other.upper
218 } else {
219 false
220 }
221 }
222
223 override min(Interval other) {
224 switch (other) {
225 case EMPTY: this
226 NonEmpty: min(other)
227 default: throw new IllegalArgumentException("Unknown interval: " + other)
228 }
229 }
230
231 def min(NonEmpty other) {
232 new NonEmpty(
233 lower.tryMin(other.lower),
234 if(other.upper === null) upper else if(upper === null) other.upper else upper.min(other.upper)
235 )
236 }
237
238 override max(Interval other) {
239 switch (other) {
240 case EMPTY: this
241 NonEmpty: max(other)
242 default: throw new IllegalArgumentException("Unknown interval: " + other)
243 }
244 }
245
246 def max(NonEmpty other) {
247 new NonEmpty(
248 if(other.lower === null) lower else if(lower === null) other.lower else lower.max(other.lower),
249 upper.tryMax(other.upper)
250 )
251 }
252
253 override join(Interval other) {
254 switch (other) {
255 case EMPTY: this
256 NonEmpty: new NonEmpty(lower.tryMin(other.lower), upper.tryMax(other.upper))
257 default: throw new IllegalArgumentException("Unknown interval: " + other)
258 }
259 }
260
261 override -() {
262 new NonEmpty(upper?.negate(ROUND_DOWN), lower?.negate(ROUND_UP))
263 }
264
265 override +(Interval other) {
266 switch (other) {
267 case EMPTY: EMPTY
268 NonEmpty: this + other
269 default: throw new IllegalArgumentException("Unknown interval: " + other)
270 }
271 }
272
273 def +(NonEmpty other) {
274 new NonEmpty(
275 lower.tryAdd(other.lower, ROUND_DOWN),
276 upper.tryAdd(other.upper, ROUND_UP)
277 )
278 }
279
280 private static def tryAdd(BigDecimal a, BigDecimal b, MathContext mc) {
281 if (b === null) {
282 null
283 } else {
284 a?.add(b, mc)
285 }
286 }
287
288 override -(Interval other) {
289 switch (other) {
290 case EMPTY: EMPTY
291 NonEmpty: this - other
292 default: throw new IllegalArgumentException("Unknown interval: " + other)
293 }
294 }
295
296 def -(NonEmpty other) {
297 new NonEmpty(
298 lower.trySubtract(other.upper, ROUND_DOWN),
299 upper.trySubtract(other.lower, ROUND_UP)
300 )
301 }
302
303 private static def trySubtract(BigDecimal a, BigDecimal b, MathContext mc) {
304 if (b === null) {
305 null
306 } else {
307 a?.subtract(b, mc)
308 }
309 }
310
311 override *(int count) {
312 val bigCount = new BigDecimal(count)
313 new NonEmpty(
314 lower.tryMultiply(bigCount, ROUND_DOWN),
315 upper.tryMultiply(bigCount, ROUND_UP)
316 )
317 }
318
319 override *(Interval other) {
320 switch (other) {
321 case EMPTY: EMPTY
322 NonEmpty: this * other
323 default: throw new IllegalArgumentException("Unknown interval: " + other)
324 }
325 }
326
327 def *(NonEmpty other) {
328 if (this == ZERO || other == ZERO) {
329 ZERO
330 } else if (nonpositive) {
331 if (other.nonpositive) {
332 new NonEmpty(
333 upper.multiply(other.upper, ROUND_DOWN),
334 lower.tryMultiply(other.lower, ROUND_UP)
335 )
336 } else if (other.nonnegative) {
337 new NonEmpty(
338 lower.tryMultiply(other.upper, ROUND_DOWN),
339 upper.multiply(other.lower, ROUND_UP)
340 )
341 } else {
342 new NonEmpty(
343 lower.tryMultiply(other.upper, ROUND_DOWN),
344 lower.tryMultiply(other.lower, ROUND_UP)
345 )
346 }
347 } else if (nonnegative) {
348 if (other.nonpositive) {
349 new NonEmpty(
350 upper.tryMultiply(other.lower, ROUND_DOWN),
351 lower.multiply(other.upper, ROUND_UP)
352 )
353 } else if (other.nonnegative) {
354 new NonEmpty(
355 lower.multiply(other.lower, ROUND_DOWN),
356 upper.tryMultiply(other.upper, ROUND_UP)
357 )
358 } else {
359 new NonEmpty(
360 upper.tryMultiply(other.lower, ROUND_DOWN),
361 upper.tryMultiply(other.upper, ROUND_UP)
362 )
363 }
364 } else {
365 if (other.nonpositive) {
366 new NonEmpty(
367 upper.tryMultiply(other.lower, ROUND_DOWN),
368 lower.tryMultiply(other.lower, ROUND_UP)
369 )
370 } else if (other.nonnegative) {
371 new NonEmpty(
372 lower.tryMultiply(other.upper, ROUND_DOWN),
373 upper.tryMultiply(other.upper, ROUND_UP)
374 )
375 } else {
376 new NonEmpty(
377 lower.tryMultiply(other.upper, ROUND_DOWN).tryMin(upper.tryMultiply(other.lower, ROUND_DOWN)),
378 lower.tryMultiply(other.lower, ROUND_UP).tryMax(upper.tryMultiply(other.upper, ROUND_UP))
379 )
380 }
381 }
382 }
383
384 private def isNonpositive() {
385 upper !== null && upper <= BigDecimal.ZERO
386 }
387
388 private def isNonnegative() {
389 lower !== null && lower >= BigDecimal.ZERO
390 }
391
392 private static def tryMultiply(BigDecimal a, BigDecimal b, MathContext mc) {
393 if (b === null) {
394 null
395 } else {
396 a?.multiply(b, mc)
397 }
398 }
399
400 private static def tryMin(BigDecimal a, BigDecimal b) {
401 if (b === null) {
402 null
403 } else {
404 a?.min(b)
405 }
406 }
407
408 private static def tryMax(BigDecimal a, BigDecimal b) {
409 if (b === null) {
410 null
411 } else {
412 a?.max(b)
413 }
414 }
415
416 override /(Interval other) {
417 switch (other) {
418 case EMPTY: EMPTY
419 NonEmpty: this / other
420 default: throw new IllegalArgumentException("Unknown interval: " + other)
421 }
422 }
423
424 def /(NonEmpty other) {
425 if (other == ZERO) {
426 EMPTY
427 } else if (this == ZERO) {
428 ZERO
429 } else if (other.strictlyNegative) {
430 if (nonpositive) {
431 new NonEmpty(
432 upper.tryDivide(other.lower, ROUND_DOWN),
433 lower.tryDivide(other.upper, ROUND_UP)
434 )
435 } else if (nonnegative) {
436 new NonEmpty(
437 upper.tryDivide(other.upper, ROUND_DOWN),
438 lower.tryDivide(other.lower, ROUND_UP)
439 )
440 } else { // lower < 0 < upper
441 new NonEmpty(
442 upper.tryDivide(other.upper, ROUND_DOWN),
443 lower.tryDivide(other.upper, ROUND_UP)
444 )
445 }
446 } else if (other.strictlyPositive) {
447 if (nonpositive) {
448 new NonEmpty(
449 lower.tryDivide(other.lower, ROUND_DOWN),
450 upper.tryDivide(other.upper, ROUND_UP)
451 )
452 } else if (nonnegative) {
453 new NonEmpty(
454 lower.tryDivide(other.upper, ROUND_DOWN),
455 upper.tryDivide(other.lower, ROUND_UP)
456 )
457 } else { // lower < 0 < upper
458 new NonEmpty(
459 lower.tryDivide(other.lower, ROUND_DOWN),
460 upper.tryDivide(other.lower, ROUND_UP)
461 )
462 }
463 } else { // other contains 0
464 if (other.lower == BigDecimal.ZERO) { // 0 == other.lower < other.upper, because [0, 0] was exluded earlier
465 if (nonpositive) {
466 new NonEmpty(null, upper.tryDivide(other.upper, ROUND_UP))
467 } else if (nonnegative) {
468 new NonEmpty(lower.tryDivide(other.upper, ROUND_DOWN), null)
469 } else { // lower < 0 < upper
470 UNBOUNDED
471 }
472 } else if (other.upper == BigDecimal.ZERO) { // other.lower < other.upper == 0
473 if (nonpositive) {
474 new NonEmpty(upper.tryDivide(other.lower, ROUND_DOWN), null)
475 } else if (nonnegative) {
476 new NonEmpty(null, lower.tryDivide(other.lower, ROUND_UP))
477 } else { // lower < 0 < upper
478 UNBOUNDED
479 }
480 } else { // other.lower < 0 < other.upper
481 UNBOUNDED
482 }
483 }
484 }
485
486 private def isStrictlyNegative() {
487 upper !== null && upper < BigDecimal.ZERO
488 }
489
490 private def isStrictlyPositive() {
491 lower !== null && lower > BigDecimal.ZERO
492 }
493
494 private static def tryDivide(BigDecimal a, BigDecimal b, MathContext mc) {
495 if (b === null) {
496 BigDecimal.ZERO
497 } else {
498 a?.divide(b, mc)
499 }
500 }
501
502 override **(Interval other) {
503 switch (other) {
504 case EMPTY: EMPTY
505 NonEmpty: this ** other
506 default: throw new IllegalArgumentException("Unknown interval: " + other)
507 }
508 }
509
510 def **(NonEmpty other) {
511 // XXX This should use proper rounding for log and exp instead of
512 // converting to double.
513 // XXX We should not ignore (integer) powers of negative numbers.
514 val lowerLog = if (lower === null || lower <= BigDecimal.ZERO) {
515 null
516 } else {
517 new BigDecimal(Math.log(lower.doubleValue), ROUND_DOWN)
518 }
519 val upperLog = if (upper === null) {
520 null
521 } else if (upper == BigDecimal.ZERO) {
522 return ZERO
523 } else if (upper < BigDecimal.ZERO) {
524 return EMPTY
525 } else {
526 new BigDecimal(Math.log(upper.doubleValue), ROUND_UP)
527 }
528 val log = new NonEmpty(lowerLog, upperLog)
529 val product = log * other
530 if (product instanceof NonEmpty) {
531 val lowerResult = if (product.lower === null) {
532 BigDecimal.ZERO
533 } else {
534 new BigDecimal(Math.exp(product.lower.doubleValue), ROUND_DOWN)
535 }
536 val upperResult = if (product.upper === null) {
537 null
538 } else {
539 new BigDecimal(Math.exp(product.upper.doubleValue), ROUND_UP)
540 }
541 new NonEmpty(lowerResult, upperResult)
542 } else {
543 throw new IllegalArgumentException("Unknown interval: " + product)
544 }
545 }
546
547 override toString() {
548 '''«IF lower === null»(-∞«ELSE»[«lower»«ENDIF», «IF upper === null»∞)«ELSE»«upper»]«ENDIF»'''
549 }
550
551 override compareTo(Interval o) {
552 switch (o) {
553 case EMPTY: 1
554 NonEmpty: compareTo(o)
555 default: throw new IllegalArgumentException("Unknown interval: " + o)
556 }
557 }
558
559 def compareTo(NonEmpty o) {
560 if (lower === null) {
561 if (o.lower !== null) {
562 return -1
563 }
564 } else if (o.lower === null) { // lower !== null
565 return 1
566 } else { // both lower and o.lower are finite
567 val lowerDifference = lower.compareTo(o.lower)
568 if (lowerDifference != 0) {
569 return lowerDifference
570 }
571 }
572 if (upper === null) {
573 if (o.upper === null) {
574 return 0
575 } else {
576 return 1
577 }
578 } else if (o.upper === null) { // upper !== null
579 return -1
580 }
581 upper.compareTo(o.upper)
582 }
583 }
584}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/IntervalAggregationMode.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/IntervalAggregationMode.java
new file mode 100644
index 00000000..f106e305
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/IntervalAggregationMode.java
@@ -0,0 +1,99 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval;
2
3import java.util.function.BinaryOperator;
4
5public enum IntervalAggregationMode implements BinaryOperator<Interval> {
6 SUM("intervalSum", "Sum a set of intervals") {
7 @Override
8 public IntervalRedBlackNode createNode(Interval interval) {
9 return new IntervalRedBlackNode(interval) {
10 public boolean isMultiplicitySensitive() {
11 return true;
12 }
13
14 public Interval multiply(Interval interval, int count) {
15 return interval.operator_multiply(count);
16 };
17
18 @Override
19 public Interval op(Interval left, Interval right) {
20 return left.operator_plus(right);
21 }
22 };
23 }
24
25 @Override
26 public Interval getNeutral() {
27 return Interval.ZERO;
28 }
29 },
30
31 MIN("intervalMin", "Find the minimum a set of intervals") {
32 @Override
33 public IntervalRedBlackNode createNode(Interval interval) {
34 return new IntervalRedBlackNode(interval) {
35 @Override
36 public Interval op(Interval left, Interval right) {
37 return left.min(right);
38 }
39 };
40 }
41 },
42
43 MAX("intervalMax", "Find the maximum a set of intervals") {
44 @Override
45 public IntervalRedBlackNode createNode(Interval interval) {
46 return new IntervalRedBlackNode(interval) {
47 @Override
48 public Interval op(Interval left, Interval right) {
49 return left.max(right);
50 }
51 };
52 }
53 },
54
55 JOIN("intervalJoin", "Calculate the smallest interval containing all the intervals in a set") {
56 @Override
57 public IntervalRedBlackNode createNode(Interval interval) {
58 return new IntervalRedBlackNode(interval) {
59 @Override
60 public Interval op(Interval left, Interval right) {
61 return left.join(right);
62 }
63 };
64 }
65 };
66
67 private final String modeName;
68 private final String description;
69 private final IntervalRedBlackNode empty;
70
71 IntervalAggregationMode(String modeName, String description) {
72 this.modeName = modeName;
73 this.description = description;
74 empty = createNode(null);
75 }
76
77 public String getModeName() {
78 return modeName;
79 }
80
81 public String getDescription() {
82 return description;
83 }
84
85 public IntervalRedBlackNode getEmpty() {
86 return empty;
87 }
88
89 @Override
90 public Interval apply(Interval left, Interval right) {
91 return empty.op(left, right);
92 }
93
94 public abstract IntervalRedBlackNode createNode(Interval interval);
95
96 public Interval getNeutral() {
97 return Interval.EMPTY;
98 }
99}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/IntervalAggregationOperator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/IntervalAggregationOperator.xtend
new file mode 100644
index 00000000..21d3d73b
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/IntervalAggregationOperator.xtend
@@ -0,0 +1,48 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval
2
3import java.util.stream.Stream
4import org.eclipse.viatra.query.runtime.matchers.psystem.aggregations.IMultisetAggregationOperator
5import org.eclipse.xtend.lib.annotations.Accessors
6import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor
7
8@FinalFieldsConstructor
9class IntervalAggregationOperator implements IMultisetAggregationOperator<Interval, IntervalRedBlackNode, Interval> {
10 @Accessors val IntervalAggregationMode mode
11
12 override getName() {
13 mode.modeName
14 }
15
16 override getShortDescription() {
17 mode.description
18 }
19
20 override createNeutral() {
21 mode.empty
22 }
23
24 override isNeutral(IntervalRedBlackNode result) {
25 result.leaf
26 }
27
28 override update(IntervalRedBlackNode oldResult, Interval updateValue, boolean isInsertion) {
29 if (isInsertion) {
30 val newNode = mode.createNode(updateValue)
31 oldResult.add(newNode)
32 } else {
33 oldResult.remove(updateValue)
34 }
35 }
36
37 override getAggregate(IntervalRedBlackNode result) {
38 if (result.leaf) {
39 mode.neutral
40 } else {
41 result.result
42 }
43 }
44
45 override aggregateStream(Stream<Interval> stream) {
46 stream.reduce(mode).orElse(mode.neutral)
47 }
48}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/IntervalHullAggregatorOperator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/IntervalHullAggregatorOperator.xtend
new file mode 100644
index 00000000..ce48eca1
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/IntervalHullAggregatorOperator.xtend
@@ -0,0 +1,87 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval
2
3import java.math.BigDecimal
4import java.math.MathContext
5import java.util.SortedMap
6import java.util.TreeMap
7import java.util.stream.Stream
8import org.eclipse.viatra.query.runtime.matchers.psystem.aggregations.IMultisetAggregationOperator
9
10abstract class IntervalHullAggregatorOperator<T extends Comparable<T>> implements IMultisetAggregationOperator<T, SortedMap<T, Integer>, Interval> {
11 protected new() {
12 }
13
14 override getName() {
15 "intervalHull"
16 }
17
18 override getShortDescription() {
19 "Calculates the interval hull of a set of numbers"
20 }
21
22 override createNeutral() {
23 new TreeMap
24 }
25
26 override getAggregate(SortedMap<T, Integer> result) {
27 if (result.neutral) {
28 Interval.EMPTY
29 } else {
30 toInterval(result.firstKey, result.lastKey)
31 }
32 }
33
34 protected abstract def BigDecimal toBigDecimal(T value, MathContext mc)
35
36 private def toInterval(T min, T max) {
37 Interval.of(min.toBigDecimal(Interval.ROUND_DOWN), max.toBigDecimal(Interval.ROUND_UP))
38 }
39
40 override isNeutral(SortedMap<T, Integer> result) {
41 result.empty
42 }
43
44 override update(SortedMap<T, Integer> oldResult, T updateValue, boolean isInsertion) {
45 if (isInsertion) {
46 oldResult.compute(updateValue) [ key, value |
47 if (value === null) {
48 1
49 } else if (value > 0) {
50 value + 1
51 } else {
52 throw new IllegalStateException("Invalid count: " + value)
53 }
54 ]
55 } else {
56 oldResult.compute(updateValue) [ key, value |
57 if (value === 1) {
58 null
59 } else if (value > 1) {
60 value - 1
61 } else {
62 throw new IllegalStateException("Invalid count: " + value)
63 }
64 ]
65 }
66 oldResult
67 }
68
69 override aggregateStream(Stream<T> stream) {
70 val iterator = stream.iterator
71 if (!iterator.hasNext) {
72 return Interval.EMPTY
73 }
74 var min = iterator.next
75 var max = min
76 while (iterator.hasNext) {
77 val element = iterator.next
78 if (element.compareTo(min) < 0) {
79 min = element
80 }
81 if (element.compareTo(max) > 0) {
82 max = element
83 }
84 }
85 toInterval(min, max)
86 }
87}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/IntervalRedBlackNode.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/IntervalRedBlackNode.xtend
new file mode 100644
index 00000000..3aa575bc
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/IntervalRedBlackNode.xtend
@@ -0,0 +1,177 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval
2
3abstract class IntervalRedBlackNode extends RedBlackNode<IntervalRedBlackNode> {
4 public val Interval interval
5 public var int count = 1
6 public var Interval result
7
8 new(Interval interval) {
9 this.interval = interval
10 }
11
12 def boolean isMultiplicitySensitive() {
13 false
14 }
15
16 def Interval multiply(Interval interval, int count) {
17 interval
18 }
19
20 abstract def Interval op(Interval left, Interval right)
21
22 override augment() {
23 val value = calcualteAugmentation()
24 if (result == value) {
25 false
26 } else {
27 result = value
28 true
29 }
30 }
31
32 private def calcualteAugmentation() {
33 var value = multiply(interval, count)
34 if (!left.leaf) {
35 value = op(value, left.result)
36 }
37 if (!right.leaf) {
38 value = op(value, right.result)
39 }
40 value
41 }
42
43 override assertNodeIsValid() {
44 super.assertNodeIsValid()
45 if (leaf) {
46 return
47 }
48 if (count <= 0) {
49 throw new IllegalStateException("Node with nonpositive count")
50 }
51 val value = calcualteAugmentation()
52 if (result != value) {
53 throw new IllegalStateException("Node with invalid augmentation: " + result + " != " + value)
54 }
55 }
56
57 override assertSubtreeIsValid() {
58 super.assertSubtreeIsValid()
59 assertNodeIsValid()
60 }
61
62 override compareTo(IntervalRedBlackNode other) {
63 if (leaf || other.leaf) {
64 throw new IllegalArgumentException("One of the nodes is a leaf node")
65 }
66 interval.compareTo(other.interval)
67 }
68
69 def add(IntervalRedBlackNode newNode) {
70 if (parent !== null) {
71 throw new IllegalArgumentException("This is not the root of a tree")
72 }
73 if (leaf) {
74 newNode.isRed = false
75 newNode.left = this
76 newNode.right = this
77 newNode.parent = null
78 newNode.augment
79 return newNode
80 }
81 val modifiedNode = addWithoutFixup(newNode)
82 if (modifiedNode === newNode) {
83 // Must augment here, because fixInsertion() might call augment()
84 // on a node repeatedly, which might lose the change notification the
85 // second time it is called, and the augmentation will fail to
86 // reach the root.
87 modifiedNode.augmentRecursively
88 modifiedNode.isRed = true
89 return modifiedNode.fixInsertion
90 }
91 if (multiplicitySensitive) {
92 modifiedNode.augmentRecursively
93 }
94 this
95 }
96
97 private def addWithoutFixup(IntervalRedBlackNode newNode) {
98 var node = this
99 while (!node.leaf) {
100 val comparison = node.interval.compareTo(newNode.interval)
101 if (comparison < 0) {
102 if (node.left.leaf) {
103 newNode.left = node.left
104 newNode.right = node.left
105 node.left = newNode
106 newNode.parent = node
107 return newNode
108 } else {
109 node = node.left
110 }
111 } else if (comparison > 0) {
112 if (node.right.leaf) {
113 newNode.left = node.right
114 newNode.right = node.right
115 node.right = newNode
116 newNode.parent = node
117 return newNode
118 } else {
119 node = node.right
120 }
121 } else { // comparison == 0
122 newNode.parent = null
123 node.count++
124 return node
125 }
126 }
127 throw new IllegalStateException("Reached leaf node while searching for insertion point")
128 }
129
130 private def augmentRecursively() {
131 for (var node = this; node !== null; node = node.parent) {
132 if (!node.augment) {
133 return
134 }
135 }
136 }
137
138 def remove(Interval interval) {
139 val node = find(interval)
140 node.count--
141 if (node.count == 0) {
142 return node.remove
143 }
144 if (multiplicitySensitive) {
145 node.augmentRecursively
146 }
147 this
148 }
149
150 private def find(Interval interval) {
151 var node = this
152 while (!node.leaf) {
153 val comparison = node.interval.compareTo(interval)
154 if (comparison < 0) {
155 node = node.left
156 } else if (comparison > 0) {
157 node = node.right
158 } else { // comparison == 0
159 return node
160 }
161 }
162 throw new IllegalStateException("Reached leaf node while searching for interval to remove")
163 }
164
165 override toString() {
166 if (leaf) {
167 "L"
168 } else {
169 '''
170 «IF isRed»R«ELSE»B«ENDIF» «count»«interval» : «result»
171 «left»
172 «right»
173 '''
174 }
175 }
176
177}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/RedBlackNode.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/RedBlackNode.java
new file mode 100644
index 00000000..8c40816b
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/RedBlackNode.java
@@ -0,0 +1,1392 @@
1/*
2 * The MIT License (MIT)
3 *
4 * Copyright (c) 2016 btrekkie
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval;
25
26import java.lang.reflect.Array;
27import java.util.Collection;
28import java.util.Comparator;
29import java.util.HashSet;
30import java.util.Iterator;
31import java.util.Set;
32
33/**
34 * A node in a red-black tree ( https://en.wikipedia.org/wiki/Red%E2%80%93black_tree ). Compared to a class like Java's
35 * TreeMap, RedBlackNode is a low-level data structure. The internals of a node are exposed as public fields, allowing
36 * clients to directly observe and manipulate the structure of the tree. This gives clients flexibility, although it
37 * also enables them to violate the red-black or BST properties. The RedBlackNode class provides methods for performing
38 * various standard operations, such as insertion and removal.
39 *
40 * Unlike most implementations of binary search trees, RedBlackNode supports arbitrary augmentation. By subclassing
41 * RedBlackNode, clients can add arbitrary data and augmentation information to each node. For example, if we were to
42 * use a RedBlackNode subclass to implement a sorted set, the subclass would have a field storing an element in the set.
43 * If we wanted to keep track of the number of non-leaf nodes in each subtree, we would store this as a "size" field and
44 * override augment() to update this field. All RedBlackNode methods (such as "insert" and remove()) call augment() as
45 * necessary to correctly maintain the augmentation information, unless otherwise indicated.
46 *
47 * The values of the tree are stored in the non-leaf nodes. RedBlackNode does not support use cases where values must be
48 * stored in the leaf nodes. It is recommended that all of the leaf nodes in a given tree be the same (black)
49 * RedBlackNode instance, to save space. The root of an empty tree is a leaf node, as opposed to null.
50 *
51 * For reference, a red-black tree is a binary search tree satisfying the following properties:
52 *
53 * - Every node is colored red or black.
54 * - The leaf nodes, which are dummy nodes that do not store any values, are colored black.
55 * - The root is black.
56 * - Both children of each red node are black.
57 * - Every path from the root to a leaf contains the same number of black nodes.
58 *
59 * @param <N> The type of node in the tree. For example, we might have
60 * "class FooNode<T> extends RedBlackNode<FooNode<T>>".
61 * @author Bill Jacobs
62 */
63public abstract class RedBlackNode<N extends RedBlackNode<N>> implements Comparable<N> {
64 /** A Comparator that compares Comparable elements using their natural order. */
65 private static final Comparator<Comparable<Object>> NATURAL_ORDER = new Comparator<Comparable<Object>>() {
66 @Override
67 public int compare(Comparable<Object> value1, Comparable<Object> value2) {
68 return value1.compareTo(value2);
69 }
70 };
71
72 /** The parent of this node, if any. "parent" is null if this is a leaf node. */
73 public N parent;
74
75 /** The left child of this node. "left" is null if this is a leaf node. */
76 public N left;
77
78 /** The right child of this node. "right" is null if this is a leaf node. */
79 public N right;
80
81 /** Whether the node is colored red, as opposed to black. */
82 public boolean isRed;
83
84 /**
85 * Sets any augmentation information about the subtree rooted at this node that is stored in this node. For
86 * example, if we augment each node by subtree size (the number of non-leaf nodes in the subtree), this method would
87 * set the size field of this node to be equal to the size field of the left child plus the size field of the right
88 * child plus one.
89 *
90 * "Augmentation information" is information that we can compute about a subtree rooted at some node, preferably
91 * based only on the augmentation information in the node's two children and the information in the node. Examples
92 * of augmentation information are the sum of the values in a subtree and the number of non-leaf nodes in a subtree.
93 * Augmentation information may not depend on the colors of the nodes.
94 *
95 * This method returns whether the augmentation information in any of the ancestors of this node might have been
96 * affected by changes in this subtree since the last call to augment(). In the usual case, where the augmentation
97 * information depends only on the information in this node and the augmentation information in its immediate
98 * children, this is equivalent to whether the augmentation information changed as a result of this call to
99 * augment(). For example, in the case of subtree size, this returns whether the value of the size field prior to
100 * calling augment() differed from the size field of the left child plus the size field of the right child plus one.
101 * False positives are permitted. The return value is unspecified if we have not called augment() on this node
102 * before.
103 *
104 * This method may assume that this is not a leaf node. It may not assume that the augmentation information stored
105 * in any of the tree's nodes is correct. However, if the augmentation information stored in all of the node's
106 * descendants is correct, then the augmentation information stored in this node must be correct after calling
107 * augment().
108 */
109 public boolean augment() {
110 return false;
111 }
112
113 /**
114 * Throws a RuntimeException if we detect that this node locally violates any invariants specific to this subclass
115 * of RedBlackNode. For example, if this stores the size of the subtree rooted at this node, this should throw a
116 * RuntimeException if the size field of this is not equal to the size field of the left child plus the size field
117 * of the right child plus one. Note that we may call this on a leaf node.
118 *
119 * assertSubtreeIsValid() calls assertNodeIsValid() on each node, or at least starts to do so until it detects a
120 * problem. assertNodeIsValid() should assume the node is in a tree that satisfies all properties common to all
121 * red-black trees, as assertSubtreeIsValid() is responsible for such checks. assertNodeIsValid() should be
122 * "downward-looking", i.e. it should ignore any information in "parent", and it should be "local", i.e. it should
123 * only check a constant number of descendants. To include "global" checks, such as verifying the BST property
124 * concerning ordering, override assertSubtreeIsValid(). assertOrderIsValid is useful for checking the BST
125 * property.
126 */
127 public void assertNodeIsValid() {
128
129 }
130
131 /** Returns whether this is a leaf node. */
132 public boolean isLeaf() {
133 return left == null;
134 }
135
136 /** Returns the root of the tree that contains this node. */
137 public N root() {
138 @SuppressWarnings("unchecked")
139 N node = (N)this;
140 while (node.parent != null) {
141 node = node.parent;
142 }
143 return node;
144 }
145
146 /** Returns the first node in the subtree rooted at this node, if any. */
147 public N min() {
148 if (isLeaf()) {
149 return null;
150 }
151 @SuppressWarnings("unchecked")
152 N node = (N)this;
153 while (!node.left.isLeaf()) {
154 node = node.left;
155 }
156 return node;
157 }
158
159 /** Returns the last node in the subtree rooted at this node, if any. */
160 public N max() {
161 if (isLeaf()) {
162 return null;
163 }
164 @SuppressWarnings("unchecked")
165 N node = (N)this;
166 while (!node.right.isLeaf()) {
167 node = node.right;
168 }
169 return node;
170 }
171
172 /** Returns the node immediately before this in the tree that contains this node, if any. */
173 public N predecessor() {
174 if (!left.isLeaf()) {
175 N node;
176 for (node = left; !node.right.isLeaf(); node = node.right);
177 return node;
178 } else if (parent == null) {
179 return null;
180 } else {
181 @SuppressWarnings("unchecked")
182 N node = (N)this;
183 while (node.parent != null && node.parent.left == node) {
184 node = node.parent;
185 }
186 return node.parent;
187 }
188 }
189
190 /** Returns the node immediately after this in the tree that contains this node, if any. */
191 public N successor() {
192 if (!right.isLeaf()) {
193 N node;
194 for (node = right; !node.left.isLeaf(); node = node.left);
195 return node;
196 } else if (parent == null) {
197 return null;
198 } else {
199 @SuppressWarnings("unchecked")
200 N node = (N)this;
201 while (node.parent != null && node.parent.right == node) {
202 node = node.parent;
203 }
204 return node.parent;
205 }
206 }
207
208 /**
209 * Performs a left rotation about this node. This method assumes that !isLeaf() && !right.isLeaf(). It calls
210 * augment() on this node and on its resulting parent. However, it does not call augment() on any of the resulting
211 * parent's ancestors, because that is normally the responsibility of the caller.
212 * @return The return value from calling augment() on the resulting parent.
213 */
214 public boolean rotateLeft() {
215 if (isLeaf() || right.isLeaf()) {
216 throw new IllegalArgumentException("The node or its right child is a leaf");
217 }
218 N newParent = right;
219 right = newParent.left;
220 @SuppressWarnings("unchecked")
221 N nThis = (N)this;
222 if (!right.isLeaf()) {
223 right.parent = nThis;
224 }
225 newParent.parent = parent;
226 parent = newParent;
227 newParent.left = nThis;
228 if (newParent.parent != null) {
229 if (newParent.parent.left == this) {
230 newParent.parent.left = newParent;
231 } else {
232 newParent.parent.right = newParent;
233 }
234 }
235 augment();
236 return newParent.augment();
237 }
238
239 /**
240 * Performs a right rotation about this node. This method assumes that !isLeaf() && !left.isLeaf(). It calls
241 * augment() on this node and on its resulting parent. However, it does not call augment() on any of the resulting
242 * parent's ancestors, because that is normally the responsibility of the caller.
243 * @return The return value from calling augment() on the resulting parent.
244 */
245 public boolean rotateRight() {
246 if (isLeaf() || left.isLeaf()) {
247 throw new IllegalArgumentException("The node or its left child is a leaf");
248 }
249 N newParent = left;
250 left = newParent.right;
251 @SuppressWarnings("unchecked")
252 N nThis = (N)this;
253 if (!left.isLeaf()) {
254 left.parent = nThis;
255 }
256 newParent.parent = parent;
257 parent = newParent;
258 newParent.right = nThis;
259 if (newParent.parent != null) {
260 if (newParent.parent.left == this) {
261 newParent.parent.left = newParent;
262 } else {
263 newParent.parent.right = newParent;
264 }
265 }
266 augment();
267 return newParent.augment();
268 }
269
270 /**
271 * Performs red-black insertion fixup. To be more precise, this fixes a tree that satisfies all of the requirements
272 * of red-black trees, except that this may be a red child of a red node, and if this is the root, the root may be
273 * red. node.isRed must initially be true. This method assumes that this is not a leaf node. The method performs
274 * any rotations by calling rotateLeft() and rotateRight(). This method is more efficient than fixInsertion if
275 * "augment" is false or augment() might return false.
276 * @param augment Whether to set the augmentation information for "node" and its ancestors, by calling augment().
277 */
278 public void fixInsertionWithoutGettingRoot(boolean augment) {
279 if (!isRed) {
280 throw new IllegalArgumentException("The node must be red");
281 }
282 boolean changed = augment;
283 if (augment) {
284 augment();
285 }
286
287 RedBlackNode<N> node = this;
288 while (node.parent != null && node.parent.isRed) {
289 N parent = node.parent;
290 N grandparent = parent.parent;
291 if (grandparent.left.isRed && grandparent.right.isRed) {
292 grandparent.left.isRed = false;
293 grandparent.right.isRed = false;
294 grandparent.isRed = true;
295
296 if (changed) {
297 changed = parent.augment();
298 if (changed) {
299 changed = grandparent.augment();
300 }
301 }
302 node = grandparent;
303 } else {
304 if (parent.left == node) {
305 if (grandparent.right == parent) {
306 parent.rotateRight();
307 node = parent;
308 parent = node.parent;
309 }
310 } else if (grandparent.left == parent) {
311 parent.rotateLeft();
312 node = parent;
313 parent = node.parent;
314 }
315
316 if (parent.left == node) {
317 boolean grandparentChanged = grandparent.rotateRight();
318 if (augment) {
319 changed = grandparentChanged;
320 }
321 } else {
322 boolean grandparentChanged = grandparent.rotateLeft();
323 if (augment) {
324 changed = grandparentChanged;
325 }
326 }
327
328 parent.isRed = false;
329 grandparent.isRed = true;
330 node = parent;
331 break;
332 }
333 }
334
335 if (node.parent == null) {
336 node.isRed = false;
337 }
338 if (changed) {
339 for (node = node.parent; node != null; node = node.parent) {
340 if (!node.augment()) {
341 break;
342 }
343 }
344 }
345 }
346
347 /**
348 * Performs red-black insertion fixup. To be more precise, this fixes a tree that satisfies all of the requirements
349 * of red-black trees, except that this may be a red child of a red node, and if this is the root, the root may be
350 * red. node.isRed must initially be true. This method assumes that this is not a leaf node. The method performs
351 * any rotations by calling rotateLeft() and rotateRight(). This method is more efficient than fixInsertion() if
352 * augment() might return false.
353 */
354 public void fixInsertionWithoutGettingRoot() {
355 fixInsertionWithoutGettingRoot(true);
356 }
357
358 /**
359 * Performs red-black insertion fixup. To be more precise, this fixes a tree that satisfies all of the requirements
360 * of red-black trees, except that this may be a red child of a red node, and if this is the root, the root may be
361 * red. node.isRed must initially be true. This method assumes that this is not a leaf node. The method performs
362 * any rotations by calling rotateLeft() and rotateRight().
363 * @param augment Whether to set the augmentation information for "node" and its ancestors, by calling augment().
364 * @return The root of the resulting tree.
365 */
366 public N fixInsertion(boolean augment) {
367 fixInsertionWithoutGettingRoot(augment);
368 return root();
369 }
370
371 /**
372 * Performs red-black insertion fixup. To be more precise, this fixes a tree that satisfies all of the requirements
373 * of red-black trees, except that this may be a red child of a red node, and if this is the root, the root may be
374 * red. node.isRed must initially be true. This method assumes that this is not a leaf node. The method performs
375 * any rotations by calling rotateLeft() and rotateRight().
376 * @return The root of the resulting tree.
377 */
378 public N fixInsertion() {
379 fixInsertionWithoutGettingRoot(true);
380 return root();
381 }
382
383 /** Returns a Comparator that compares instances of N using their natural order, as in N.compareTo. */
384 @SuppressWarnings({"rawtypes", "unchecked"})
385 private Comparator<N> naturalOrder() {
386 Comparator comparator = (Comparator)NATURAL_ORDER;
387 return (Comparator<N>)comparator;
388 }
389
390 /**
391 * Inserts the specified node into the tree rooted at this node. Assumes this is the root. We treat newNode as a
392 * solitary node that does not belong to any tree, and we ignore its initial "parent", "left", "right", and isRed
393 * fields.
394 *
395 * If it is not efficient or convenient to find the location for a node using a Comparator, then you should manually
396 * add the node to the appropriate location, color it red, and call fixInsertion().
397 *
398 * @param newNode The node to insert.
399 * @param allowDuplicates Whether to insert newNode if there is an equal node in the tree. To check whether we
400 * inserted newNode, check whether newNode.parent is null and the return value differs from newNode.
401 * @param comparator A comparator indicating where to put the node. If this is null, we use the nodes' natural
402 * order, as in N.compareTo. If you are passing null, then you must override the compareTo method, because the
403 * default implementation requires the nodes to already be in the same tree.
404 * @return The root of the resulting tree.
405 */
406 public N insert(N newNode, boolean allowDuplicates, Comparator<? super N> comparator) {
407 if (parent != null) {
408 throw new IllegalArgumentException("This is not the root of a tree");
409 }
410 @SuppressWarnings("unchecked")
411 N nThis = (N)this;
412 if (isLeaf()) {
413 newNode.isRed = false;
414 newNode.left = nThis;
415 newNode.right = nThis;
416 newNode.parent = null;
417 newNode.augment();
418 return newNode;
419 }
420 if (comparator == null) {
421 comparator = naturalOrder();
422 }
423
424 N node = nThis;
425 int comparison;
426 while (true) {
427 comparison = comparator.compare(newNode, node);
428 if (comparison < 0) {
429 if (!node.left.isLeaf()) {
430 node = node.left;
431 } else {
432 newNode.left = node.left;
433 newNode.right = node.left;
434 node.left = newNode;
435 newNode.parent = node;
436 break;
437 }
438 } else if (comparison > 0 || allowDuplicates) {
439 if (!node.right.isLeaf()) {
440 node = node.right;
441 } else {
442 newNode.left = node.right;
443 newNode.right = node.right;
444 node.right = newNode;
445 newNode.parent = node;
446 break;
447 }
448 } else {
449 newNode.parent = null;
450 return nThis;
451 }
452 }
453 newNode.isRed = true;
454 return newNode.fixInsertion();
455 }
456
457 /**
458 * Moves this node to its successor's former position in the tree and vice versa, i.e. sets the "left", "right",
459 * "parent", and isRed fields of each. This method assumes that this is not a leaf node.
460 * @return The node with which we swapped.
461 */
462 private N swapWithSuccessor() {
463 N replacement = successor();
464 boolean oldReplacementIsRed = replacement.isRed;
465 N oldReplacementLeft = replacement.left;
466 N oldReplacementRight = replacement.right;
467 N oldReplacementParent = replacement.parent;
468
469 replacement.isRed = isRed;
470 replacement.left = left;
471 replacement.right = right;
472 replacement.parent = parent;
473 if (parent != null) {
474 if (parent.left == this) {
475 parent.left = replacement;
476 } else {
477 parent.right = replacement;
478 }
479 }
480
481 @SuppressWarnings("unchecked")
482 N nThis = (N)this;
483 isRed = oldReplacementIsRed;
484 left = oldReplacementLeft;
485 right = oldReplacementRight;
486 if (oldReplacementParent == this) {
487 parent = replacement;
488 parent.right = nThis;
489 } else {
490 parent = oldReplacementParent;
491 parent.left = nThis;
492 }
493
494 replacement.right.parent = replacement;
495 if (!replacement.left.isLeaf()) {
496 replacement.left.parent = replacement;
497 }
498 if (!right.isLeaf()) {
499 right.parent = nThis;
500 }
501 return replacement;
502 }
503
504 /**
505 * Performs red-black deletion fixup. To be more precise, this fixes a tree that satisfies all of the requirements
506 * of red-black trees, except that all paths from the root to a leaf that pass through the sibling of this node have
507 * one fewer black node than all other root-to-leaf paths. This method assumes that this is not a leaf node.
508 */
509 private void fixSiblingDeletion() {
510 RedBlackNode<N> sibling = this;
511 boolean changed = true;
512 boolean haveAugmentedParent = false;
513 boolean haveAugmentedGrandparent = false;
514 while (true) {
515 N parent = sibling.parent;
516 if (sibling.isRed) {
517 parent.isRed = true;
518 sibling.isRed = false;
519 if (parent.left == sibling) {
520 changed = parent.rotateRight();
521 sibling = parent.left;
522 } else {
523 changed = parent.rotateLeft();
524 sibling = parent.right;
525 }
526 haveAugmentedParent = true;
527 haveAugmentedGrandparent = true;
528 } else if (!sibling.left.isRed && !sibling.right.isRed) {
529 sibling.isRed = true;
530 if (parent.isRed) {
531 parent.isRed = false;
532 break;
533 } else {
534 if (changed && !haveAugmentedParent) {
535 changed = parent.augment();
536 }
537 N grandparent = parent.parent;
538 if (grandparent == null) {
539 break;
540 } else if (grandparent.left == parent) {
541 sibling = grandparent.right;
542 } else {
543 sibling = grandparent.left;
544 }
545 haveAugmentedParent = haveAugmentedGrandparent;
546 haveAugmentedGrandparent = false;
547 }
548 } else {
549 if (sibling == parent.left) {
550 if (!sibling.left.isRed) {
551 sibling.rotateLeft();
552 sibling = sibling.parent;
553 }
554 } else if (!sibling.right.isRed) {
555 sibling.rotateRight();
556 sibling = sibling.parent;
557 }
558 sibling.isRed = parent.isRed;
559 parent.isRed = false;
560 if (sibling == parent.left) {
561 sibling.left.isRed = false;
562 changed = parent.rotateRight();
563 } else {
564 sibling.right.isRed = false;
565 changed = parent.rotateLeft();
566 }
567 haveAugmentedParent = haveAugmentedGrandparent;
568 haveAugmentedGrandparent = false;
569 break;
570 }
571 }
572
573 // Update augmentation info
574 N parent = sibling.parent;
575 if (changed && parent != null) {
576 if (!haveAugmentedParent) {
577 changed = parent.augment();
578 }
579 if (changed && parent.parent != null) {
580 parent = parent.parent;
581 if (!haveAugmentedGrandparent) {
582 changed = parent.augment();
583 }
584 if (changed) {
585 for (parent = parent.parent; parent != null; parent = parent.parent) {
586 if (!parent.augment()) {
587 break;
588 }
589 }
590 }
591 }
592 }
593 }
594
595 /**
596 * Removes this node from the tree that contains it. The effect of this method on the fields of this node is
597 * unspecified. This method assumes that this is not a leaf node. This method is more efficient than remove() if
598 * augment() might return false.
599 *
600 * If the node has two children, we begin by moving the node's successor to its former position, by changing the
601 * successor's "left", "right", "parent", and isRed fields.
602 */
603 public void removeWithoutGettingRoot() {
604 if (isLeaf()) {
605 throw new IllegalArgumentException("Attempted to remove a leaf node");
606 }
607 N replacement;
608 if (left.isLeaf() || right.isLeaf()) {
609 replacement = null;
610 } else {
611 replacement = swapWithSuccessor();
612 }
613
614 N child;
615 if (!left.isLeaf()) {
616 child = left;
617 } else if (!right.isLeaf()) {
618 child = right;
619 } else {
620 child = null;
621 }
622
623 if (child != null) {
624 // Replace this node with its child
625 child.parent = parent;
626 if (parent != null) {
627 if (parent.left == this) {
628 parent.left = child;
629 } else {
630 parent.right = child;
631 }
632 }
633 child.isRed = false;
634
635 if (child.parent != null) {
636 N parent;
637 for (parent = child.parent; parent != null; parent = parent.parent) {
638 if (!parent.augment()) {
639 break;
640 }
641 }
642 }
643 } else if (parent != null) {
644 // Replace this node with a leaf node
645 N leaf = left;
646 N parent = this.parent;
647 N sibling;
648 if (parent.left == this) {
649 parent.left = leaf;
650 sibling = parent.right;
651 } else {
652 parent.right = leaf;
653 sibling = parent.left;
654 }
655
656 if (!isRed) {
657 RedBlackNode<N> siblingNode = sibling;
658 siblingNode.fixSiblingDeletion();
659 } else {
660 while (parent != null) {
661 if (!parent.augment()) {
662 break;
663 }
664 parent = parent.parent;
665 }
666 }
667 }
668
669 if (replacement != null) {
670 replacement.augment();
671 for (N parent = replacement.parent; parent != null; parent = parent.parent) {
672 if (!parent.augment()) {
673 break;
674 }
675 }
676 }
677
678 // Clear any previously existing links, so that we're more likely to encounter an exception if we attempt to
679 // access the removed node
680 parent = null;
681 left = null;
682 right = null;
683 isRed = true;
684 }
685
686 /**
687 * Removes this node from the tree that contains it. The effect of this method on the fields of this node is
688 * unspecified. This method assumes that this is not a leaf node.
689 *
690 * If the node has two children, we begin by moving the node's successor to its former position, by changing the
691 * successor's "left", "right", "parent", and isRed fields.
692 *
693 * @return The root of the resulting tree.
694 */
695 public N remove() {
696 if (isLeaf()) {
697 throw new IllegalArgumentException("Attempted to remove a leaf node");
698 }
699
700 // Find an arbitrary non-leaf node in the tree other than this node
701 N node;
702 if (parent != null) {
703 node = parent;
704 } else if (!left.isLeaf()) {
705 node = left;
706 } else if (!right.isLeaf()) {
707 node = right;
708 } else {
709 return left;
710 }
711
712 removeWithoutGettingRoot();
713 return node.root();
714 }
715
716 /**
717 * Returns the root of a perfectly height-balanced subtree containing the next "size" (non-leaf) nodes from
718 * "iterator", in iteration order. This method is responsible for setting the "left", "right", "parent", and isRed
719 * fields of the nodes, and calling augment() as appropriate. It ignores the initial values of the "left", "right",
720 * "parent", and isRed fields.
721 * @param iterator The nodes.
722 * @param size The number of nodes.
723 * @param height The "height" of the subtree's root node above the deepest leaf in the tree that contains it. Since
724 * insertion fixup is slow if there are too many red nodes and deleteion fixup is slow if there are too few red
725 * nodes, we compromise and have red nodes at every fourth level. We color a node red iff its "height" is equal
726 * to 1 mod 4.
727 * @param leaf The leaf node.
728 * @return The root of the subtree.
729 */
730 private static <N extends RedBlackNode<N>> N createTree(
731 Iterator<? extends N> iterator, int size, int height, N leaf) {
732 if (size == 0) {
733 return leaf;
734 } else {
735 N left = createTree(iterator, (size - 1) / 2, height - 1, leaf);
736 N node = iterator.next();
737 N right = createTree(iterator, size / 2, height - 1, leaf);
738
739 node.isRed = height % 4 == 1;
740 node.left = left;
741 node.right = right;
742 if (!left.isLeaf()) {
743 left.parent = node;
744 }
745 if (!right.isLeaf()) {
746 right.parent = node;
747 }
748
749 node.augment();
750 return node;
751 }
752 }
753
754 /**
755 * Returns the root of a perfectly height-balanced tree containing the specified nodes, in iteration order. This
756 * method is responsible for setting the "left", "right", "parent", and isRed fields of the nodes (excluding
757 * "leaf"), and calling augment() as appropriate. It ignores the initial values of the "left", "right", "parent",
758 * and isRed fields.
759 * @param nodes The nodes.
760 * @param leaf The leaf node.
761 * @return The root of the tree.
762 */
763 public static <N extends RedBlackNode<N>> N createTree(Collection<? extends N> nodes, N leaf) {
764 int size = nodes.size();
765 if (size == 0) {
766 return leaf;
767 }
768
769 int height = 0;
770 for (int subtreeSize = size; subtreeSize > 0; subtreeSize /= 2) {
771 height++;
772 }
773
774 N node = createTree(nodes.iterator(), size, height, leaf);
775 node.parent = null;
776 node.isRed = false;
777 return node;
778 }
779
780 /**
781 * Concatenates to the end of the tree rooted at this node. To be precise, given that all of the nodes in this
782 * precede the node "pivot", which precedes all of the nodes in "last", this returns the root of a tree containing
783 * all of these nodes. This method destroys the trees rooted at "this" and "last". We treat "pivot" as a solitary
784 * node that does not belong to any tree, and we ignore its initial "parent", "left", "right", and isRed fields.
785 * This method assumes that this node and "last" are the roots of their respective trees.
786 *
787 * This method takes O(log N) time. It is more efficient than inserting "pivot" and then calling concatenate(last).
788 * It is considerably more efficient than inserting "pivot" and all of the nodes in "last".
789 */
790 public N concatenate(N last, N pivot) {
791 // If the black height of "first", where first = this, is less than or equal to that of "last", starting at the
792 // root of "last", we keep going left until we reach a black node whose black height is equal to that of
793 // "first". Then, we make "pivot" the parent of that node and of "first", coloring it red, and perform
794 // insertion fixup on the pivot. If the black height of "first" is greater than that of "last", we do the
795 // mirror image of the above.
796
797 if (parent != null) {
798 throw new IllegalArgumentException("This is not the root of a tree");
799 }
800 if (last.parent != null) {
801 throw new IllegalArgumentException("\"last\" is not the root of a tree");
802 }
803
804 // Compute the black height of the trees
805 int firstBlackHeight = 0;
806 @SuppressWarnings("unchecked")
807 N first = (N)this;
808 for (N node = first; node != null; node = node.right) {
809 if (!node.isRed) {
810 firstBlackHeight++;
811 }
812 }
813 int lastBlackHeight = 0;
814 for (N node = last; node != null; node = node.right) {
815 if (!node.isRed) {
816 lastBlackHeight++;
817 }
818 }
819
820 // Identify the children and parent of pivot
821 N firstChild = first;
822 N lastChild = last;
823 N parent;
824 if (firstBlackHeight <= lastBlackHeight) {
825 parent = null;
826 int blackHeight = lastBlackHeight;
827 while (blackHeight > firstBlackHeight) {
828 if (!lastChild.isRed) {
829 blackHeight--;
830 }
831 parent = lastChild;
832 lastChild = lastChild.left;
833 }
834 if (lastChild.isRed) {
835 parent = lastChild;
836 lastChild = lastChild.left;
837 }
838 } else {
839 parent = null;
840 int blackHeight = firstBlackHeight;
841 while (blackHeight > lastBlackHeight) {
842 if (!firstChild.isRed) {
843 blackHeight--;
844 }
845 parent = firstChild;
846 firstChild = firstChild.right;
847 }
848 if (firstChild.isRed) {
849 parent = firstChild;
850 firstChild = firstChild.right;
851 }
852 }
853
854 // Add "pivot" to the tree
855 pivot.isRed = true;
856 pivot.parent = parent;
857 if (parent != null) {
858 if (firstBlackHeight < lastBlackHeight) {
859 parent.left = pivot;
860 } else {
861 parent.right = pivot;
862 }
863 }
864 pivot.left = firstChild;
865 if (!firstChild.isLeaf()) {
866 firstChild.parent = pivot;
867 }
868 pivot.right = lastChild;
869 if (!lastChild.isLeaf()) {
870 lastChild.parent = pivot;
871 }
872
873 // Perform insertion fixup
874 return pivot.fixInsertion();
875 }
876
877 /**
878 * Concatenates the tree rooted at "last" to the end of the tree rooted at this node. To be precise, given that all
879 * of the nodes in this precede all of the nodes in "last", this returns the root of a tree containing all of these
880 * nodes. This method destroys the trees rooted at "this" and "last". It assumes that this node and "last" are the
881 * roots of their respective trees. This method takes O(log N) time. It is considerably more efficient than
882 * inserting all of the nodes in "last".
883 */
884 public N concatenate(N last) {
885 if (parent != null || last.parent != null) {
886 throw new IllegalArgumentException("The node is not the root of a tree");
887 }
888 if (isLeaf()) {
889 return last;
890 } else if (last.isLeaf()) {
891 @SuppressWarnings("unchecked")
892 N nThis = (N)this;
893 return nThis;
894 } else {
895 N node = last.min();
896 last = node.remove();
897 return concatenate(last, node);
898 }
899 }
900
901 /**
902 * Splits the tree rooted at this node into two trees, so that the first element of the return value is the root of
903 * a tree consisting of the nodes that were before the specified node, and the second element of the return value is
904 * the root of a tree consisting of the nodes that were equal to or after the specified node. This method is
905 * destructive, meaning it does not preserve the original tree. It assumes that this node is the root and is in the
906 * same tree as splitNode. It takes O(log N) time. It is considerably more efficient than removing all of the
907 * nodes at or after splitNode and then creating a new tree from those nodes.
908 * @param The node at which to split the tree.
909 * @return An array consisting of the resulting trees.
910 */
911 public N[] split(N splitNode) {
912 // To split the tree, we accumulate a pre-split tree and a post-split tree. We walk down the tree toward the
913 // position where we are splitting. Whenever we go left, we concatenate the right subtree with the post-split
914 // tree, and whenever we go right, we concatenate the pre-split tree with the left subtree. We use the
915 // concatenation algorithm described in concatenate(Object, Object). For the pivot, we use the last node where
916 // we went left in the case of a left move, and the last node where we went right in the case of a right move.
917 //
918 // The method uses the following variables:
919 //
920 // node: The current node in our walk down the tree.
921 // first: A node on the right spine of the pre-split tree. At the beginning of each iteration, it is the black
922 // node with the same black height as "node". If the pre-split tree is empty, this is null instead.
923 // firstParent: The parent of "first". If the pre-split tree is empty, this is null. Otherwise, this is the
924 // same as first.parent, unless first.isLeaf().
925 // firstPivot: The node where we last went right, i.e. the next node to use as a pivot when concatenating with
926 // the pre-split tree.
927 // advanceFirst: Whether to set "first" to be its next black descendant at the end of the loop.
928 // last, lastParent, lastPivot, advanceLast: Analogous to "first", firstParent, firstPivot, and advanceFirst,
929 // but for the post-split tree.
930 if (parent != null) {
931 throw new IllegalArgumentException("This is not the root of a tree");
932 }
933 if (isLeaf() || splitNode.isLeaf()) {
934 throw new IllegalArgumentException("The root or the split node is a leaf");
935 }
936
937 // Create an array containing the path from the root to splitNode
938 int depth = 1;
939 N parent;
940 for (parent = splitNode; parent.parent != null; parent = parent.parent) {
941 depth++;
942 }
943 if (parent != this) {
944 throw new IllegalArgumentException("The split node does not belong to this tree");
945 }
946 RedBlackNode<?>[] path = new RedBlackNode<?>[depth];
947 for (parent = splitNode; parent != null; parent = parent.parent) {
948 depth--;
949 path[depth] = parent;
950 }
951
952 @SuppressWarnings("unchecked")
953 N node = (N)this;
954 N first = null;
955 N firstParent = null;
956 N last = null;
957 N lastParent = null;
958 N firstPivot = null;
959 N lastPivot = null;
960 while (!node.isLeaf()) {
961 boolean advanceFirst = !node.isRed && firstPivot != null;
962 boolean advanceLast = !node.isRed && lastPivot != null;
963 if ((depth + 1 < path.length && path[depth + 1] == node.left) || depth + 1 == path.length) {
964 // Left move
965 if (lastPivot == null) {
966 // The post-split tree is empty
967 last = node.right;
968 last.parent = null;
969 if (last.isRed) {
970 last.isRed = false;
971 lastParent = last;
972 last = last.left;
973 }
974 } else {
975 // Concatenate node.right and the post-split tree
976 if (node.right.isRed) {
977 node.right.isRed = false;
978 } else if (!node.isRed) {
979 lastParent = last;
980 last = last.left;
981 if (last.isRed) {
982 lastParent = last;
983 last = last.left;
984 }
985 advanceLast = false;
986 }
987 lastPivot.isRed = true;
988 lastPivot.parent = lastParent;
989 if (lastParent != null) {
990 lastParent.left = lastPivot;
991 }
992 lastPivot.left = node.right;
993 if (!lastPivot.left.isLeaf()) {
994 lastPivot.left.parent = lastPivot;
995 }
996 lastPivot.right = last;
997 if (!last.isLeaf()) {
998 last.parent = lastPivot;
999 }
1000 last = lastPivot.left;
1001 lastParent = lastPivot;
1002 lastPivot.fixInsertionWithoutGettingRoot(false);
1003 }
1004 lastPivot = node;
1005 node = node.left;
1006 } else {
1007 // Right move
1008 if (firstPivot == null) {
1009 // The pre-split tree is empty
1010 first = node.left;
1011 first.parent = null;
1012 if (first.isRed) {
1013 first.isRed = false;
1014 firstParent = first;
1015 first = first.right;
1016 }
1017 } else {
1018 // Concatenate the post-split tree and node.left
1019 if (node.left.isRed) {
1020 node.left.isRed = false;
1021 } else if (!node.isRed) {
1022 firstParent = first;
1023 first = first.right;
1024 if (first.isRed) {
1025 firstParent = first;
1026 first = first.right;
1027 }
1028 advanceFirst = false;
1029 }
1030 firstPivot.isRed = true;
1031 firstPivot.parent = firstParent;
1032 if (firstParent != null) {
1033 firstParent.right = firstPivot;
1034 }
1035 firstPivot.right = node.left;
1036 if (!firstPivot.right.isLeaf()) {
1037 firstPivot.right.parent = firstPivot;
1038 }
1039 firstPivot.left = first;
1040 if (!first.isLeaf()) {
1041 first.parent = firstPivot;
1042 }
1043 first = firstPivot.right;
1044 firstParent = firstPivot;
1045 firstPivot.fixInsertionWithoutGettingRoot(false);
1046 }
1047 firstPivot = node;
1048 node = node.right;
1049 }
1050
1051 depth++;
1052
1053 // Update "first" and "last" to be the nodes at the proper black height
1054 if (advanceFirst) {
1055 firstParent = first;
1056 first = first.right;
1057 if (first.isRed) {
1058 firstParent = first;
1059 first = first.right;
1060 }
1061 }
1062 if (advanceLast) {
1063 lastParent = last;
1064 last = last.left;
1065 if (last.isRed) {
1066 lastParent = last;
1067 last = last.left;
1068 }
1069 }
1070 }
1071
1072 // Add firstPivot to the pre-split tree
1073 N leaf = node;
1074 if (first == null) {
1075 first = leaf;
1076 } else {
1077 firstPivot.isRed = true;
1078 firstPivot.parent = firstParent;
1079 if (firstParent != null) {
1080 firstParent.right = firstPivot;
1081 }
1082 firstPivot.left = leaf;
1083 firstPivot.right = leaf;
1084 firstPivot.fixInsertionWithoutGettingRoot(false);
1085 for (first = firstPivot; first.parent != null; first = first.parent) {
1086 first.augment();
1087 }
1088 first.augment();
1089 }
1090
1091 // Add lastPivot to the post-split tree
1092 lastPivot.isRed = true;
1093 lastPivot.parent = lastParent;
1094 if (lastParent != null) {
1095 lastParent.left = lastPivot;
1096 }
1097 lastPivot.left = leaf;
1098 lastPivot.right = leaf;
1099 lastPivot.fixInsertionWithoutGettingRoot(false);
1100 for (last = lastPivot; last.parent != null; last = last.parent) {
1101 last.augment();
1102 }
1103 last.augment();
1104
1105 @SuppressWarnings("unchecked")
1106 N[] result = (N[])Array.newInstance(getClass(), 2);
1107 result[0] = first;
1108 result[1] = last;
1109 return result;
1110 }
1111
1112 /**
1113 * Returns the lowest common ancestor of this node and "other" - the node that is an ancestor of both and is not the
1114 * parent of a node that is an ancestor of both. Assumes that this is in the same tree as "other". Assumes that
1115 * neither "this" nor "other" is a leaf node. This method may return "this" or "other".
1116 *
1117 * Note that while it is possible to compute the lowest common ancestor in O(P) time, where P is the length of the
1118 * path from this node to "other", the "lca" method is not guaranteed to take O(P) time. If your application
1119 * requires this, then you should write your own lowest common ancestor method.
1120 */
1121 public N lca(N other) {
1122 if (isLeaf() || other.isLeaf()) {
1123 throw new IllegalArgumentException("One of the nodes is a leaf node");
1124 }
1125
1126 // Compute the depth of each node
1127 int depth = 0;
1128 for (N parent = this.parent; parent != null; parent = parent.parent) {
1129 depth++;
1130 }
1131 int otherDepth = 0;
1132 for (N parent = other.parent; parent != null; parent = parent.parent) {
1133 otherDepth++;
1134 }
1135
1136 // Go up to nodes of the same depth
1137 @SuppressWarnings("unchecked")
1138 N parent = (N)this;
1139 N otherParent = other;
1140 if (depth <= otherDepth) {
1141 for (int i = otherDepth; i > depth; i--) {
1142 otherParent = otherParent.parent;
1143 }
1144 } else {
1145 for (int i = depth; i > otherDepth; i--) {
1146 parent = parent.parent;
1147 }
1148 }
1149
1150 // Find the LCA
1151 while (parent != otherParent) {
1152 parent = parent.parent;
1153 otherParent = otherParent.parent;
1154 }
1155 if (parent != null) {
1156 return parent;
1157 } else {
1158 throw new IllegalArgumentException("The nodes do not belong to the same tree");
1159 }
1160 }
1161
1162 /**
1163 * Returns an integer comparing the position of this node in the tree that contains it with that of "other". Returns
1164 * a negative number if this is earlier, a positive number if this is later, and 0 if this is at the same position.
1165 * Assumes that this is in the same tree as "other". Assumes that neither "this" nor "other" is a leaf node.
1166 *
1167 * The base class's implementation takes O(log N) time. If a RedBlackNode subclass stores a value used to order the
1168 * nodes, then it could override compareTo to compare the nodes' values, which would take O(1) time.
1169 *
1170 * Note that while it is possible to compare the positions of two nodes in O(P) time, where P is the length of the
1171 * path from this node to "other", the default implementation of compareTo is not guaranteed to take O(P) time. If
1172 * your application requires this, then you should write your own comparison method.
1173 */
1174 @Override
1175 public int compareTo(N other) {
1176 if (isLeaf() || other.isLeaf()) {
1177 throw new IllegalArgumentException("One of the nodes is a leaf node");
1178 }
1179
1180 // The algorithm operates as follows: compare the depth of this node to that of "other". If the depth of
1181 // "other" is greater, keep moving up from "other" until we find the ancestor at the same depth. Then, keep
1182 // moving up from "this" and from that node until we reach the lowest common ancestor. The node that arrived
1183 // from the left child of the common ancestor is earlier. The algorithm is analogous if the depth of "other" is
1184 // not greater.
1185 if (this == other) {
1186 return 0;
1187 }
1188
1189 // Compute the depth of each node
1190 int depth = 0;
1191 RedBlackNode<N> parent;
1192 for (parent = this; parent.parent != null; parent = parent.parent) {
1193 depth++;
1194 }
1195 int otherDepth = 0;
1196 N otherParent;
1197 for (otherParent = other; otherParent.parent != null; otherParent = otherParent.parent) {
1198 otherDepth++;
1199 }
1200
1201 // Go up to nodes of the same depth
1202 if (depth < otherDepth) {
1203 otherParent = other;
1204 for (int i = otherDepth - 1; i > depth; i--) {
1205 otherParent = otherParent.parent;
1206 }
1207 if (otherParent.parent != this) {
1208 otherParent = otherParent.parent;
1209 } else if (left == otherParent) {
1210 return 1;
1211 } else {
1212 return -1;
1213 }
1214 parent = this;
1215 } else if (depth > otherDepth) {
1216 parent = this;
1217 for (int i = depth - 1; i > otherDepth; i--) {
1218 parent = parent.parent;
1219 }
1220 if (parent.parent != other) {
1221 parent = parent.parent;
1222 } else if (other.left == parent) {
1223 return -1;
1224 } else {
1225 return 1;
1226 }
1227 otherParent = other;
1228 } else {
1229 parent = this;
1230 otherParent = other;
1231 }
1232
1233 // Keep going up until we reach the lowest common ancestor
1234 while (parent.parent != otherParent.parent) {
1235 parent = parent.parent;
1236 otherParent = otherParent.parent;
1237 }
1238 if (parent.parent == null) {
1239 throw new IllegalArgumentException("The nodes do not belong to the same tree");
1240 }
1241 if (parent.parent.left == parent) {
1242 return -1;
1243 } else {
1244 return 1;
1245 }
1246 }
1247
1248 /** Throws a RuntimeException if the RedBlackNode fields of this are not correct for a leaf node. */
1249 private void assertIsValidLeaf() {
1250 if (left != null || right != null || parent != null || isRed) {
1251 throw new RuntimeException("A leaf node's \"left\", \"right\", \"parent\", or isRed field is incorrect");
1252 }
1253 }
1254
1255 /**
1256 * Throws a RuntimeException if the subtree rooted at this node does not satisfy the red-black properties, excluding
1257 * the requirement that the root be black, or it contains a repeated node other than a leaf node.
1258 * @param blackHeight The required number of black nodes in each path from this to a leaf node, including this and
1259 * the leaf node.
1260 * @param visited The nodes we have reached thus far, other than leaf nodes. This method adds the non-leaf nodes in
1261 * the subtree rooted at this node to "visited".
1262 */
1263 private void assertSubtreeIsValidRedBlack(int blackHeight, Set<Reference<N>> visited) {
1264 @SuppressWarnings("unchecked")
1265 N nThis = (N)this;
1266 if (left == null || right == null) {
1267 assertIsValidLeaf();
1268 if (blackHeight != 1) {
1269 throw new RuntimeException("Not all root-to-leaf paths have the same number of black nodes");
1270 }
1271 return;
1272 } else if (!visited.add(new Reference<N>(nThis))) {
1273 throw new RuntimeException("The tree contains a repeated non-leaf node");
1274 } else {
1275 int childBlackHeight;
1276 if (isRed) {
1277 if ((!left.isLeaf() && left.isRed) || (!right.isLeaf() && right.isRed)) {
1278 throw new RuntimeException("A red node has a red child");
1279 }
1280 childBlackHeight = blackHeight;
1281 } else if (blackHeight == 0) {
1282 throw new RuntimeException("Not all root-to-leaf paths have the same number of black nodes");
1283 } else {
1284 childBlackHeight = blackHeight - 1;
1285 }
1286
1287 if (!left.isLeaf() && left.parent != this) {
1288 throw new RuntimeException("left.parent != this");
1289 }
1290 if (!right.isLeaf() && right.parent != this) {
1291 throw new RuntimeException("right.parent != this");
1292 }
1293 RedBlackNode<N> leftNode = left;
1294 RedBlackNode<N> rightNode = right;
1295 leftNode.assertSubtreeIsValidRedBlack(childBlackHeight, visited);
1296 rightNode.assertSubtreeIsValidRedBlack(childBlackHeight, visited);
1297 }
1298 }
1299
1300 /** Calls assertNodeIsValid() on every node in the subtree rooted at this node. */
1301 private void assertNodesAreValid() {
1302 assertNodeIsValid();
1303 if (left != null) {
1304 RedBlackNode<N> leftNode = left;
1305 RedBlackNode<N> rightNode = right;
1306 leftNode.assertNodesAreValid();
1307 rightNode.assertNodesAreValid();
1308 }
1309 }
1310
1311 /**
1312 * Throws a RuntimeException if the subtree rooted at this node is not a valid red-black tree, e.g. if a red node
1313 * has a red child or it contains a non-leaf node "node" for which node.left.parent != node. (If parent != null,
1314 * it's okay if isRed is true.) This method is useful for debugging. See also assertSubtreeIsValid().
1315 */
1316 public void assertSubtreeIsValidRedBlack() {
1317 if (isLeaf()) {
1318 assertIsValidLeaf();
1319 } else {
1320 if (parent == null && isRed) {
1321 throw new RuntimeException("The root is red");
1322 }
1323
1324 // Compute the black height of the tree
1325 Set<Reference<N>> nodes = new HashSet<Reference<N>>();
1326 int blackHeight = 0;
1327 @SuppressWarnings("unchecked")
1328 N node = (N)this;
1329 while (node != null) {
1330 if (!nodes.add(new Reference<N>(node))) {
1331 throw new RuntimeException("The tree contains a repeated non-leaf node");
1332 }
1333 if (!node.isRed) {
1334 blackHeight++;
1335 }
1336 node = node.left;
1337 }
1338
1339 assertSubtreeIsValidRedBlack(blackHeight, new HashSet<Reference<N>>());
1340 }
1341 }
1342
1343 /**
1344 * Throws a RuntimeException if we detect a problem with the subtree rooted at this node, such as a red child of a
1345 * red node or a non-leaf descendant "node" for which node.left.parent != node. This method is useful for
1346 * debugging. RedBlackNode subclasses may want to override assertSubtreeIsValid() to call assertOrderIsValid.
1347 */
1348 public void assertSubtreeIsValid() {
1349 assertSubtreeIsValidRedBlack();
1350 assertNodesAreValid();
1351 }
1352
1353 /**
1354 * Throws a RuntimeException if the nodes in the subtree rooted at this node are not in the specified order or they
1355 * do not lie in the specified range. Assumes that the subtree rooted at this node is a valid binary tree, i.e. it
1356 * has no repeated nodes other than leaf nodes.
1357 * @param comparator A comparator indicating how the nodes should be ordered.
1358 * @param start The lower limit for nodes in the subtree, if any.
1359 * @param end The upper limit for nodes in the subtree, if any.
1360 */
1361 private void assertOrderIsValid(Comparator<? super N> comparator, N start, N end) {
1362 if (!isLeaf()) {
1363 @SuppressWarnings("unchecked")
1364 N nThis = (N)this;
1365 if (start != null && comparator.compare(nThis, start) < 0) {
1366 throw new RuntimeException("The nodes are not ordered correctly");
1367 }
1368 if (end != null && comparator.compare(nThis, end) > 0) {
1369 throw new RuntimeException("The nodes are not ordered correctly");
1370 }
1371 RedBlackNode<N> leftNode = left;
1372 RedBlackNode<N> rightNode = right;
1373 leftNode.assertOrderIsValid(comparator, start, nThis);
1374 rightNode.assertOrderIsValid(comparator, nThis, end);
1375 }
1376 }
1377
1378 /**
1379 * Throws a RuntimeException if the nodes in the subtree rooted at this node are not in the specified order.
1380 * Assumes that this is a valid binary tree, i.e. there are no repeated nodes other than leaf nodes. This method is
1381 * useful for debugging. RedBlackNode subclasses may want to override assertSubtreeIsValid() to call
1382 * assertOrderIsValid.
1383 * @param comparator A comparator indicating how the nodes should be ordered. If this is null, we use the nodes'
1384 * natural order, as in N.compareTo.
1385 */
1386 public void assertOrderIsValid(Comparator<? super N> comparator) {
1387 if (comparator == null) {
1388 comparator = naturalOrder();
1389 }
1390 assertOrderIsValid(comparator, null, null);
1391 }
1392}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/Reference.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/Reference.java
new file mode 100644
index 00000000..a25c167d
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/Reference.java
@@ -0,0 +1,51 @@
1/*
2 * The MIT License (MIT)
3 *
4 * Copyright (c) 2016 btrekkie
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval;
25
26/**
27 * Wraps a value using reference equality. In other words, two references are equal only if their values are the same
28 * object instance, as in ==.
29 * @param <T> The type of value.
30 */
31class Reference<T> {
32 /** The value this wraps. */
33 private final T value;
34
35 public Reference(T value) {
36 this.value = value;
37 }
38
39 public boolean equals(Object obj) {
40 if (!(obj instanceof Reference)) {
41 return false;
42 }
43 Reference<?> reference = (Reference<?>)obj;
44 return value == reference.value;
45 }
46
47 @Override
48 public int hashCode() {
49 return System.identityHashCode(value);
50 }
51}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/aggregators/IntervalAggregatorFactory.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/aggregators/IntervalAggregatorFactory.xtend
new file mode 100644
index 00000000..dee31f67
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/aggregators/IntervalAggregatorFactory.xtend
@@ -0,0 +1,50 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval.aggregators
2
3import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval.Interval
4import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval.IntervalAggregationMode
5import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval.IntervalAggregationOperator
6import org.eclipse.viatra.query.runtime.matchers.psystem.aggregations.AggregatorType
7import org.eclipse.viatra.query.runtime.matchers.psystem.aggregations.BoundAggregator
8import org.eclipse.viatra.query.runtime.matchers.psystem.aggregations.IAggregatorFactory
9import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor
10
11@AggregatorType(parameterTypes=#[Interval], returnTypes=#[Interval])
12abstract class IntervalAggregatorFactory implements IAggregatorFactory {
13 val IntervalAggregationMode mode
14
15 @FinalFieldsConstructor
16 protected new() {
17 }
18
19 override getAggregatorLogic(Class<?> domainClass) {
20 if (domainClass == Interval) {
21 new BoundAggregator(new IntervalAggregationOperator(mode), Interval, Interval)
22 } else {
23 throw new IllegalArgumentException("Unknown domain class: " + domainClass)
24 }
25 }
26}
27
28class intervalSum extends IntervalAggregatorFactory {
29 new() {
30 super(IntervalAggregationMode.SUM)
31 }
32}
33
34class intervalMin extends IntervalAggregatorFactory {
35 new() {
36 super(IntervalAggregationMode.MIN)
37 }
38}
39
40class intervalMax extends IntervalAggregatorFactory {
41 new() {
42 super(IntervalAggregationMode.MAX)
43 }
44}
45
46class intervalJoin extends IntervalAggregatorFactory {
47 new() {
48 super(IntervalAggregationMode.JOIN)
49 }
50}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/aggregators/intervalHull.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/aggregators/intervalHull.xtend
new file mode 100644
index 00000000..72605f57
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/interval/aggregators/intervalHull.xtend
@@ -0,0 +1,74 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval.aggregators
2
3import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval.Interval
4import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval.IntervalHullAggregatorOperator
5import java.math.BigDecimal
6import java.math.BigInteger
7import java.math.MathContext
8import org.eclipse.viatra.query.runtime.matchers.psystem.aggregations.AggregatorType
9import org.eclipse.viatra.query.runtime.matchers.psystem.aggregations.BoundAggregator
10import org.eclipse.viatra.query.runtime.matchers.psystem.aggregations.IAggregatorFactory
11
12@AggregatorType(parameterTypes=#[BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, Short], returnTypes=#[
13 Interval, Interval, Interval, Interval, Interval, Interval, Interval, Interval])
14class intervalHull implements IAggregatorFactory {
15
16 override getAggregatorLogic(Class<?> domainClass) {
17 new BoundAggregator(getAggregationOperator(domainClass), domainClass, Interval)
18 }
19
20 private def getAggregationOperator(Class<?> domainClass) {
21 switch (domainClass) {
22 case BigDecimal:
23 new IntervalHullAggregatorOperator<BigDecimal>() {
24 override protected toBigDecimal(BigDecimal value, MathContext mc) {
25 value.round(mc)
26 }
27 }
28 case BigInteger:
29 new IntervalHullAggregatorOperator<BigInteger>() {
30 override protected toBigDecimal(BigInteger value, MathContext mc) {
31 new BigDecimal(value, mc)
32 }
33 }
34 case Byte:
35 new IntervalHullAggregatorOperator<Byte>() {
36 override protected toBigDecimal(Byte value, MathContext mc) {
37 new BigDecimal(value, mc)
38 }
39 }
40 case Double:
41 new IntervalHullAggregatorOperator<Double>() {
42 override protected toBigDecimal(Double value, MathContext mc) {
43 new BigDecimal(value, mc)
44 }
45 }
46 case Float:
47 new IntervalHullAggregatorOperator<Float>() {
48 override protected toBigDecimal(Float value, MathContext mc) {
49 new BigDecimal(value, mc)
50 }
51 }
52 case Integer:
53 new IntervalHullAggregatorOperator<Integer>() {
54 override protected toBigDecimal(Integer value, MathContext mc) {
55 new BigDecimal(value, mc)
56 }
57 }
58 case Long:
59 new IntervalHullAggregatorOperator<Long>() {
60 override protected toBigDecimal(Long value, MathContext mc) {
61 new BigDecimal(value, mc)
62 }
63 }
64 case Short:
65 new IntervalHullAggregatorOperator<Short>() {
66 override protected toBigDecimal(Short value, MathContext mc) {
67 new BigDecimal(value, mc)
68 }
69 }
70 default:
71 throw new IllegalArgumentException("Unknown domain class: " + domainClass)
72 }
73 }
74}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/GenericTypeIndexer.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/GenericTypeIndexer.xtend
index d6a15c1a..0e0f1f02 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/GenericTypeIndexer.xtend
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/GenericTypeIndexer.xtend
@@ -1,209 +1,150 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns 1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns
2 2
3import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem
4import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type 3import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type
5import org.eclipse.emf.ecore.EClass 4import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem
6import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality 5import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality
7import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
8import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeAnalysisResult 6import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeAnalysisResult
9 7
10class GenericTypeIndexer extends TypeIndexer { 8class GenericTypeIndexer extends TypeIndexer {
11 val PatternGenerator base;
12
13 new(PatternGenerator base) { 9 new(PatternGenerator base) {
14 this.base = base 10 super(base)
15 } 11 }
12
16 override requiresTypeAnalysis() { false } 13 override requiresTypeAnalysis() { false }
17 14
18 public override getRequiredQueries() ''' 15 override getRequiredQueries() '''
19 private pattern newELement(interpretation: PartialInterpretation, element: DefinedElement) { 16 «super.requiredQueries»
20 PartialInterpretation.newElements(interpretation,element); 17
21 } 18 /**
22 19 * Direct supertypes of a type.
23 private pattern typeInterpretation(problem:LogicProblem, interpetation:PartialInterpretation, type:TypeDeclaration, typeInterpretation:PartialComplexTypeInterpretation) { 20 */
24 find interpretation(problem,interpetation); 21 private pattern supertypeDirect(subtype : Type, supertype : Type) {
25 LogicProblem.types(problem,type); 22 Type.supertypes(subtype, supertype);
26 PartialInterpretation.partialtypeinterpratation(interpetation,typeInterpretation); 23 }
27 PartialComplexTypeInterpretation.interpretationOf(typeInterpretation,type); 24
28 } 25 /**
29 26 * All supertypes of a type.
30 private pattern directInstanceOf(problem:LogicProblem, interpetation:PartialInterpretation, element:DefinedElement, type:Type) { 27 */
31 find interpretation(problem,interpetation); 28 private pattern supertypeStar(subtype: Type, supertype: Type) {
32 find mustExist(problem,interpetation,element); 29 subtype == supertype;
33 LogicProblem.types(problem,type); 30 } or {
34 TypeDefinition.elements(type,element); 31 find supertypeDirect+(subtype,supertype);
35 } or { 32 }
36 find mustExist(problem,interpetation,element); 33
37 find typeInterpretation(problem,interpetation,type,typeInterpretation); 34 /// Complex type reasoning patterns ///
38 PartialComplexTypeInterpretation.elements(typeInterpretation,element); 35 //
39 } 36 // In a valid type system, for each element e there is exactly one type T where
40 37 // 1: T(e) - but we dont know this for type declaration
41 /** 38 // 2: For the dynamic type D and another type T, where D(e) && D-->T, T(e) is true.
42 * Direct supertypes of a type. 39 // 2e: A type hierarchy is invalid, if there is a supertype T for a dynamic type D which does no contains e:
43 */ 40 // D(e) && D-->T && !T(e)
44 private pattern supertypeDirect(subtype : Type, supertype : Type) { 41 // 3: There is no T' that T'->T and T'(e)
45 Type.supertypes(subtype, supertype); 42 // 3e: A type hierarcy is invalid, if there is a type T for a dynamic type D, which contains e, but not subtype of T:
46 } 43 // D(e) && ![T--->D] && T(e)
47
48 /**
49 * All supertypes of a type.
50 */
51 private pattern supertypeStar(subtype: Type, supertype: Type) {
52 subtype == supertype;
53 } or {
54 find supertypeDirect+(subtype,supertype);
55 }
56
57 /// Complex type reasoning patterns ///
58 //
59 // In a valid type system, for each element e there is exactly one type T where
60 // 1: T(e) - but we dont know this for type declaration
61 // 2: For the dynamic type D and another type T, where D(e) && D-->T, T(e) is true.
62 // 2e: A type hierarchy is invalid, if there is a supertype T for a dynamic type D which does no contains e:
63 // D(e) && D-->T && !T(e)
64 // 3: There is no T' that T'->T and T'(e)
65 // 3e: A type hierarcy is invalid, if there is a type T for a dynamic type D, which contains e, but not subtype of T:
66 // D(e) && ![T--->D] && T(e)
67 // 4: T is not abstract
68 // Such type T is called Dynamic type of e, while other types are called static types.
69 //
70 // The following patterns checks the possible dynamic types for an element
71
72 private pattern wellformedType(problem: LogicProblem, interpretation:PartialInterpretation, dynamic:Type, element:DefinedElement) {
73 // 1: T(e)
74 find directInstanceOf(problem,interpretation,element,dynamic);
75 // 2e is not true: D(e) && D-->T && !T(e)
76 neg find dynamicTypeNotSubtypeOfADefinition(problem,interpretation,element,dynamic);
77 // 3e is not true: D(e) && ![T--->D] && T(e)
78 neg find dynamicTypeIsSubtypeOfANonDefinition(problem,interpretation,element,dynamic);
79 // 4: T is not abstract
80 Type.isAbstract(dynamic,false);
81 }
82
83
84 private pattern isPrimitive(element: PrimitiveElement) {
85 PrimitiveElement(element);
86 }
87
88 private pattern possibleDynamicType(problem: LogicProblem, interpretation:PartialInterpretation, dynamic:Type, element:DefinedElement)
89 // case 1: element is defined at least once
90 {
91 LogicProblem.types(problem,dynamic);
92 // select a random definition 'randomType'
93 find directInstanceOf(problem,interpretation,element,randomType);
94 // dynamic is a subtype of 'randomType'
95 find supertypeStar(dynamic,randomType);
96 // 2e is not true: D(e) && D-->T && !T(e)
97 neg find dynamicTypeNotSubtypeOfADefinition(problem,interpretation,element,dynamic);
98 // 3e is not true: D(e) && ![T--->D] && T(e)
99 neg find dynamicTypeIsSubtypeOfANonDefinition(problem,interpretation,element,dynamic);
100 // 4: T is not abstract
101 Type.isAbstract(dynamic,false);
102 // 5. element is not primitive datatype
103 neg find isPrimitive(element);
104 } or
105 // case 2: element is not defined anywhere
106 {
107 find mayExist(problem,interpretation,element);
108 // there is no definition
109 neg find directInstanceOf(problem,interpretation,element,_);
110 // 2e is not true: D(e) && D-->T && !T(e)
111 // because non of the definition contains element, the type cannot have defined supertype
112 LogicProblem.types(problem,dynamic);
113 PartialInterpretation.problem(interpretation,problem);
114 neg find typeWithDefinedSupertype(dynamic);
115 // 3e is not true: D(e) && ![T--->D] && T(e)
116 // because there is no definition, dynamic covers all definition
117 // 4: T is not abstract 44 // 4: T is not abstract
118 Type.isAbstract(dynamic,false); 45 // Such type T is called Dynamic type of e, while other types are called static types.
119 // 5. element is not primitive datatype 46 //
120 neg find isPrimitive(element); 47 // The following patterns checks the possible dynamic types for an element
121 } 48
122 49 private pattern wellformedType(problem: LogicProblem, interpretation:PartialInterpretation, dynamic:Type, element:DefinedElement) {
123 /** 50 // 1: T(e)
124 * supertype -------> element <------- otherSupertype 51 find directInstanceOf(problem,interpretation,element,dynamic);
125 * A A 52 // 2e is not true: D(e) && D-->T && !T(e)
126 * | | 53 neg find dynamicTypeNotSubtypeOfADefinition(problem,interpretation,element,dynamic);
127 * wrongDynamic -----------------------------X 54 // 3e is not true: D(e) && ![T--->D] && T(e)
128 */ 55 neg find dynamicTypeIsSubtypeOfANonDefinition(problem,interpretation,element,dynamic);
129 private pattern dynamicTypeNotSubtypeOfADefinition(problem:LogicProblem, interpretation:PartialInterpretation, element:DefinedElement, wrongDynamic : Type) { 56 // 4: T is not abstract
130 find directInstanceOf(problem,interpretation,element,supertype); 57 Type.isAbstract(dynamic,false);
131 find directInstanceOf(problem,interpretation,element,otherSupertype); 58 }
132 find supertypeStar(wrongDynamic,supertype); 59
133 neg find supertypeStar(wrongDynamic,otherSupertype); 60 private pattern possibleDynamicType(problem: LogicProblem, interpretation:PartialInterpretation, dynamic:Type, element:DefinedElement)
134 } 61 // case 1: element is defined at least once
135 62 {
136 /** 63 LogicProblem.types(problem,dynamic);
137 * supertype -------> element <---X--- otherSupertype 64 // select a random definition 'randomType'
138 * A A 65 find directInstanceOf(problem,interpretation,element,randomType);
139 * | | 66 // dynamic is a subtype of 'randomType'
140 * wrongDynamic -----------------------------+ 67 find supertypeStar(dynamic,randomType);
141 */ 68 // 2e is not true: D(e) && D-->T && !T(e)
142 private pattern dynamicTypeIsSubtypeOfANonDefinition(problem: LogicProblem, interpretation:PartialInterpretation, element:DefinedElement, wrongDynamic:Type) { 69 neg find dynamicTypeNotSubtypeOfADefinition(problem,interpretation,element,dynamic);
143 find directInstanceOf(problem,interpretation,element,supertype); 70 // 3e is not true: D(e) && ![T--->D] && T(e)
144 neg find elementInTypeDefinition(element,otherSupertype); 71 neg find dynamicTypeIsSubtypeOfANonDefinition(problem,interpretation,element,dynamic);
145 TypeDefinition(otherSupertype); 72 // 4: T is not abstract
146 find supertypeStar(wrongDynamic, supertype); 73 Type.isAbstract(dynamic,false);
147 find supertypeStar(wrongDynamic, otherSupertype); 74 // 5. element is not primitive datatype
148 } 75 neg find isPrimitive(element);
149 76 } or
150 private pattern elementInTypeDefinition(element:DefinedElement, definition:TypeDefinition) { 77 // case 2: element is not defined anywhere
151 TypeDefinition.elements(definition,element); 78 {
152 } 79 find mayExist(problem,interpretation,element);
153 80 // there is no definition
154 private pattern typeWithDefinedSupertype(type:Type) { 81 neg find directInstanceOf(problem,interpretation,element,_);
155 find supertypeStar(type,definedSupertype); 82 // 2e is not true: D(e) && D-->T && !T(e)
156 TypeDefinition(definedSupertype); 83 // because non of the definition contains element, the type cannot have defined supertype
157 } 84 LogicProblem.types(problem,dynamic);
158 85 PartialInterpretation.problem(interpretation,problem);
159 private pattern scopeDisallowsNewElementsFromType(typeInterpretation:PartialComplexTypeInterpretation) { 86 neg find typeWithDefinedSupertype(dynamic);
160 Scope.targetTypeInterpretation(scope,typeInterpretation); 87 // 3e is not true: D(e) && ![T--->D] && T(e)
161 Scope.maxNewElements(scope,0); 88 // because there is no definition, dynamic covers all definition
162 } 89 // 4: T is not abstract
163 ''' 90 Type.isAbstract(dynamic,false);
164 91 // 5. element is not primitive datatype
165 public override generateInstanceOfQueries(LogicProblem problem, PartialInterpretation emptySolution,TypeAnalysisResult typeAnalysisResult) { 92 neg find isPrimitive(element);
166 ''' 93 }
167 «FOR type:problem.types» 94
168 «problem.generateMustInstenceOf(type)»
169 «problem.generateMayInstanceOf(type)»
170 «ENDFOR»
171 '''
172 }
173
174 private def patternName(Type type, Modality modality)
175 '''«modality.toString.toLowerCase»InstanceOf«base.canonizeName(type.name)»'''
176
177 private def generateMustInstenceOf(LogicProblem problem, Type type) {
178 '''
179 /** 95 /**
180 * An element must be an instance of type "«type.name»". 96 * supertype -------> element <------- otherSupertype
97 * A A
98 * | |
99 * wrongDynamic -----------------------------X
181 */ 100 */
182 private pattern «patternName(type,Modality.MUST)»(problem:LogicProblem, interpretation:PartialInterpretation, element:DefinedElement) { 101 private pattern dynamicTypeNotSubtypeOfADefinition(problem:LogicProblem, interpretation:PartialInterpretation, element:DefinedElement, wrongDynamic : Type) {
183 Type.name(type,"«type.name»"); 102 find directInstanceOf(problem,interpretation,element,supertype);
184 find directInstanceOf(problem,interpretation,element,type); 103 find directInstanceOf(problem,interpretation,element,otherSupertype);
104 find supertypeStar(wrongDynamic,supertype);
105 neg find supertypeStar(wrongDynamic,otherSupertype);
185 } 106 }
186 ''' 107
187 }
188
189 private def generateMayInstanceOf(LogicProblem problem, Type type) {
190 '''
191 /** 108 /**
192 * An element may be an instance of type "«type.name»". 109 * supertype -------> element <---X--- otherSupertype
110 * A A
111 * | |
112 * wrongDynamic -----------------------------+
193 */ 113 */
194 private pattern «patternName(type,Modality.MAY)»(problem:LogicProblem, interpretation:PartialInterpretation, element:DefinedElement) { 114 private pattern dynamicTypeIsSubtypeOfANonDefinition(problem: LogicProblem, interpretation:PartialInterpretation, element:DefinedElement, wrongDynamic:Type) {
195 Type.name(type,"«type.name»"); 115 find directInstanceOf(problem,interpretation,element,supertype);
196 find possibleDynamicType(problem,interpretation,dynamic,element); 116 neg find elementInTypeDefinition(element,otherSupertype);
197 find supertypeStar(dynamic,type); 117 TypeDefinition(otherSupertype);
198 neg find scopeDisallowsNewElementsFromType(dynamic); 118 find supertypeStar(wrongDynamic, supertype);
119 find supertypeStar(wrongDynamic, otherSupertype);
120 }
121
122 private pattern elementInTypeDefinition(element:DefinedElement, definition:TypeDefinition) {
123 TypeDefinition.elements(definition,element);
124 }
125
126 private pattern typeWithDefinedSupertype(type:Type) {
127 find supertypeStar(type,definedSupertype);
128 TypeDefinition(definedSupertype);
129 }
130
131 private pattern scopeDisallowsNewElementsFromType(typeInterpretation:PartialComplexTypeInterpretation) {
132 Scope.targetTypeInterpretation(scope,typeInterpretation);
133 Scope.maxNewElements(scope,0);
199 } 134 }
135 '''
136
137 protected override generateMayInstanceOf(LogicProblem problem, Type type, TypeAnalysisResult typeAnalysisResult) {
138 '''
139 /**
140 * An element may be an instance of type "«type.name»".
141 */
142 private pattern «patternName(type,Modality.MAY)»(problem:LogicProblem, interpretation:PartialInterpretation, element:DefinedElement) {
143 Type.name(type,"«type.name»");
144 find possibleDynamicType(problem,interpretation,dynamic,element);
145 find supertypeStar(dynamic,type);
146 neg find scopeDisallowsNewElementsFromType(dynamic);
147 }
200 ''' 148 '''
201 } 149 }
202 150}
203 public override referInstanceOf(Type type, Modality modality, String variableName) {
204 '''find «patternName(type,modality)»(problem,interpretation,«variableName»);'''
205 }
206 public override referInstanceOf(EClass type, Modality modality, String variableName) {
207 '''find «modality.toString.toLowerCase»InstanceOf«base.canonizeName('''«type.name» class''')»(problem,interpretation,«variableName»);'''
208 }
209} \ 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/GenericTypeRefinementGenerator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/GenericTypeRefinementGenerator.xtend
index 2e03d6ed..52f0cbea 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/GenericTypeRefinementGenerator.xtend
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/GenericTypeRefinementGenerator.xtend
@@ -11,110 +11,114 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.par
11import java.util.HashMap 11import java.util.HashMap
12 12
13class GenericTypeRefinementGenerator extends TypeRefinementGenerator { 13class GenericTypeRefinementGenerator extends TypeRefinementGenerator {
14 public new(PatternGenerator base) { 14 new(PatternGenerator base) {
15 super(base) 15 super(base)
16 } 16 }
17
17 override requiresTypeAnalysis() { false } 18 override requiresTypeAnalysis() { false }
18 19
19 override generateRefineObjectQueries(LogicProblem p, PartialInterpretation emptySolution, TypeAnalysisResult typeAnalysisResult) { 20 override generateRefineObjectQueries(LogicProblem p, PartialInterpretation emptySolution,
21 TypeAnalysisResult typeAnalysisResult) {
20 val containment = p.containmentHierarchies.head 22 val containment = p.containmentHierarchies.head
21 val newObjectTypes = p.types.filter(TypeDeclaration).filter[!isAbstract] 23 val newObjectTypes = p.types.filter(TypeDeclaration).filter[!isAbstract]
22 val inverseRelations = new HashMap 24 val inverseRelations = new HashMap
23 p.annotations.filter(InverseRelationAssertion).forEach[ 25 p.annotations.filter(InverseRelationAssertion).forEach [
24 inverseRelations.put(it.inverseA,it.inverseB) 26 inverseRelations.put(it.inverseA, it.inverseB)
25 inverseRelations.put(it.inverseB,it.inverseA) 27 inverseRelations.put(it.inverseB, it.inverseA)
26 ] 28 ]
27 return ''' 29 return '''
28 private pattern hasElementInContainment(problem:LogicProblem, interpretation:PartialInterpretation) 30 pattern «hasElementInContainmentName»(problem:LogicProblem, interpretation:PartialInterpretation)
29 «FOR type :containment.typesOrderedInHierarchy SEPARATOR "or"»{ 31 «FOR type : containment.typesOrderedInHierarchy SEPARATOR "or"»{
30 find interpretation(problem,interpretation);
31 «base.typeIndexer.referInstanceOf(type,Modality.MUST,"root")»
32 find mustExist(problem, interpretation, root);
33 }«ENDFOR»
34 «FOR type:newObjectTypes»
35 «IF(containment.typesOrderedInHierarchy.contains(type))»
36 «FOR containmentRelation : containment.containmentRelations.filter[canBeContainedByRelation(it,type)]»
37 «IF inverseRelations.containsKey(containmentRelation)»
38 pattern «this.patternName(containmentRelation,inverseRelations.get(containmentRelation),type)»(
39 problem:LogicProblem, interpretation:PartialInterpretation,
40 relationInterpretation:PartialRelationInterpretation, inverseInterpretation:PartialRelationInterpretation ,typeInterpretation:PartialComplexTypeInterpretation,
41 container:DefinedElement)
42 {
43 find interpretation(problem,interpretation);
44 PartialInterpretation.partialtypeinterpratation(interpretation,typeInterpretation);
45 PartialComplexTypeInterpretation.interpretationOf.name(typeInterpretation,"«type.name»");
46 PartialInterpretation.partialrelationinterpretation(interpretation,relationInterpretation);
47 PartialRelationInterpretation.interpretationOf.name(relationInterpretation,"«containmentRelation.name»");
48 PartialInterpretation.partialrelationinterpretation(interpretation,inverseInterpretation);
49 PartialRelationInterpretation.interpretationOf.name(inverseInterpretation,"«inverseRelations.get(containmentRelation).name»");
50 «base.typeIndexer.referInstanceOf((containmentRelation.parameters.get(0) as ComplexTypeReference).referred,Modality.MUST,"container")»
51 «base.typeIndexer.referInstanceOf(type,Modality.MAY,"newObject")»
52 «base.relationDeclarationIndexer.referRelation(containmentRelation as RelationDeclaration,"container","newObject",Modality.MAY)»
53 find mustExist(problem, interpretation, container);
54 neg find mustExist(problem, interpretation, newObject);
55 }
56 «ELSE»
57 pattern «this.patternName(containmentRelation,null,type)»(
58 problem:LogicProblem, interpretation:PartialInterpretation,
59 relationInterpretation:PartialRelationInterpretation, typeInterpretation:PartialComplexTypeInterpretation,
60 container:DefinedElement)
61 {
62 find interpretation(problem,interpretation);
63 PartialInterpretation.partialtypeinterpratation(interpretation,typeInterpretation);
64 PartialComplexTypeInterpretation.interpretationOf.name(typeInterpretation,"«type.name»");
65 PartialInterpretation.partialrelationinterpretation(interpretation,relationInterpretation);
66 PartialRelationInterpretation.interpretationOf.name(relationInterpretation,"«containmentRelation.name»");
67 «base.typeIndexer.referInstanceOf((containmentRelation.parameters.get(0) as ComplexTypeReference).referred,Modality.MUST,"container")»
68 «base.typeIndexer.referInstanceOf(type,Modality.MAY,"newObject")»
69 «base.relationDeclarationIndexer.referRelation(containmentRelation as RelationDeclaration,"container","newObject",Modality.MAY)»
70 find mustExist(problem, interpretation, container);
71 neg find mustExist(problem, interpretation, newObject);
72 }
73 «ENDIF»
74 «ENDFOR»
75 pattern «patternName(null,null,type)»(
76 problem:LogicProblem, interpretation:PartialInterpretation,
77 typeInterpretation:PartialComplexTypeInterpretation)
78 {
79 find interpretation(problem,interpretation); 32 find interpretation(problem,interpretation);
80 neg find hasElementInContainment(problem,interpretation); 33 «base.typeIndexer.referInstanceOf(type,Modality.MUST,"root")»
81 PartialInterpretation.partialtypeinterpratation(interpretation,typeInterpretation); 34 find mustExist(problem, interpretation, root);
82 PartialComplexTypeInterpretation.interpretationOf.name(type,"«type.name»"); 35 }«ENDFOR»
83 «base.typeIndexer.referInstanceOf(type,Modality.MAY,"newObject")» 36 «FOR type : newObjectTypes»
84 find mayExist(problem, interpretation, newObject); 37 «IF(containment.typesOrderedInHierarchy.contains(type))»
85 neg find mustExist(problem, interpretation, newObject); 38 «FOR containmentRelation : containment.containmentRelations.filter[canBeContainedByRelation(it,type)]»
86 } 39 «IF inverseRelations.containsKey(containmentRelation)»
87 «ELSE» 40 pattern «this.patternName(containmentRelation,inverseRelations.get(containmentRelation),type)»(
88 pattern createObject_«this.patternName(null,null,type)»( 41 problem:LogicProblem, interpretation:PartialInterpretation,
89 problem:LogicProblem, interpretation:PartialInterpretation, 42 relationInterpretation:PartialRelationInterpretation, inverseInterpretation:PartialRelationInterpretation ,typeInterpretation:PartialComplexTypeInterpretation,
90 typeInterpretation:PartialComplexTypeInterpretation) 43 container:DefinedElement)
91 { 44 {
92 find interpretation(problem,interpretation); 45 find interpretation(problem,interpretation);
93 PartialInterpretation.partialtypeinterpratation(interpretation,typeInterpretation); 46 PartialInterpretation.partialtypeinterpratation(interpretation,typeInterpretation);
94 PartialComplexTypeInterpretation.interpretationOf.name(typeInterpretation,"«type.name»"); 47 PartialComplexTypeInterpretation.interpretationOf.name(typeInterpretation,"«type.name»");
95 «base.typeIndexer.referInstanceOf(type,Modality.MAY,"newObject")» 48 PartialInterpretation.partialrelationinterpretation(interpretation,relationInterpretation);
96 find mayExist(problem, interpretation, newObject); 49 PartialRelationInterpretation.interpretationOf.name(relationInterpretation,"«containmentRelation.name»");
97 neg find mustExist(problem, interpretation, newObject); 50 PartialInterpretation.partialrelationinterpretation(interpretation,inverseInterpretation);
98 } 51 PartialRelationInterpretation.interpretationOf.name(inverseInterpretation,"«inverseRelations.get(containmentRelation).name»");
99 «ENDIF» 52 «base.typeIndexer.referInstanceOf((containmentRelation.parameters.get(0) as ComplexTypeReference).referred,Modality.MUST,"container")»
100 «ENDFOR» 53 «base.typeIndexer.referInstanceOf(type,Modality.MAY,"newObject")»
54 «base.relationDeclarationIndexer.referRelation(containmentRelation as RelationDeclaration,"container","newObject",Modality.MAY)»
55 find mustExist(problem, interpretation, container);
56 neg find mustExist(problem, interpretation, newObject);
57 }
58 «ELSE»
59 pattern «this.patternName(containmentRelation,null,type)»(
60 problem:LogicProblem, interpretation:PartialInterpretation,
61 relationInterpretation:PartialRelationInterpretation, typeInterpretation:PartialComplexTypeInterpretation,
62 container:DefinedElement)
63 {
64 find interpretation(problem,interpretation);
65 PartialInterpretation.partialtypeinterpratation(interpretation,typeInterpretation);
66 PartialComplexTypeInterpretation.interpretationOf.name(typeInterpretation,"«type.name»");
67 PartialInterpretation.partialrelationinterpretation(interpretation,relationInterpretation);
68 PartialRelationInterpretation.interpretationOf.name(relationInterpretation,"«containmentRelation.name»");
69 «base.typeIndexer.referInstanceOf((containmentRelation.parameters.get(0) as ComplexTypeReference).referred,Modality.MUST,"container")»
70 «base.typeIndexer.referInstanceOf(type,Modality.MAY,"newObject")»
71 «base.relationDeclarationIndexer.referRelation(containmentRelation as RelationDeclaration,"container","newObject",Modality.MAY)»
72 find mustExist(problem, interpretation, container);
73 neg find mustExist(problem, interpretation, newObject);
74 }
75 «ENDIF»
76 «ENDFOR»
77 pattern «patternName(null,null,type)»(
78 problem:LogicProblem, interpretation:PartialInterpretation,
79 typeInterpretation:PartialComplexTypeInterpretation)
80 {
81 find interpretation(problem,interpretation);
82 neg find «hasElementInContainmentName»(problem,interpretation);
83 PartialInterpretation.partialtypeinterpratation(interpretation,typeInterpretation);
84 PartialComplexTypeInterpretation.interpretationOf.name(type,"«type.name»");
85 «base.typeIndexer.referInstanceOf(type,Modality.MAY,"newObject")»
86 find mayExist(problem, interpretation, newObject);
87 neg find mustExist(problem, interpretation, newObject);
88 }
89 «ELSE»
90 pattern createObject_«this.patternName(null,null,type)»(
91 problem:LogicProblem, interpretation:PartialInterpretation,
92 typeInterpretation:PartialComplexTypeInterpretation)
93 {
94 find interpretation(problem,interpretation);
95 PartialInterpretation.partialtypeinterpratation(interpretation,typeInterpretation);
96 PartialComplexTypeInterpretation.interpretationOf.name(typeInterpretation,"«type.name»");
97 «base.typeIndexer.referInstanceOf(type,Modality.MAY,"newObject")»
98 find mayExist(problem, interpretation, newObject);
99 neg find mustExist(problem, interpretation, newObject);
100 }
101 «ENDIF»
102 «ENDFOR»
101 ''' 103 '''
102 } 104 }
103 105
104 override generateRefineTypeQueries(LogicProblem p, PartialInterpretation emptySolution, TypeAnalysisResult typeAnalysisResult) { 106 override generateRefineTypeQueries(LogicProblem p, PartialInterpretation emptySolution,
107 TypeAnalysisResult typeAnalysisResult) {
105 return ''' 108 return '''
106 «FOR type : p.types.filter(TypeDeclaration).filter[!it.isAbstract]» 109 «FOR type : p.types.filter(TypeDeclaration).filter[!it.isAbstract]»
107 pattern refineTypeTo_«base.canonizeName(type.name)»(problem:LogicProblem, interpretation:PartialInterpretation, object: DefinedElement) { 110 pattern refineTypeTo_«base.canonizeName(type.name)»(problem:LogicProblem, interpretation:PartialInterpretation, object: DefinedElement) {
108 find interpretation(problem,interpretation); 111 find interpretation(problem,interpretation);
109 find mustExist(problem, interpretation, object); 112 find mustExist(problem, interpretation, object);
110 «base.typeIndexer.referInstanceOf(type,Modality.MAY,"object")» 113 «base.typeIndexer.referInstanceOf(type,Modality.MAY,"object")»
111 neg «base.typeIndexer.referInstanceOf(type,Modality.MUST,"object")» 114 neg «base.typeIndexer.referInstanceOf(type,Modality.MUST,"object")»
112 } 115 }
113 «ENDFOR» 116 «ENDFOR»
114 ''' 117 '''
115 } 118 }
116 119
117 override getRefineTypeQueryNames(LogicProblem p, PartialInterpretation emptySolution, TypeAnalysisResult typeAnalysisResult) { 120 override getRefineTypeQueryNames(LogicProblem p, PartialInterpretation emptySolution,
121 TypeAnalysisResult typeAnalysisResult) {
118 p.types.filter(TypeDeclaration).toInvertedMap['''refineTypeTo_«base.canonizeName(it.name)»'''] 122 p.types.filter(TypeDeclaration).toInvertedMap['''refineTypeTo_«base.canonizeName(it.name)»''']
119 } 123 }
120} \ No newline at end of file 124}
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 677170b8..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
@@ -1,7 +1,6 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns 1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns
2 2
3import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.InverseRelationAssertion 3import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.InverseRelationAssertion
4import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.LowerMultiplicityAssertion
5import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.BoolTypeReference 4import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.BoolTypeReference
6import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.IntTypeReference 5import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.IntTypeReference
7import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RealTypeReference 6import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RealTypeReference
@@ -17,7 +16,11 @@ import hu.bme.mit.inf.dslreasoner.viatra2logic.viatra2logicannotations.Transform
17import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality 16import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality
18import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeAnalysisResult 17import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeAnalysisResult
19import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeInferenceMethod 18import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeInferenceMethod
19import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint
20import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.RelationConstraints
21import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy
20import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation 22import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
23import java.util.Collection
21import java.util.HashMap 24import java.util.HashMap
22import java.util.Map 25import java.util.Map
23import org.eclipse.emf.ecore.EAttribute 26import org.eclipse.emf.ecore.EAttribute
@@ -36,21 +39,23 @@ import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint
36} 39}
37 40
38class PatternGenerator { 41class PatternGenerator {
39 @Accessors(PUBLIC_GETTER) val TypeIndexer typeIndexer //= new TypeIndexer(this) 42 @Accessors(PUBLIC_GETTER) val TypeIndexer typeIndexer // = new TypeIndexer(this)
40 @Accessors(PUBLIC_GETTER) val RelationDeclarationIndexer relationDeclarationIndexer = new RelationDeclarationIndexer(this) 43 @Accessors(PUBLIC_GETTER) val RelationDeclarationIndexer relationDeclarationIndexer = new RelationDeclarationIndexer(
41 @Accessors(PUBLIC_GETTER) val RelationDefinitionIndexer relationDefinitionIndexer = new RelationDefinitionIndexer(this) 44 this)
45 @Accessors(PUBLIC_GETTER) val RelationDefinitionIndexer relationDefinitionIndexer = new RelationDefinitionIndexer(
46 this)
42 @Accessors(PUBLIC_GETTER) val ContainmentIndexer containmentIndexer = new ContainmentIndexer(this) 47 @Accessors(PUBLIC_GETTER) val ContainmentIndexer containmentIndexer = new ContainmentIndexer(this)
43 @Accessors(PUBLIC_GETTER) val InvalidIndexer invalidIndexer = new InvalidIndexer(this) 48 @Accessors(PUBLIC_GETTER) val InvalidIndexer invalidIndexer = new InvalidIndexer(this)
44 @Accessors(PUBLIC_GETTER) val UnfinishedIndexer unfinishedIndexer = new UnfinishedIndexer(this) 49 @Accessors(PUBLIC_GETTER) val UnfinishedIndexer unfinishedIndexer
45 @Accessors(PUBLIC_GETTER) val TypeRefinementGenerator typeRefinementGenerator //= new RefinementGenerator(this) 50 @Accessors(PUBLIC_GETTER) val TypeRefinementGenerator typeRefinementGenerator //= new RefinementGenerator(this)
46 @Accessors(PUBLIC_GETTER) val RelationRefinementGenerator relationRefinementGenerator = new RelationRefinementGenerator(this) 51 @Accessors(PUBLIC_GETTER) val RelationRefinementGenerator relationRefinementGenerator = new RelationRefinementGenerator(this)
47 @Accessors(PUBLIC_GETTER) val UnitPropagationPreconditionGenerator unitPropagationPreconditionGenerator = new UnitPropagationPreconditionGenerator(this) 52 @Accessors(PUBLIC_GETTER) val UnitPropagationPreconditionGenerator unitPropagationPreconditionGenerator = new UnitPropagationPreconditionGenerator(this)
48 53
49 public new(TypeInferenceMethod typeInferenceMethod) { 54 public new(TypeInferenceMethod typeInferenceMethod, ScopePropagatorStrategy scopePropagatorStrategy) {
50 if(typeInferenceMethod == TypeInferenceMethod.Generic) { 55 if(typeInferenceMethod == TypeInferenceMethod.Generic) {
51 this.typeIndexer = new GenericTypeIndexer(this) 56 this.typeIndexer = new GenericTypeIndexer(this)
52 this.typeRefinementGenerator = new GenericTypeRefinementGenerator(this) 57 this.typeRefinementGenerator = new GenericTypeRefinementGenerator(this)
53 } else if(typeInferenceMethod == TypeInferenceMethod.PreliminaryAnalysis) { 58 } else if (typeInferenceMethod == TypeInferenceMethod.PreliminaryAnalysis) {
54 this.typeIndexer = new TypeIndexerWithPreliminaryTypeAnalysis(this) 59 this.typeIndexer = new TypeIndexerWithPreliminaryTypeAnalysis(this)
55 this.typeRefinementGenerator = new TypeRefinementWithPreliminaryTypeAnalysis(this) 60 this.typeRefinementGenerator = new TypeRefinementWithPreliminaryTypeAnalysis(this)
56 } else { 61 } else {
@@ -58,110 +63,101 @@ class PatternGenerator {
58 this.typeRefinementGenerator = null 63 this.typeRefinementGenerator = null
59 throw new IllegalArgumentException('''Unknown type indexing technique : «typeInferenceMethod.name»''') 64 throw new IllegalArgumentException('''Unknown type indexing technique : «typeInferenceMethod.name»''')
60 } 65 }
66 this.unfinishedIndexer = new UnfinishedIndexer(this, scopePropagatorStrategy.requiresUpperBoundIndexing)
61 } 67 }
62 68
63 public def requiresTypeAnalysis() { 69 def requiresTypeAnalysis() {
64 typeIndexer.requiresTypeAnalysis || typeRefinementGenerator.requiresTypeAnalysis 70 typeIndexer.requiresTypeAnalysis || typeRefinementGenerator.requiresTypeAnalysis
65 } 71 }
66 72
67 public dispatch def referRelation( 73 dispatch def CharSequence referRelation(RelationDeclaration referred, String sourceVariable, String targetVariable,
68 RelationDeclaration referred, 74 Modality modality, Map<String, PQuery> fqn2PQuery) {
69 String sourceVariable, 75 return this.relationDeclarationIndexer.referRelation(referred, sourceVariable, targetVariable, modality)
70 String targetVariable,
71 Modality modality,
72 Map<String,PQuery> fqn2PQuery)
73 {
74 return this.relationDeclarationIndexer.referRelation(referred,sourceVariable,targetVariable,modality)
75 } 76 }
76 public dispatch def referRelation( 77
77 RelationDefinition referred, 78 dispatch def CharSequence referRelation(RelationDefinition referred, String sourceVariable, String targetVariable,
78 String sourceVariable, 79 Modality modality, Map<String, PQuery> fqn2PQuery) {
79 String targetVariable, 80 val pattern = referred.annotations.filter(TransfomedViatraQuery).head.patternFullyQualifiedName.lookup(
80 Modality modality, 81 fqn2PQuery)
81 Map<String,PQuery> fqn2PQuery) 82 return this.relationDefinitionIndexer.referPattern(pattern, #[sourceVariable, targetVariable], modality, true,
82 { 83 false)
83 val pattern = referred.annotations.filter(TransfomedViatraQuery).head.patternFullyQualifiedName.lookup(fqn2PQuery)
84 return this.relationDefinitionIndexer.referPattern(pattern,#[sourceVariable,targetVariable],modality,true,false)
85 } 84 }
86 85
87 def public referRelationByName(EReference reference, 86 def referRelationByName(EReference reference, String sourceVariable, String targetVariable, Modality modality) {
88 String sourceVariable, 87 '''find «modality.name.toLowerCase»InRelation«canonizeName('''«reference.name» reference «reference.EContainingClass.name»''')»(problem,interpretation,«sourceVariable»,«targetVariable»);'''
89 String targetVariable,
90 Modality modality)
91 {
92 '''find «modality.name.toLowerCase»InRelation«canonizeName('''«reference.name» reference «reference.EContainingClass.name»''')
93 »(problem,interpretation,«sourceVariable»,«targetVariable»);'''
94 } 88 }
95 89
96 def public CharSequence referAttributeByName(EAttribute attribute, 90 def CharSequence referAttributeByName(EAttribute attribute, String sourceVariable, String targetVariable,
97 String sourceVariable, 91 Modality modality) {
98 String targetVariable, 92 '''find «modality.name.toLowerCase»InRelation«canonizeName('''«attribute.name» attribute «attribute.EContainingClass.name»''')»(problem,interpretation,«sourceVariable»,«targetVariable»);'''
99 Modality modality)
100 {
101 '''find «modality.name.toLowerCase»InRelation«canonizeName('''«attribute.name» attribute «attribute.EContainingClass.name»''')
102 »(problem,interpretation,«sourceVariable»,«targetVariable»);'''
103 } 93 }
104 94
105 public def canonizeName(String name) { 95 def canonizeName(String name) {
106 name.split(' ').join('_') 96 name.split(' ').join('_')
107 } 97 }
108 98
109 public def lowerMultiplicities(LogicProblem problem) { 99 def wfQueries(LogicProblem problem) {
110 problem.assertions.map[annotations].flatten.filter(LowerMultiplicityAssertion).filter[!it.relation.isDerived] 100 problem.assertions.map[it.annotations].flatten.filter(TransformedViatraWellformednessConstraint).map[it.query]
111 }
112 public def wfQueries(LogicProblem problem) {
113 problem.assertions.map[it.annotations]
114 .flatten
115 .filter(TransformedViatraWellformednessConstraint)
116 .map[it.query]
117 } 101 }
118 public def getContainments(LogicProblem p) { 102
103 def getContainments(LogicProblem p) {
119 return p.containmentHierarchies.head.containmentRelations 104 return p.containmentHierarchies.head.containmentRelations
120 } 105 }
121 public def getInverseRelations(LogicProblem p) { 106
107 def getInverseRelations(LogicProblem p) {
122 val inverseRelations = new HashMap 108 val inverseRelations = new HashMap
123 p.annotations.filter(InverseRelationAssertion).forEach[ 109 p.annotations.filter(InverseRelationAssertion).forEach [
124 inverseRelations.put(it.inverseA,it.inverseB) 110 inverseRelations.put(it.inverseA, it.inverseB)
125 inverseRelations.put(it.inverseB,it.inverseA) 111 inverseRelations.put(it.inverseB, it.inverseA)
126 ] 112 ]
127 return inverseRelations 113 return inverseRelations
128 } 114 }
129 public def isRepresentative(Relation relation, Relation inverse) { 115
130 if(inverse == null) { 116 def isRepresentative(Relation relation, Relation inverse) {
117 if (relation === null) {
118 return false
119 } else if (inverse === null) {
131 return true 120 return true
132 } else { 121 } else {
133 relation.name.compareTo(inverse.name)<1 122 relation.name.compareTo(inverse.name) < 1
134 } 123 }
135 } 124 }
136 125
137 public def isDerived(Relation relation) { 126 def isDerived(Relation relation) {
138 relation.annotations.exists[it instanceof DefinedByDerivedFeature] 127 relation.annotations.exists[it instanceof DefinedByDerivedFeature]
139 } 128 }
140 public def getDerivedDefinition(RelationDeclaration relation) { 129
130 def getDerivedDefinition(RelationDeclaration relation) {
141 relation.annotations.filter(DefinedByDerivedFeature).head.query 131 relation.annotations.filter(DefinedByDerivedFeature).head.query
142 } 132 }
143 133
144 private def allTypeReferences(LogicProblem problem) { 134 private def allTypeReferences(LogicProblem problem) {
145 problem.eAllContents.filter(TypeReference).toIterable 135 problem.eAllContents.filter(TypeReference).toIterable
146 } 136 }
137
147 protected def hasBoolean(LogicProblem problem) { 138 protected def hasBoolean(LogicProblem problem) {
148 problem.allTypeReferences.exists[it instanceof BoolTypeReference] 139 problem.allTypeReferences.exists[it instanceof BoolTypeReference]
149 } 140 }
141
150 protected def hasInteger(LogicProblem problem) { 142 protected def hasInteger(LogicProblem problem) {
151 problem.allTypeReferences.exists[it instanceof IntTypeReference] 143 problem.allTypeReferences.exists[it instanceof IntTypeReference]
152 } 144 }
145
153 protected def hasReal(LogicProblem problem) { 146 protected def hasReal(LogicProblem problem) {
154 problem.allTypeReferences.exists[it instanceof RealTypeReference] 147 problem.allTypeReferences.exists[it instanceof RealTypeReference]
155 } 148 }
149
156 protected def hasString(LogicProblem problem) { 150 protected def hasString(LogicProblem problem) {
157 problem.allTypeReferences.exists[it instanceof StringTypeReference] 151 problem.allTypeReferences.exists[it instanceof StringTypeReference]
158 } 152 }
159 153
160 public def PatternGeneratorResult transformBaseProperties( 154 def transformBaseProperties(
161 LogicProblem problem, 155 LogicProblem problem,
162 PartialInterpretation emptySolution, 156 PartialInterpretation emptySolution,
163 Map<String,PQuery> fqn2PQuery, 157 Map<String, PQuery> fqn2PQuery,
164 TypeAnalysisResult typeAnalysisResult 158 TypeAnalysisResult typeAnalysisResult,
159 RelationConstraints constraints,
160 Collection<LinearTypeConstraintHint> hints
165 ) { 161 ) {
166 val first = 162 val first =
167 ''' 163 '''
@@ -199,7 +195,7 @@ class PatternGenerator {
199 195
200 private pattern elementCloseWorld(element:DefinedElement) { 196 private pattern elementCloseWorld(element:DefinedElement) {
201 PartialInterpretation.openWorldElements(i,element); 197 PartialInterpretation.openWorldElements(i,element);
202 PartialInterpretation.maxNewElements(i,0); 198 PartialInterpretation.maxNewElements(i,0);
203 } or { 199 } or {
204 Scope.targetTypeInterpretation(scope,interpretation); 200 Scope.targetTypeInterpretation(scope,interpretation);
205 PartialTypeInterpratation.elements(interpretation,element); 201 PartialTypeInterpratation.elements(interpretation,element);
@@ -288,7 +284,9 @@ class PatternGenerator {
288 ////////// 284 //////////
289 // 1.1.1 Required Patterns by TypeIndexer 285 // 1.1.1 Required Patterns by TypeIndexer
290 ////////// 286 //////////
287
291 «typeIndexer.requiredQueries» 288 «typeIndexer.requiredQueries»
289
292 ////////// 290 //////////
293 // 1.1.2 primitive Type Indexers 291 // 1.1.2 primitive Type Indexers
294 ////////// 292 //////////
@@ -306,6 +304,7 @@ class PatternGenerator {
306 // > StringElement.value(variableName,value) 304 // > StringElement.value(variableName,value)
307 // Whether a value is set is defined by: 305 // Whether a value is set is defined by:
308 // > PrimitiveElement.valueSet(variableName,isFilled); 306 // > PrimitiveElement.valueSet(variableName,isFilled);
307
309 ////////// 308 //////////
310 // 1.1.3 domain-specific Type Indexers 309 // 1.1.3 domain-specific Type Indexers
311 ////////// 310 //////////
@@ -338,7 +337,7 @@ class PatternGenerator {
338 ////////// 337 //////////
339 // 3.1 Unfinishedness Measured by Multiplicity 338 // 3.1 Unfinishedness Measured by Multiplicity
340 ////////// 339 //////////
341 «unfinishedIndexer.generateUnfinishedMultiplicityQueries(problem,fqn2PQuery)» 340 «unfinishedIndexer.generateUnfinishedMultiplicityQueries(constraints.multiplicityConstraints,fqn2PQuery)»
342 341
343 ////////// 342 //////////
344 // 3.2 Unfinishedness Measured by WF Queries 343 // 3.2 Unfinishedness Measured by WF Queries
@@ -363,11 +362,18 @@ class PatternGenerator {
363 «relationRefinementGenerator.generateRefineReference(problem)» 362 «relationRefinementGenerator.generateRefineReference(problem)»
364 363
365 ////////// 364 //////////
366 // 5 Unit Propagations 365 // 5 Hints
366 //////////
367 «FOR hint : hints»
368 «hint.getAdditionalPatterns(this)»
369 «ENDFOR»
370
371 //////////
372 // 6 Unit Propagations
367 ////////// 373 //////////
368 ''' 374 '''
369 val up = unitPropagationPreconditionGenerator.generateUnitPropagationRules(problem,problem.relations.filter(RelationDefinition),fqn2PQuery) 375 val up = unitPropagationPreconditionGenerator.generateUnitPropagationRules(problem,problem.relations.filter(RelationDefinition),fqn2PQuery)
370 val second = up.definitions 376 val second = up.definitions
371 return new PatternGeneratorResult(first+second,up.constraint2MustPreconditionName,up.constraint2CurrentPreconditionName) 377 return new PatternGeneratorResult(first+second,up.constraint2MustPreconditionName,up.constraint2CurrentPreconditionName)
372 } 378 }
373} 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 f3de4ccc..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
@@ -2,78 +2,95 @@ package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns
2 2
3import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Relation 3import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Relation
4import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RelationDeclaration 4import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RelationDeclaration
5import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RelationDefinition
5import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type 6import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type
6import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem 7import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem
8import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality
7import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationStatistics 9import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationStatistics
8import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeAnalysis 10import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeAnalysis
9import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeAnalysisResult 11import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeAnalysisResult
10import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeInferenceMethod 12import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeInferenceMethod
13import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint
14import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.RelationConstraints
15import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.RelationMultiplicityConstraint
16import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy
11import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.util.ParseUtil 17import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.util.ParseUtil
12import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation 18import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
13import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace 19import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace
20import java.util.Collection
21import java.util.HashMap
14import java.util.Map 22import java.util.Map
23import java.util.Set
15import org.eclipse.viatra.query.runtime.api.IPatternMatch 24import org.eclipse.viatra.query.runtime.api.IPatternMatch
16import org.eclipse.viatra.query.runtime.api.IQuerySpecification 25import org.eclipse.viatra.query.runtime.api.IQuerySpecification
17import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher 26import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher
27import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint
18import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery 28import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery
19import org.eclipse.xtend.lib.annotations.Data 29import org.eclipse.xtend.lib.annotations.Data
20 30
21import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.* 31import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.*
22import java.util.Collection
23import java.util.Set
24import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint
25import java.util.HashMap
26 32
27@Data class GeneratedPatterns { 33@Data class GeneratedPatterns {
28 public Map<Relation, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> invalidWFQueries 34 public Map<Relation, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> invalidWFQueries
29 public Map<Relation, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedWFQueries 35 public Map<Relation, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedWFQueries
30 public Map<Relation, Pair<IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>,Integer>> unfinishedContainmentMulticiplicityQueries 36 public Map<RelationMultiplicityConstraint, UnifinishedMultiplicityQueries> multiplicityConstraintQueries
31 public Map<Relation, Pair<IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>,Integer>> unfinishedNonContainmentMulticiplicityQueries 37 public IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> hasElementInContainmentQuery
32 public Map<ObjectCreationPrecondition, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> refineObjectQueries 38 public Map<ObjectCreationPrecondition, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> refineObjectQueries
33 public Map<? extends Type, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> refineTypeQueries 39 public Map<? extends Type, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> refineTypeQueries
34 public Map<Pair<RelationDeclaration, Relation>, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> refinerelationQueries 40 public Map<Pair<RelationDeclaration, Relation>, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> refinerelationQueries
35 public Map<PConstraint, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> mustUnitPropagationPreconditionPatterns 41 public Map<PConstraint, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> mustUnitPropagationPreconditionPatterns
36 public Map<PConstraint, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> currentUnitPropagationPreconditionPatterns 42 public Map<PConstraint, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> currentUnitPropagationPreconditionPatterns
43 public Map<RelationDefinition, ModalPatternQueries> modalRelationQueries
37 public Collection<IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> allQueries 44 public Collection<IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> allQueries
38} 45}
39 46
47@Data
48class ModalPatternQueries {
49 val IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> mayQuery
50 val IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> mustQuery
51 val IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> currentQuery
52}
53
54@Data
55class UnifinishedMultiplicityQueries {
56 val IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> unfinishedMultiplicityQuery
57 val IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> unrepairableMultiplicityQuery
58 val IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> remainingInverseMultiplicityQuery
59 val IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> remainingContentsQuery
60}
61
40class PatternProvider { 62class PatternProvider {
41 63
42 val TypeAnalysis typeAnalysis = new TypeAnalysis 64 val TypeAnalysis typeAnalysis = new TypeAnalysis
43 65
44 public def generateQueries( 66 def generateQueries(LogicProblem problem, PartialInterpretation emptySolution, ModelGenerationStatistics statistics,
45 LogicProblem problem, 67 Set<PQuery> existingQueries, ReasonerWorkspace workspace, TypeInferenceMethod typeInferenceMethod,
46 PartialInterpretation emptySolution, 68 ScopePropagatorStrategy scopePropagatorStrategy, RelationConstraints relationConstraints,
47 ModelGenerationStatistics statistics, 69 Collection<LinearTypeConstraintHint> hints, boolean writeToFile) {
48 Set<PQuery> existingQueries,
49 ReasonerWorkspace workspace,
50 TypeInferenceMethod typeInferenceMethod,
51 boolean writeToFile)
52 {
53 val fqn2Query = existingQueries.toMap[it.fullyQualifiedName] 70 val fqn2Query = existingQueries.toMap[it.fullyQualifiedName]
54 val PatternGenerator patternGenerator = new PatternGenerator(typeInferenceMethod) 71 val PatternGenerator patternGenerator = new PatternGenerator(typeInferenceMethod, scopePropagatorStrategy)
55 val typeAnalysisResult = if(patternGenerator.requiresTypeAnalysis) { 72 val typeAnalysisResult = if (patternGenerator.requiresTypeAnalysis) {
56 val startTime = System.nanoTime 73 val startTime = System.nanoTime
57 val result = typeAnalysis.performTypeAnalysis(problem,emptySolution) 74 val result = typeAnalysis.performTypeAnalysis(problem, emptySolution)
58 val typeAnalysisTime = System.nanoTime - startTime 75 val typeAnalysisTime = System.nanoTime - startTime
59 statistics.PreliminaryTypeAnalisisTime = typeAnalysisTime 76 statistics.preliminaryTypeAnalisisTime = typeAnalysisTime
60 result 77 result
61 } else { 78 } else {
62 null 79 null
63 } 80 }
64 val patternGeneratorResult = patternGenerator.transformBaseProperties(problem,emptySolution,fqn2Query,typeAnalysisResult) 81 val patternGeneratorResult = patternGenerator.transformBaseProperties(problem, emptySolution, fqn2Query,
65 val baseIndexerFile = patternGeneratorResult.patternText 82 typeAnalysisResult, relationConstraints, hints)
66 val mustUnitPropagationTrace = patternGeneratorResult.constraint2MustPreconditionName 83 if (writeToFile) {
67 val currentUnitPropagationTrace = patternGeneratorResult.constraint2CurrentPreconditionName 84 workspace.writeText('''generated3valued.vql_deactivated''', patternGeneratorResult.patternText)
68 if(writeToFile) {
69 workspace.writeText('''generated3valued.vql_deactivated''',baseIndexerFile)
70 } 85 }
71 val ParseUtil parseUtil = new ParseUtil 86 val ParseUtil parseUtil = new ParseUtil
72 val generatedQueries = parseUtil.parse(baseIndexerFile) 87 val generatedQueries = parseUtil.parse(patternGeneratorResult.patternText)
73 val runtimeQueries = calclulateRuntimeQueries(patternGenerator,problem,emptySolution,typeAnalysisResult,mustUnitPropagationTrace,currentUnitPropagationTrace,generatedQueries); 88 val runtimeQueries = calclulateRuntimeQueries(patternGenerator, problem, emptySolution, typeAnalysisResult,
89 patternGeneratorResult.constraint2MustPreconditionName, patternGeneratorResult.constraint2CurrentPreconditionName,
90 relationConstraints, generatedQueries)
74 return runtimeQueries 91 return runtimeQueries
75 } 92 }
76 93
77 private def GeneratedPatterns calclulateRuntimeQueries( 94 private def GeneratedPatterns calclulateRuntimeQueries(
78 PatternGenerator patternGenerator, 95 PatternGenerator patternGenerator,
79 LogicProblem problem, 96 LogicProblem problem,
@@ -81,31 +98,23 @@ class PatternProvider {
81 TypeAnalysisResult typeAnalysisResult, 98 TypeAnalysisResult typeAnalysisResult,
82 HashMap<PConstraint, String> mustUnitPropagationTrace, 99 HashMap<PConstraint, String> mustUnitPropagationTrace,
83 HashMap<PConstraint, String> currentUnitPropagationTrace, 100 HashMap<PConstraint, String> currentUnitPropagationTrace,
101 RelationConstraints relationConstraints,
84 Map<String, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> queries 102 Map<String, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> queries
85 ) { 103 ) {
86 val Map<Relation, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> 104 val Map<Relation, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>>
87 invalidWFQueries = patternGenerator.invalidIndexer.getInvalidateByWfQueryNames(problem).mapValues[it.lookup(queries)] 105 invalidWFQueries = patternGenerator.invalidIndexer.getInvalidateByWfQueryNames(problem).mapValues[it.lookup(queries)]
88 val Map<Relation, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> 106 val Map<Relation, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>>
89 unfinishedWFQueries = patternGenerator.unfinishedIndexer.getUnfinishedWFQueryNames(problem).mapValues[it.lookup(queries)] 107 unfinishedWFQueries = patternGenerator.unfinishedIndexer.getUnfinishedWFQueryNames(problem).mapValues[it.lookup(queries)]
90 108
91 val unfinishedMultiplicities = patternGenerator.unfinishedIndexer.getUnfinishedMultiplicityQueries(problem) 109 val unfinishedMultiplicities = patternGenerator.unfinishedIndexer.getUnfinishedMultiplicityQueries(relationConstraints.multiplicityConstraints)
92 val unfinishedContainmentMultiplicities = new HashMap 110 val multiplicityConstraintQueries = unfinishedMultiplicities.mapValues [
93 val unfinishedNonContainmentMultiplicities = new HashMap 111 new UnifinishedMultiplicityQueries(unfinishedMultiplicityQueryName?.lookup(queries),
94 for(entry : unfinishedMultiplicities.entrySet) { 112 unrepairableMultiplicityQueryName?.lookup(queries),
95 val relation = entry.key 113 remainingInverseMultiplicityQueryName?.lookup(queries), remainingContentsQueryName?.lookup(queries))
96 val name = entry.value.key 114 ]
97 val amount = entry.value.value 115 val hasElementInContainmentQuery = patternGenerator.typeRefinementGenerator.hasElementInContainmentName.lookup(
98 val query = name.lookup(queries) 116 queries)
99 if(problem.containmentHierarchies.head.containmentRelations.contains(relation)) { 117
100 unfinishedContainmentMultiplicities.put(relation,query->amount)
101 } else {
102 unfinishedNonContainmentMultiplicities.put(relation,query->amount)
103 }
104 }
105// val Map<Relation, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>>
106// unfinishedMultiplicityQueries = patternGenerator.unfinishedIndexer.getUnfinishedMultiplicityQueries(problem).mapValues[it.lookup(queries)]
107//
108
109 val Map<ObjectCreationPrecondition, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> 118 val Map<ObjectCreationPrecondition, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>>
110 refineObjectsQueries = patternGenerator.typeRefinementGenerator.getRefineObjectQueryNames(problem,emptySolution,typeAnalysisResult).mapValues[it.lookup(queries)] 119 refineObjectsQueries = patternGenerator.typeRefinementGenerator.getRefineObjectQueryNames(problem,emptySolution,typeAnalysisResult).mapValues[it.lookup(queries)]
111 val Map<? extends Type, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> 120 val Map<? extends Type, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>>
@@ -116,16 +125,27 @@ class PatternProvider {
116 mustUnitPropagationPreconditionPatterns = mustUnitPropagationTrace.mapValues[it.lookup(queries)] 125 mustUnitPropagationPreconditionPatterns = mustUnitPropagationTrace.mapValues[it.lookup(queries)]
117 val Map<PConstraint, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> 126 val Map<PConstraint, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>>
118 currentUnitPropagationPreconditionPatterns = currentUnitPropagationTrace.mapValues[it.lookup(queries)] 127 currentUnitPropagationPreconditionPatterns = currentUnitPropagationTrace.mapValues[it.lookup(queries)]
128
129 val modalRelationQueries = problem.relations.filter(RelationDefinition).toMap([it], [ relationDefinition |
130 val indexer = patternGenerator.relationDefinitionIndexer
131 new ModalPatternQueries(
132 indexer.relationDefinitionName(relationDefinition, Modality.MAY).lookup(queries),
133 indexer.relationDefinitionName(relationDefinition, Modality.MUST).lookup(queries),
134 indexer.relationDefinitionName(relationDefinition, Modality.CURRENT).lookup(queries)
135 )
136 ])
137
119 return new GeneratedPatterns( 138 return new GeneratedPatterns(
120 invalidWFQueries, 139 invalidWFQueries,
121 unfinishedWFQueries, 140 unfinishedWFQueries,
122 unfinishedContainmentMultiplicities, 141 multiplicityConstraintQueries,
123 unfinishedNonContainmentMultiplicities, 142 hasElementInContainmentQuery,
124 refineObjectsQueries, 143 refineObjectsQueries,
125 refineTypeQueries, 144 refineTypeQueries,
126 refineRelationQueries, 145 refineRelationQueries,
127 mustUnitPropagationPreconditionPatterns, 146 mustUnitPropagationPreconditionPatterns,
128 currentUnitPropagationPreconditionPatterns, 147 currentUnitPropagationPreconditionPatterns,
148 modalRelationQueries,
129 queries.values 149 queries.values
130 ) 150 )
131 } 151 }
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 37950834..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
@@ -7,10 +7,10 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality
7import java.util.Map 7import java.util.Map
8import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable 8import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable
9import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.BinaryTransitiveClosure 9import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.BinaryTransitiveClosure
10import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PDisjunction
10import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery 11import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery
11 12
12import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.* 13import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.*
13import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PDisjunction
14 14
15class RelationDefinitionIndexer { 15class RelationDefinitionIndexer {
16 public val PatternGenerator base; 16 public val PatternGenerator base;
@@ -60,7 +60,7 @@ class RelationDefinitionIndexer {
60 ] 60 ]
61 } 61 }
62 62
63 private def relationDefinitionName(RelationDefinition relation, Modality modality) 63 def String relationDefinitionName(RelationDefinition relation, Modality modality)
64 '''«modality.name.toLowerCase»InRelation_«base.canonizeName(relation.name)»''' 64 '''«modality.name.toLowerCase»InRelation_«base.canonizeName(relation.name)»'''
65 65
66 def canonizeName(PVariable v) { 66 def canonizeName(PVariable v) {
@@ -102,6 +102,4 @@ class RelationDefinitionIndexer {
102 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) '''
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(',')»); 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(',')»);
104 ''' 104 '''
105
106
107} \ 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/RelationRefinementGenerator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/RelationRefinementGenerator.xtend
index f9e9baea..d915d47e 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/RelationRefinementGenerator.xtend
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/RelationRefinementGenerator.xtend
@@ -9,77 +9,71 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.ComplexTypeReference
9 9
10class RelationRefinementGenerator { 10class RelationRefinementGenerator {
11 PatternGenerator base; 11 PatternGenerator base;
12
12 public new(PatternGenerator base) { 13 public new(PatternGenerator base) {
13 this.base = base 14 this.base = base
14 } 15 }
15 16
16 def CharSequence generateRefineReference(LogicProblem p) { 17 def CharSequence generateRefineReference(LogicProblem p) '''
17 return ''' 18 «FOR relationRefinement : this.getRelationRefinements(p)»
18 «FOR relationRefinement: this.getRelationRefinements(p)» 19 pattern «relationRefinementQueryName(relationRefinement.key,relationRefinement.value)»(
19 pattern «relationRefinementQueryName(relationRefinement.key,relationRefinement.value)»( 20 problem:LogicProblem, interpretation:PartialInterpretation,
20 problem:LogicProblem, interpretation:PartialInterpretation, 21 relationIterpretation:PartialRelationInterpretation«IF relationRefinement.value !== null», oppositeInterpretation:PartialRelationInterpretation«ENDIF»,
21 relationIterpretation:PartialRelationInterpretation«IF relationRefinement.value != null», oppositeInterpretation:PartialRelationInterpretation«ENDIF», 22 from: DefinedElement, to: DefinedElement)
22 from: DefinedElement, to: DefinedElement) 23 {
23 { 24 find interpretation(problem,interpretation);
24 find interpretation(problem,interpretation); 25 PartialInterpretation.partialrelationinterpretation(interpretation,relationIterpretation);
25 PartialInterpretation.partialrelationinterpretation(interpretation,relationIterpretation); 26 PartialRelationInterpretation.interpretationOf.name(relationIterpretation,"«relationRefinement.key.name»");
26 PartialRelationInterpretation.interpretationOf.name(relationIterpretation,"«relationRefinement.key.name»"); 27 «IF relationRefinement.value !== null»
27 «IF relationRefinement.value != null» 28 PartialInterpretation.partialrelationinterpretation(interpretation,oppositeInterpretation);
28 PartialInterpretation.partialrelationinterpretation(interpretation,oppositeInterpretation); 29 PartialRelationInterpretation.interpretationOf.name(oppositeInterpretation,"«relationRefinement.value.name»");
29 PartialRelationInterpretation.interpretationOf.name(oppositeInterpretation,"«relationRefinement.value.name»"); 30 «ENDIF»
30 «ENDIF» 31 find mustExist(problem, interpretation, from);
31 find mustExist(problem, interpretation, from); 32 find mustExist(problem, interpretation, to);
32 find mustExist(problem, interpretation, to); 33 «base.typeIndexer.referInstanceOfByReference(relationRefinement.key.parameters.get(0), Modality::MUST,"from")»
33 «base.typeIndexer.referInstanceOfByReference(relationRefinement.key.parameters.get(0), Modality::MUST,"from")» 34 «base.typeIndexer.referInstanceOfByReference(relationRefinement.key.parameters.get(1), Modality::MUST,"to")»
34 «base.typeIndexer.referInstanceOfByReference(relationRefinement.key.parameters.get(1), Modality::MUST,"to")» 35 «base.relationDeclarationIndexer.referRelation(relationRefinement.key,"from","to",Modality.MAY)»
35 «base.relationDeclarationIndexer.referRelation(relationRefinement.key,"from","to",Modality.MAY)» 36 neg «base.relationDeclarationIndexer.referRelation(relationRefinement.key,"from","to",Modality.MUST)»
36 neg «base.relationDeclarationIndexer.referRelation(relationRefinement.key,"from","to",Modality.MUST)» 37 }
37 }
38 «ENDFOR» 38 «ENDFOR»
39 ''' 39 '''
40 } 40
41
42 def String relationRefinementQueryName(RelationDeclaration relation, Relation inverseRelation) { 41 def String relationRefinementQueryName(RelationDeclaration relation, Relation inverseRelation) {
43 '''«IF inverseRelation != null 42 '''«IF inverseRelation !== null»refineRelation_«base.canonizeName(relation.name)»_and_«base.canonizeName(inverseRelation.name)»«ELSE»refineRelation_«base.canonizeName(relation.name)»«ENDIF»'''
44 »refineRelation_«base.canonizeName(relation.name)»_and_«base.canonizeName(inverseRelation.name)»«
45 ELSE
46 »refineRelation_«base.canonizeName(relation.name)»«ENDIF»'''
47 } 43 }
48 44
49 def referRefinementQuery(RelationDeclaration relation, Relation inverseRelation, String relInterpretationName, 45 def referRefinementQuery(RelationDeclaration relation, Relation inverseRelation, String relInterpretationName,
50 String inverseInterpretationName, String sourceName, String targetName) 46 String inverseInterpretationName, String sourceName,
51 '''find «this.relationRefinementQueryName(relation,inverseRelation)»(problem, interpretation, «relInterpretationName», «IF inverseRelation != null»inverseInterpretationName, «ENDIF»«sourceName», «targetName»);''' 47 String targetName) '''find «this.relationRefinementQueryName(relation,inverseRelation)»(problem, interpretation, «relInterpretationName», «IF inverseRelation !== null»«inverseInterpretationName», «ENDIF»«sourceName», «targetName»);'''
52 48
53 def getRefineRelationQueries(LogicProblem p) { 49 def getRefineRelationQueries(LogicProblem p) {
54// val containmentRelations = p.containmentHierarchies.map[containmentRelations].flatten.toSet 50// val containmentRelations = p.containmentHierarchies.map[containmentRelations].flatten.toSet
55// p.relations.filter(RelationDeclaration).filter[!containmentRelations.contains(it)].toInvertedMap['''refineRelation_«base.canonizeName(it.name)»'''] 51// p.relations.filter(RelationDeclaration).filter[!containmentRelations.contains(it)].toInvertedMap['''refineRelation_«base.canonizeName(it.name)»''']
56 /* 52 /*
57 val res = new LinkedHashMap 53 * val res = new LinkedHashMap
58 for(relation: getRelationRefinements(p)) { 54 * for(relation: getRelationRefinements(p)) {
59 if(inverseRelations.containsKey(relation)) { 55 * if(inverseRelations.containsKey(relation)) {
60 val name = '''refineRelation_«base.canonizeName(relation.name)»_and_«base.canonizeName(inverseRelations.get(relation).name)»''' 56 * val name = '''refineRelation_«base.canonizeName(relation.name)»_and_«base.canonizeName(inverseRelations.get(relation).name)»'''
61 res.put(relation -> inverseRelations.get(relation),name) 57 * res.put(relation -> inverseRelations.get(relation),name)
62 } else { 58 * } else {
63 val name = '''refineRelation_«base.canonizeName(relation.name)»''' 59 * val name = '''refineRelation_«base.canonizeName(relation.name)»'''
64 res.put(relation -> null,name) 60 * res.put(relation -> null,name)
65 } 61 * }
66 } 62 * }
67 return res*/ 63 return res*/
68 64 getRelationRefinements(p).toInvertedMap[relationRefinementQueryName(it.key, it.value)]
69 getRelationRefinements(p).toInvertedMap[relationRefinementQueryName(it.key,it.value)]
70 } 65 }
71
72 66
73 def getRelationRefinements(LogicProblem p) { 67 def getRelationRefinements(LogicProblem p) {
74 val inverses = base.getInverseRelations(p) 68 val inverses = base.getInverseRelations(p)
75 val containments = base.getContainments(p) 69 val containments = base.getContainments(p)
76 val list = new LinkedList 70 val list = new LinkedList
77 for(relation : p.relations.filter(RelationDeclaration)) { 71 for (relation : p.relations.filter(RelationDeclaration)) {
78 if(!containments.contains(relation)) { 72 if (!containments.contains(relation)) {
79 if(inverses.containsKey(relation)) { 73 if (inverses.containsKey(relation)) {
80 val inverse = inverses.get(relation) 74 val inverse = inverses.get(relation)
81 if(!containments.contains(inverse)) { 75 if (!containments.contains(inverse)) {
82 if(base.isRepresentative(relation,inverse)) { 76 if (base.isRepresentative(relation, inverse)) {
83 list += (relation -> inverse) 77 list += (relation -> inverse)
84 } 78 }
85 } 79 }
@@ -90,4 +84,4 @@ class RelationRefinementGenerator {
90 } 84 }
91 return list 85 return list
92 } 86 }
93} \ No newline at end of file 87}
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 41eb75a8..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
@@ -1,54 +1,126 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns 1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns
2 2
3import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem
4import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type
5import org.eclipse.emf.ecore.EClass
6import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality
7import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
8import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeAnalysisResult
9import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.ComplexTypeReference
10import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.BoolTypeReference 3import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.BoolTypeReference
4import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.ComplexTypeReference
11import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.IntTypeReference 5import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.IntTypeReference
12import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RealTypeReference 6import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RealTypeReference
13import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.StringTypeReference 7import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.StringTypeReference
8import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type
9import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem
10import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality
11import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeAnalysisResult
12import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
14import java.math.BigDecimal 13import java.math.BigDecimal
14import org.eclipse.emf.ecore.EClass
15import org.eclipse.xtend.lib.annotations.Accessors
16import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor
15 17
18@FinalFieldsConstructor
16abstract class TypeIndexer { 19abstract class TypeIndexer {
17 public def CharSequence getRequiredQueries() 20 @Accessors(PROTECTED_GETTER) val PatternGenerator base
18 public def boolean requiresTypeAnalysis() 21
19 public def CharSequence generateInstanceOfQueries(LogicProblem problem,PartialInterpretation emptySolution,TypeAnalysisResult typeAnalysisResult) 22 def CharSequence getRequiredQueries() '''
20 public def CharSequence referInstanceOf(Type type, Modality modality, String variableName) 23 private pattern typeInterpretation(problem:LogicProblem, interpretation:PartialInterpretation, type:TypeDeclaration, typeInterpretation:PartialComplexTypeInterpretation) {
21 public def CharSequence referInstanceOf(EClass type, Modality modality, String variableName) 24 find interpretation(problem,interpretation);
22 25 LogicProblem.types(problem,type);
23 public def dispatch CharSequence referInstanceOfByReference(ComplexTypeReference reference, Modality modality, String variableName) { 26 PartialInterpretation.partialtypeinterpratation(interpretation,typeInterpretation);
24 reference.referred.referInstanceOf(modality,variableName) 27 PartialComplexTypeInterpretation.interpretationOf(typeInterpretation,type);
25 } 28 }
26 public def dispatch CharSequence referInstanceOfByReference(BoolTypeReference reference, Modality modality, String variableName) { 29
30 private pattern directInstanceOf(problem:LogicProblem, interpretation:PartialInterpretation, element:DefinedElement, type:Type) {
31 find interpretation(problem,interpretation);
32 LogicProblem.types(problem,type);
33 TypeDefinition.elements(type,element);
34 } or {
35 find interpretation(problem,interpretation);
36 find typeInterpretation(problem,interpretation,type,typeInterpretation);
37 PartialComplexTypeInterpretation.elements(typeInterpretation,element);
38 }
39
40 private pattern isPrimitive(element: PrimitiveElement) {
41 PrimitiveElement(element);
42 }
43 '''
44
45 def boolean requiresTypeAnalysis()
46
47 def CharSequence generateInstanceOfQueries(LogicProblem problem, PartialInterpretation emptySolution,
48 TypeAnalysisResult typeAnalysisResult) '''
49 «FOR type : problem.types»
50 «problem.generateMustInstenceOf(type, typeAnalysisResult)»
51 «problem.generateMayInstanceOf(type, typeAnalysisResult)»
52 «ENDFOR»
53 '''
54
55 protected def CharSequence generateMustInstenceOf(LogicProblem problem, Type type,
56 TypeAnalysisResult typeAnalysisResult) '''
57 /**
58 * An element must be an instance of type "«type.name»".
59 */
60 private pattern «patternName(type,Modality.MUST)»(problem:LogicProblem, interpretation:PartialInterpretation, element:DefinedElement) {
61 Type.name(type,"«type.name»");
62 find directInstanceOf(problem,interpretation,element,type);
63 }
64 '''
65
66 protected def CharSequence generateMayInstanceOf(LogicProblem problem, Type type,
67 TypeAnalysisResult typeAnalysisResult)
68
69 protected def patternName(Type type,
70 Modality modality) '''«modality.toBase»InstanceOf«base.canonizeName(type.name)»'''
71
72 def referInstanceOf(Type type, Modality modality, String variableName) {
73 '''find «patternName(type,modality)»(problem,interpretation,«variableName»);'''
74 }
75
76 def referInstanceOf(EClass type, Modality modality, String variableName) {
77 '''find «modality.toBase»InstanceOf«base.canonizeName('''«type.name» class''')»(problem,interpretation,«variableName»);'''
78 }
79
80 def dispatch CharSequence referInstanceOfByReference(ComplexTypeReference reference, Modality modality,
81 String variableName) {
82 reference.referred.referInstanceOf(modality, variableName)
83 }
84
85 def dispatch CharSequence referInstanceOfByReference(BoolTypeReference reference, Modality modality,
86 String variableName) {
27 '''BooleanElement(«variableName»);''' 87 '''BooleanElement(«variableName»);'''
28 } 88 }
29 public def dispatch CharSequence referInstanceOfByReference(IntTypeReference reference, Modality modality, String variableName) { 89
90 def dispatch CharSequence referInstanceOfByReference(IntTypeReference reference, Modality modality,
91 String variableName) {
30 '''IntegerElement(«variableName»);''' 92 '''IntegerElement(«variableName»);'''
31 } 93 }
32 public def dispatch CharSequence referInstanceOfByReference(RealTypeReference reference, Modality modality, String variableName) { 94
95 def dispatch CharSequence referInstanceOfByReference(RealTypeReference reference, Modality modality,
96 String variableName) {
33 '''RealElement(«variableName»);''' 97 '''RealElement(«variableName»);'''
34 } 98 }
35 public def dispatch CharSequence referInstanceOfByReference(StringTypeReference reference, Modality modality, String variableName) { 99
100 def dispatch CharSequence referInstanceOfByReference(StringTypeReference reference, Modality modality,
101 String variableName) {
36 '''StringElement(«variableName»);''' 102 '''StringElement(«variableName»);'''
37 } 103 }
38 public def dispatch CharSequence referPrimitiveValue(String variableName, Boolean value) { 104
105 def dispatch CharSequence referPrimitiveValue(String variableName, Boolean value) {
39 '''BooleanElement.value(«variableName»,«value»);''' 106 '''BooleanElement.value(«variableName»,«value»);'''
40 } 107 }
41 public def dispatch CharSequence referPrimitiveValue(String variableName, Integer value) { 108
109 def dispatch CharSequence referPrimitiveValue(String variableName, Integer value) {
42 '''IntegerElement.value(«variableName»,«value»);''' 110 '''IntegerElement.value(«variableName»,«value»);'''
43 } 111 }
44 public def dispatch CharSequence referPrimitiveValue(String variableName, BigDecimal value) { 112
113 def dispatch CharSequence referPrimitiveValue(String variableName, BigDecimal value) {
45 '''RealElement.value(«variableName»,«value»);''' 114 '''RealElement.value(«variableName»,«value»);'''
46 } 115 }
47 ///TODO: de-escaping string literals 116
48 public def dispatch CharSequence referPrimitiveValue(String variableName, String value) { 117 def dispatch CharSequence referPrimitiveValue(String variableName, String value) {
118 // /TODO: de-escaping string literals
49 '''StringElement.value(«variableName»,"«value»");''' 119 '''StringElement.value(«variableName»,"«value»");'''
50 } 120 }
51 public def CharSequence referPrimitiveFilled(String variableName, boolean isFilled) { 121
122 def CharSequence referPrimitiveFilled(String variableName, boolean isFilled) {
52 '''PrimitiveElement.valueSet(«variableName»,«isFilled»);''' 123 '''PrimitiveElement.valueSet(«variableName»,«isFilled»);'''
53 } 124 }
54} \ No newline at end of file 125}
126
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/TypeIndexerWithPreliminaryTypeAnalysis.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/TypeIndexerWithPreliminaryTypeAnalysis.xtend
index d3af0426..0393b803 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/TypeIndexerWithPreliminaryTypeAnalysis.xtend
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/TypeIndexerWithPreliminaryTypeAnalysis.xtend
@@ -4,113 +4,51 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type
4import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem 4import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem
5import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality 5import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality
6import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeAnalysisResult 6import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeAnalysisResult
7import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeRefinementPrecondition
8import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
9import org.eclipse.emf.ecore.EClass
10 7
11class TypeIndexerWithPreliminaryTypeAnalysis extends TypeIndexer{ 8class TypeIndexerWithPreliminaryTypeAnalysis extends TypeIndexer {
12 val PatternGenerator base;
13
14 new(PatternGenerator base) { 9 new(PatternGenerator base) {
15 this.base = base 10 super(base)
16 } 11 }
12
17 override requiresTypeAnalysis() { true } 13 override requiresTypeAnalysis() { true }
18 14
19 override getRequiredQueries() ''' 15 protected override generateMayInstanceOf(LogicProblem problem, Type type, TypeAnalysisResult typeAnalysisResult) {
20 private pattern typeInterpretation(problem:LogicProblem, interpretation:PartialInterpretation, type:TypeDeclaration, typeInterpretation:PartialComplexTypeInterpretation) { 16 val precondition = typeAnalysisResult?.mayNewTypePreconditions?.get(type)
21 find interpretation(problem,interpretation); 17 val inhibitorTypes = precondition?.inhibitorTypes
22 LogicProblem.types(problem,type);
23 PartialInterpretation.partialtypeinterpratation(interpretation,typeInterpretation);
24 PartialComplexTypeInterpretation.interpretationOf(typeInterpretation,type);
25 }
26
27 private pattern directInstanceOf(problem:LogicProblem, interpretation:PartialInterpretation, element:DefinedElement, type:Type) {
28 find interpretation(problem,interpretation);
29 LogicProblem.types(problem,type);
30 TypeDefinition.elements(type,element);
31 } or {
32 find interpretation(problem,interpretation);
33 find typeInterpretation(problem,interpretation,type,typeInterpretation);
34 PartialComplexTypeInterpretation.elements(typeInterpretation,element);
35 }
36
37 private pattern isPrimitive(element: PrimitiveElement) {
38 PrimitiveElement(element);
39 }
40 '''
41
42 override generateInstanceOfQueries(LogicProblem problem, PartialInterpretation emptySolution, TypeAnalysisResult typeAnalysisResult) {
43 val mayNewTypePreconditions = typeAnalysisResult.mayNewTypePreconditions
44
45 return '''
46 «FOR type:problem.types»
47 «problem.generateMustInstenceOf(type)»
48 «problem.generateMayInstanceOf(type,mayNewTypePreconditions.get(type))»
49 «ENDFOR»
50 '''
51 }
52
53 private def patternName(Type type, Modality modality)
54 '''«modality.toString.toLowerCase»InstanceOf«base.canonizeName(type.name)»'''
55
56 private def generateMustInstenceOf(LogicProblem problem, Type type) {
57 '''
58 /**
59 * An element must be an instance of type "«type.name»".
60 */
61 private pattern «patternName(type,Modality.MUST)»(problem:LogicProblem, interpretation:PartialInterpretation, element:DefinedElement) {
62 Type.name(type,"«type.name»");
63 find directInstanceOf(problem,interpretation,element,type);
64 }
65 '''
66 }
67
68 private def generateMayInstanceOf(LogicProblem problem, Type type, TypeRefinementPrecondition precondition) {
69 val inhibitorTypes = if(precondition!=null) {
70 precondition.inhibitorTypes
71 } else {
72 null
73 }
74 ''' 18 '''
75 private pattern scopeDisallowsNew«base.canonizeName(type.name)»(problem:LogicProblem, interpretation:PartialInterpretation) { 19 private pattern scopeDisallowsNew«base.canonizeName(type.name)»(problem:LogicProblem, interpretation:PartialInterpretation) {
76 find interpretation(problem,interpretation); 20 find interpretation(problem,interpretation);
77 PartialInterpretation.scopes(interpretation,scope); 21 PartialInterpretation.scopes(interpretation,scope);
78 Scope.targetTypeInterpretation(scope,typeInterpretation); 22 Scope.targetTypeInterpretation(scope,typeInterpretation);
79 Scope.maxNewElements(scope,0); 23 Scope.maxNewElements(scope,0);
80 PartialComplexTypeInterpretation.interpretationOf(typeInterpretation,type); 24 PartialComplexTypeInterpretation.interpretationOf(typeInterpretation,type);
81 Type.name(type,"«type.name»"); 25 Type.name(type,"«type.name»");
82 } 26 }
83 27
84 /** 28 /**
85 * An element may be an instance of type "«type.name»". 29 * An element may be an instance of type "«type.name»".
86 */ 30 */
87 private pattern «patternName(type,Modality.MAY)»(problem:LogicProblem, interpretation:PartialInterpretation, element:DefinedElement) 31 private pattern «patternName(type,Modality.MAY)»(problem:LogicProblem, interpretation:PartialInterpretation, element:DefinedElement)
88 «IF inhibitorTypes !== null»{ 32 «IF inhibitorTypes !== null»
89 find interpretation(problem,interpretation); 33 {
90 PartialInterpretation.newElements(interpretation,element); 34 find interpretation(problem,interpretation);
91 «FOR inhibitorType : inhibitorTypes» 35 PartialInterpretation.newElements(interpretation,element);
92 neg «referInstanceOf(inhibitorType,Modality.MUST,"element")» 36 «FOR inhibitorType : inhibitorTypes»
93 «ENDFOR» 37 neg «referInstanceOf(inhibitorType,Modality.MUST,"element")»
94 neg find scopeDisallowsNew«base.canonizeName(type.name)»(problem, interpretation); 38 «ENDFOR»
95 neg find isPrimitive(element); 39 neg find scopeDisallowsNew«base.canonizeName(type.name)»(problem, interpretation);
96 } or { 40 neg find isPrimitive(element);
97 find interpretation(problem,interpretation); 41 } or {
98 PartialInterpretation.openWorldElements(interpretation,element); 42 find interpretation(problem,interpretation);
99 «FOR inhibitorType : inhibitorTypes» 43 PartialInterpretation.openWorldElements(interpretation,element);
100 neg «referInstanceOf(inhibitorType,Modality.MUST,"element")» 44 «FOR inhibitorType : inhibitorTypes»
101 «ENDFOR» 45 neg «referInstanceOf(inhibitorType,Modality.MUST,"element")»
102 neg find scopeDisallowsNew«base.canonizeName(type.name)»(problem, interpretation); 46 «ENDFOR»
103 neg find isPrimitive(element); 47 neg find scopeDisallowsNew«base.canonizeName(type.name)»(problem, interpretation);
104 } or 48 neg find isPrimitive(element);
105 «ENDIF» 49 } or
106 { «referInstanceOf(type,Modality.MUST,"element")» } 50 «ENDIF»
51 { «referInstanceOf(type,Modality.MUST,"element")» }
107 ''' 52 '''
108 } 53 }
109 54}
110 public override referInstanceOf(Type type, Modality modality, String variableName) {
111 '''find «patternName(type,modality)»(problem,interpretation,«variableName»);'''
112 }
113 public override referInstanceOf(EClass type, Modality modality, String variableName) {
114 '''find «modality.toString.toLowerCase»InstanceOf«base.canonizeName('''«type.name» class''')»(problem,interpretation,«variableName»);'''
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/TypeRefinementGenerator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/TypeRefinementGenerator.xtend
index 7e3fad91..4ef336ae 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/TypeRefinementGenerator.xtend
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/TypeRefinementGenerator.xtend
@@ -25,69 +25,76 @@ class ObjectCreationPrecondition {
25 25
26abstract class TypeRefinementGenerator { 26abstract class TypeRefinementGenerator {
27 val protected PatternGenerator base; 27 val protected PatternGenerator base;
28 public new(PatternGenerator base) { 28
29 new(PatternGenerator base) {
29 this.base = base 30 this.base = base
30 } 31 }
31 32
32 public def boolean requiresTypeAnalysis() 33 def boolean requiresTypeAnalysis()
33 public def CharSequence generateRefineObjectQueries(LogicProblem p, PartialInterpretation emptySolution, TypeAnalysisResult typeAnalysisResult) 34
34 public def CharSequence generateRefineTypeQueries(LogicProblem p, PartialInterpretation emptySolution, TypeAnalysisResult typeAnalysisResult) 35 def CharSequence generateRefineObjectQueries(LogicProblem p, PartialInterpretation emptySolution,
35 public def Map<? extends Type, String> getRefineTypeQueryNames(LogicProblem p, PartialInterpretation emptySolution, TypeAnalysisResult typeAnalysisResult) 36 TypeAnalysisResult typeAnalysisResult)
36 37
37 public def getRefineObjectQueryNames(LogicProblem p, PartialInterpretation emptySolution, TypeAnalysisResult typeAnalysisResult) { 38 def CharSequence generateRefineTypeQueries(LogicProblem p, PartialInterpretation emptySolution,
38 val Map<ObjectCreationPrecondition,String> objectCreationQueries = new LinkedHashMap 39 TypeAnalysisResult typeAnalysisResult)
40
41 def Map<? extends Type, String> getRefineTypeQueryNames(LogicProblem p, PartialInterpretation emptySolution,
42 TypeAnalysisResult typeAnalysisResult)
43
44 def getRefineObjectQueryNames(LogicProblem p, PartialInterpretation emptySolution,
45 TypeAnalysisResult typeAnalysisResult) {
46 val Map<ObjectCreationPrecondition, String> objectCreationQueries = new LinkedHashMap
39 val containment = p.containmentHierarchies.head 47 val containment = p.containmentHierarchies.head
40 val inverseRelations = new HashMap 48 val inverseRelations = new HashMap
41 p.annotations.filter(InverseRelationAssertion).forEach[ 49 p.annotations.filter(InverseRelationAssertion).forEach [
42 inverseRelations.put(it.inverseA,it.inverseB) 50 inverseRelations.put(it.inverseA, it.inverseB)
43 inverseRelations.put(it.inverseB,it.inverseA) 51 inverseRelations.put(it.inverseB, it.inverseA)
44 ] 52 ]
45 for(type: p.types.filter(TypeDeclaration).filter[!it.isAbstract]) { 53 for (type : p.types.filter(TypeDeclaration).filter[!it.isAbstract]) {
46 if(containment.typeInContainment(type)) { 54 if (containment.typeInContainment(type)) {
47 for(containmentRelation : containment.containmentRelations.filter[canBeContainedByRelation(it,type)]) { 55 for (containmentRelation : containment.containmentRelations.
48 if(inverseRelations.containsKey(containmentRelation)) { 56 filter[canBeContainedByRelation(it, type)]) {
57 if (inverseRelations.containsKey(containmentRelation)) {
49 objectCreationQueries.put( 58 objectCreationQueries.put(
50 new ObjectCreationPrecondition(containmentRelation,inverseRelations.get(containmentRelation),type), 59 new ObjectCreationPrecondition(containmentRelation,
51 this.patternName(containmentRelation,inverseRelations.get(containmentRelation),type)) 60 inverseRelations.get(containmentRelation), type),
61 this.patternName(containmentRelation, inverseRelations.get(containmentRelation), type))
52 } else { 62 } else {
53 objectCreationQueries.put( 63 objectCreationQueries.put(new ObjectCreationPrecondition(containmentRelation, null, type),
54 new ObjectCreationPrecondition(containmentRelation,null,type), 64 patternName(containmentRelation, null, type))
55 patternName(containmentRelation,null,type))
56 } 65 }
57 } 66 }
58 objectCreationQueries.put( 67 objectCreationQueries.put(new ObjectCreationPrecondition(null, null, type),
59 new ObjectCreationPrecondition(null,null,type), 68 patternName(null, null, type))
60 patternName(null,null,type))
61 } else { 69 } else {
62 objectCreationQueries.put( 70 objectCreationQueries.put(new ObjectCreationPrecondition(null, null, type),
63 new ObjectCreationPrecondition(null,null,type), 71 this.patternName(null, null, type))
64 this.patternName(null,null,type))
65 } 72 }
66 } 73 }
67 return objectCreationQueries 74 return objectCreationQueries
68 } 75 }
69 76
70 protected def canBeContainedByRelation(Relation r, Type t) { 77 protected def canBeContainedByRelation(Relation r, Type t) {
71 if(r.parameters.size==2) { 78 if (r.parameters.size == 2) {
72 val param = r.parameters.get(1) 79 val param = r.parameters.get(1)
73 if(param instanceof ComplexTypeReference) { 80 if (param instanceof ComplexTypeReference) {
74 val allSuperTypes = t.transitiveClosureStar[it.supertypes] 81 val allSuperTypes = t.transitiveClosureStar[it.supertypes]
75 for(superType : allSuperTypes) { 82 for (superType : allSuperTypes) {
76 if(param.referred == superType) return true 83 if(param.referred == superType) return true
77 } 84 }
78 } 85 }
79 } 86 }
80 return false 87 return false
81 } 88 }
82 89
83 private def typeInContainment(ContainmentHierarchy hierarchy, Type type) { 90 private def typeInContainment(ContainmentHierarchy hierarchy, Type type) {
84 val allSuperTypes = type.transitiveClosureStar[it.supertypes] 91 val allSuperTypes = type.transitiveClosureStar[it.supertypes]
85 return allSuperTypes.exists[hierarchy.typesOrderedInHierarchy.contains(it)] 92 return allSuperTypes.exists[hierarchy.typesOrderedInHierarchy.contains(it)]
86 } 93 }
87 94
88 protected def String patternName(Relation containmentRelation, Relation inverseContainment, Type newType) { 95 protected def String patternName(Relation containmentRelation, Relation inverseContainment, Type newType) {
89 if(containmentRelation != null) { 96 if (containmentRelation !== null) {
90 if(inverseContainment != null) { 97 if (inverseContainment !== null) {
91 '''createObject_«base.canonizeName(newType.name)»_by_«base.canonizeName(containmentRelation.name)»_with_«base.canonizeName(inverseContainment.name)»''' 98 '''createObject_«base.canonizeName(newType.name)»_by_«base.canonizeName(containmentRelation.name)»_with_«base.canonizeName(inverseContainment.name)»'''
92 } else { 99 } else {
93 '''createObject_«base.canonizeName(newType.name)»_by_«base.canonizeName(containmentRelation.name)»''' 100 '''createObject_«base.canonizeName(newType.name)»_by_«base.canonizeName(containmentRelation.name)»'''
@@ -96,4 +103,8 @@ abstract class TypeRefinementGenerator {
96 '''createObject_«base.canonizeName(newType.name)»''' 103 '''createObject_«base.canonizeName(newType.name)»'''
97 } 104 }
98 } 105 }
99} \ No newline at end of file 106
107 def hasElementInContainmentName() {
108 "hasElementInContainment"
109 }
110}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/TypeRefinementWithPreliminaryTypeAnalysis.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/TypeRefinementWithPreliminaryTypeAnalysis.xtend
index cbbbcb08..1a81695e 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/TypeRefinementWithPreliminaryTypeAnalysis.xtend
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/TypeRefinementWithPreliminaryTypeAnalysis.xtend
@@ -10,7 +10,7 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.par
10import java.util.HashMap 10import java.util.HashMap
11 11
12class TypeRefinementWithPreliminaryTypeAnalysis extends TypeRefinementGenerator{ 12class TypeRefinementWithPreliminaryTypeAnalysis extends TypeRefinementGenerator{
13 public new(PatternGenerator base) { 13 new(PatternGenerator base) {
14 super(base) 14 super(base)
15 } 15 }
16 override requiresTypeAnalysis() { true } 16 override requiresTypeAnalysis() { true }
@@ -24,7 +24,7 @@ class TypeRefinementWithPreliminaryTypeAnalysis extends TypeRefinementGenerator{
24 inverseRelations.put(it.inverseB,it.inverseA) 24 inverseRelations.put(it.inverseB,it.inverseA)
25 ] 25 ]
26 return ''' 26 return '''
27 private pattern hasElementInContainment(problem:LogicProblem, interpretation:PartialInterpretation) 27 pattern «hasElementInContainmentName»(problem:LogicProblem, interpretation:PartialInterpretation)
28 «FOR type :containment.typesOrderedInHierarchy SEPARATOR "or"»{ 28 «FOR type :containment.typesOrderedInHierarchy SEPARATOR "or"»{
29 find interpretation(problem,interpretation); 29 find interpretation(problem,interpretation);
30 «base.typeIndexer.referInstanceOf(type,Modality.MUST,"root")» 30 «base.typeIndexer.referInstanceOf(type,Modality.MUST,"root")»
@@ -76,7 +76,7 @@ class TypeRefinementWithPreliminaryTypeAnalysis extends TypeRefinementGenerator{
76 typeInterpretation:PartialComplexTypeInterpretation) 76 typeInterpretation:PartialComplexTypeInterpretation)
77 { 77 {
78 find interpretation(problem,interpretation); 78 find interpretation(problem,interpretation);
79 neg find hasElementInContainment(problem,interpretation); 79 neg find «hasElementInContainmentName»(problem,interpretation);
80 PartialInterpretation.partialtypeinterpratation(interpretation,typeInterpretation); 80 PartialInterpretation.partialtypeinterpratation(interpretation,typeInterpretation);
81 PartialComplexTypeInterpretation.interpretationOf.name(typeInterpretation,"«type.name»"); 81 PartialComplexTypeInterpretation.interpretationOf.name(typeInterpretation,"«type.name»");
82 «base.typeIndexer.referInstanceOf(type,Modality.MAY,"newObject")» 82 «base.typeIndexer.referInstanceOf(type,Modality.MAY,"newObject")»
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/UnfinishedIndexer.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/UnfinishedIndexer.xtend
index 1df402fa..a8a07756 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/UnfinishedIndexer.xtend
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/UnfinishedIndexer.xtend
@@ -1,85 +1,204 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns 1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns
2 2
3import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.LowerMultiplicityAssertion 3import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RelationDeclaration
4import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem 4import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem
5import hu.bme.mit.inf.dslreasoner.viatra2logic.viatra2logicannotations.TransformedViatraWellformednessConstraint 5import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality
6import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.RelationMultiplicityConstraint
7import java.util.LinkedHashMap
8import java.util.List
6import java.util.Map 9import java.util.Map
7import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery 10import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery
11import org.eclipse.xtend.lib.annotations.Data
8 12
9import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.* 13import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.*
10import java.util.LinkedHashMap 14
11import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality 15@Data
12import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.ComplexTypeReference 16class UnifinishedMultiplicityQueryNames {
17 val String unfinishedMultiplicityQueryName
18 val String unrepairableMultiplicityQueryName
19 val String remainingInverseMultiplicityQueryName
20 val String remainingContentsQueryName
21}
13 22
14class UnfinishedIndexer { 23class UnfinishedIndexer {
15 val PatternGenerator base 24 val PatternGenerator base
16 25 val boolean indexUpperMultiplicities
17 new(PatternGenerator patternGenerator) { 26
27 new(PatternGenerator patternGenerator, boolean indexUpperMultiplicities) {
18 this.base = patternGenerator 28 this.base = patternGenerator
29 this.indexUpperMultiplicities = indexUpperMultiplicities
19 } 30 }
20 31
21 def generateUnfinishedWfQueries(LogicProblem problem, Map<String,PQuery> fqn2PQuery) { 32 def generateUnfinishedWfQueries(LogicProblem problem, Map<String, PQuery> fqn2PQuery) {
22 val wfQueries = base.wfQueries(problem) 33 val wfQueries = base.wfQueries(problem)
23 ''' 34 '''
24 «FOR wfQuery: wfQueries» 35 «FOR wfQuery : wfQueries»
25 pattern unfinishedBy_«base.canonizeName(wfQuery.target.name)»(problem:LogicProblem, interpretation:PartialInterpretation, 36 pattern unfinishedBy_«base.canonizeName(wfQuery.target.name)»(problem:LogicProblem, interpretation:PartialInterpretation,
26 «FOR param : wfQuery.patternFullyQualifiedName.lookup(fqn2PQuery).parameters SEPARATOR ', '»var_«param.name»«ENDFOR») 37 «FOR param : wfQuery.patternFullyQualifiedName.lookup(fqn2PQuery).parameters SEPARATOR ', '»var_«param.name»«ENDFOR»)
27 { 38 {
28 «base.relationDefinitionIndexer.referPattern( 39 «base.relationDefinitionIndexer.referPattern(
29 wfQuery.patternFullyQualifiedName.lookup(fqn2PQuery), 40 wfQuery.patternFullyQualifiedName.lookup(fqn2PQuery),
30 wfQuery.patternFullyQualifiedName.lookup(fqn2PQuery).parameters.map['''var_«it.name»'''], 41 wfQuery.patternFullyQualifiedName.lookup(fqn2PQuery).parameters.map['''var_«it.name»'''],
31 Modality.CURRENT, 42 Modality.CURRENT,
32 true,false)» 43 true,false)»
33 } 44 }
34 «ENDFOR» 45 «ENDFOR»
35 ''' 46 '''
36 } 47 }
48
37 def getUnfinishedWFQueryNames(LogicProblem problem) { 49 def getUnfinishedWFQueryNames(LogicProblem problem) {
38 val wfQueries = base.wfQueries(problem) 50 val wfQueries = base.wfQueries(problem)
39 val map = new LinkedHashMap 51 val map = new LinkedHashMap
40 for(wfQuery : wfQueries) { 52 for (wfQuery : wfQueries) {
41 map.put(wfQuery.target,'''unfinishedBy_«base.canonizeName(wfQuery.target.name)»''') 53 map.put(wfQuery.target, '''unfinishedBy_«base.canonizeName(wfQuery.target.name)»''')
42 } 54 }
43 return map 55 return map
44 } 56 }
45 def generateUnfinishedMultiplicityQueries(LogicProblem problem, Map<String,PQuery> fqn2PQuery) { 57
46 val lowerMultiplicities = base.lowerMultiplicities(problem) 58 def generateUnfinishedMultiplicityQueries(List<RelationMultiplicityConstraint> constraints,
47 return ''' 59 Map<String, PQuery> fqn2PQuery) '''
48 «FOR lowerMultiplicity : lowerMultiplicities» 60 «FOR constraint : constraints»
49 pattern «unfinishedMultiplicityName(lowerMultiplicity)»(problem:LogicProblem, interpretation:PartialInterpretation, relationIterpretation:PartialRelationInterpretation, object:DefinedElement,numberOfExistingReferences) { 61 «IF constraint.constrainsUnfinished»
50 find interpretation(problem,interpretation); 62 private pattern «unfinishedMultiplicityName(constraint)»_helper(problem:LogicProblem, interpretation:PartialInterpretation, object:DefinedElement, missingMultiplicity:java Integer) {
51 PartialInterpretation.partialrelationinterpretation(interpretation,relationIterpretation); 63 find interpretation(problem,interpretation);
52 PartialRelationInterpretation.interpretationOf.name(relationIterpretation,"«lowerMultiplicity.relation.name»"); 64 find mustExist(problem,interpretation,object);
53 «base.typeIndexer.referInstanceOf(lowerMultiplicity.firstParamTypeOfRelation,Modality::MUST,"object")» 65 «base.typeIndexer.referInstanceOf(constraint.sourceType,Modality::MUST,"object")»
54 numberOfExistingReferences == count «base.referRelation(lowerMultiplicity.relation,"object","_",Modality.MUST,fqn2PQuery)» 66 numberOfExistingReferences == count «base.referRelation(constraint.relation,"object","_",Modality.MUST,fqn2PQuery)»
55««« numberOfExistingReferences < «lowerMultiplicity.lower»; 67 check(numberOfExistingReferences < «constraint.lowerBound»);
56««« missingMultiplicity == eval(«lowerMultiplicity.lower»-numberOfExistingReferences); 68 missingMultiplicity == eval(«constraint.lowerBound»-numberOfExistingReferences);
57 } 69 }
70
71 pattern «unfinishedMultiplicityName(constraint)»(problem:LogicProblem, interpretation:PartialInterpretation, missingMultiplicity:java Integer) {
72 find interpretation(problem,interpretation);
73 missingMultiplicity == sum find «unfinishedMultiplicityName(constraint)»_helper(problem, interpretation, _, #_);
74 }
75 «ENDIF»
76
77 «IF indexUpperMultiplicities»
78 «IF constraint.constrainsUnrepairable || constraint.constrainsRemainingInverse»
79 private pattern «repairMatchName(constraint)»(problem:LogicProblem, interpretation:PartialInterpretation, source:DefinedElement, target:DefinedElement) {
80 «IF base.isRepresentative(constraint.relation, constraint.inverseRelation) && constraint.relation instanceof RelationDeclaration»
81 «base.relationRefinementGenerator.referRefinementQuery(constraint.relation as RelationDeclaration, constraint.inverseRelation, "_", "_", "source", "target")»
82 «ELSE»
83 «IF base.isRepresentative(constraint.inverseRelation, constraint.relation) && constraint.inverseRelation instanceof RelationDeclaration»
84 «base.relationRefinementGenerator.referRefinementQuery(constraint.inverseRelation as RelationDeclaration, constraint.relation, "_", "_", "target", "source")»
85 «ELSE»
86 find interpretation(problem,interpretation);
87 find mustExist(problem,interpretation,source);
88 «base.typeIndexer.referInstanceOf(constraint.sourceType,Modality::MUST,"source")»
89 find mustExist(problem,interpretation,target);
90 «base.typeIndexer.referInstanceOf(constraint.targetType,Modality::MUST,"target")»
91 neg «base.referRelation(constraint.relation,"source","target",Modality.MUST,fqn2PQuery)»
92 «base.referRelation(constraint.relation,"source","target",Modality.MAY,fqn2PQuery)»
93 «ENDIF»
94 «ENDIF»
95 }
96 «ENDIF»
97
98 «IF constraint.constrainsUnrepairable»
99 private pattern «unrepairableMultiplicityName(constraint)»_helper(problem:LogicProblem, interpretation:PartialInterpretation, object:DefinedElement, unrepairableMultiplicity:java Integer) {
100 find «unfinishedMultiplicityName(constraint)»_helper(problem, interpretation, object, missingMultiplicity);
101 numberOfRepairMatches == count find «repairMatchName(constraint)»(problem, interpretation, object, _);
102 check(numberOfRepairMatches < missingMultiplicity);
103 unrepairableMultiplicity == eval(missingMultiplicity-numberOfRepairMatches);
104 }
105
106 private pattern «unrepairableMultiplicityName(constraint)»(problem:LogicProblem, interpretation:PartialInterpretation, unrepairableMultiplicity:java Integer) {
107 find interpretation(problem,interpretation);
108 unrepairableMultiplicity == max find «unrepairableMultiplicityName(constraint)»_helper(problem, interpretation, _, #_);
109 } or {
110 find interpretation(problem,interpretation);
111 neg find «unrepairableMultiplicityName(constraint)»_helper(problem, interpretation, _, _);
112 unrepairableMultiplicity == 0;
113 }
114 «ENDIF»
115
116 «IF constraint.constrainsRemainingInverse»
117 private pattern «remainingMultiplicityName(constraint)»_helper(problem:LogicProblem, interpretation:PartialInterpretation, object:DefinedElement, remainingMultiplicity:java Integer) {
118 find interpretation(problem,interpretation);
119 find mustExist(problem,interpretation,object);
120 «base.typeIndexer.referInstanceOf(constraint.targetType,Modality::MUST,"object")»
121 numberOfExistingReferences == count «base.referRelation(constraint.relation,"_","object",Modality.MUST,fqn2PQuery)»
122 check(numberOfExistingReferences < «constraint.inverseUpperBound»);
123 numberOfRepairMatches == count find «repairMatchName(constraint)»(problem, interpretation, _, object);
124 remainingMultiplicity == eval(Math.min(«constraint.inverseUpperBound»-numberOfExistingReferences, numberOfRepairMatches));
125 }
126
127 pattern «remainingMultiplicityName(constraint)»(problem:LogicProblem, interpretation:PartialInterpretation, remainingMultiplicity:java Integer) {
128 find interpretation(problem,interpretation);
129 remainingMultiplicity == sum find «remainingMultiplicityName(constraint)»_helper(problem, interpretation, _, #_);
130 }
131 «ENDIF»
132
133 «IF constraint.constrainsRemainingContents»
134 «IF constraint.upperBoundFinite»
135 private pattern «remainingContentsName(constraint)»_helper(problem:LogicProblem, interpretation:PartialInterpretation, object:DefinedElement, remainingMultiplicity:java Integer) {
136 find interpretation(problem,interpretation);
137 find mustExist(problem,interpretation,object);
138 «base.typeIndexer.referInstanceOf(constraint.sourceType,Modality::MUST,"object")»
139 numberOfExistingReferences == count «base.referRelation(constraint.relation,"object","_",Modality.MUST,fqn2PQuery)»
140 check(numberOfExistingReferences < «constraint.upperBound»);
141 remainingMultiplicity == eval(«constraint.upperBound»-numberOfExistingReferences);
142 }
143
144 pattern «remainingContentsName(constraint)»(problem:LogicProblem, interpretation:PartialInterpretation, remainingMultiplicity:java Integer) {
145 find interpretation(problem,interpretation);
146 remainingMultiplicity == sum find «remainingContentsName(constraint)»_helper(problem, interpretation, _, #_);
147 }
148 «ELSE»
149 pattern «remainingContentsName(constraint)»_helper(problem:LogicProblem, interpretation:PartialInterpretation) {
150 find interpretation(problem,interpretation);
151 find mustExist(problem,interpretation,object);
152 «base.typeIndexer.referInstanceOf(constraint.sourceType,Modality::MUST,"object")»
153 }
154
155 pattern «remainingContentsName(constraint)»(problem:LogicProblem, interpretation:PartialInterpretation, remainingMultiplicity:java Integer) {
156 find interpretation(problem,interpretation);
157 find «remainingContentsName(constraint)»_helper(problem, interpretation);
158 remainingMultiplicity == -1;
159 } or {
160 find interpretation(problem,interpretation);
161 neg find «remainingContentsName(constraint)»_helper(problem, interpretation);
162 remainingMultiplicity == 0;
163 }
164 «ENDIF»
165 «ENDIF»
166 «ENDIF»
58 «ENDFOR» 167 «ENDFOR»
59 ''' 168 '''
60 } 169
61 def String unfinishedMultiplicityName(LowerMultiplicityAssertion lowerMultiplicityAssertion) 170 def String unfinishedMultiplicityName(
62 '''unfinishedLowerMultiplicity_«base.canonizeName(lowerMultiplicityAssertion.relation.name)»''' 171 RelationMultiplicityConstraint constraint) '''unfinishedLowerMultiplicity_«base.canonizeName(constraint.relation.name)»'''
63 172
64 //def public referUnfinishedMultiplicityQuery(LowerMultiplicityAssertion lowerMultiplicityAssertion) 173 def String unrepairableMultiplicityName(
65 // '''find «unfinishedMultiplicityName(lowerMultiplicityAssertion)»(problem, interpretation ,object, missingMultiplicity);''' 174 RelationMultiplicityConstraint constraint) '''unrepairableLowerMultiplicity_«base.canonizeName(constraint.relation.name)»'''
66 175
67 def getFirstParamTypeOfRelation(LowerMultiplicityAssertion lowerMultiplicityAssertion) { 176 private def String repairMatchName(
68 val parameters = lowerMultiplicityAssertion.relation.parameters 177 RelationMultiplicityConstraint constraint) '''repair_«base.canonizeName(constraint.relation.name)»'''
69 if(parameters.size == 2) { 178
70 val firstParam = parameters.get(0) 179 def String remainingMultiplicityName(
71 if(firstParam instanceof ComplexTypeReference) { 180 RelationMultiplicityConstraint constraint) '''remainingInverseUpperMultiplicity_«base.canonizeName(constraint.relation.name)»'''
72 return firstParam.referred 181
73 } 182 def String remainingContentsName(
74 } 183 RelationMultiplicityConstraint constraint) '''remainingContents_«base.canonizeName(constraint.relation.name)»'''
75 } 184
76 185 def getUnfinishedMultiplicityQueries(List<RelationMultiplicityConstraint> constraints) {
77 def getUnfinishedMultiplicityQueries(LogicProblem problem) { 186 constraints.toInvertedMap [ constraint |
78 val lowerMultiplicities = base.lowerMultiplicities(problem) 187 new UnifinishedMultiplicityQueryNames(
79 val map = new LinkedHashMap 188 if(constraint.constrainsUnfinished) unfinishedMultiplicityName(constraint) else null,
80 for(lowerMultiplicity : lowerMultiplicities) { 189 if (indexUpperMultiplicities && constraint.constrainsUnrepairable)
81 map.put(lowerMultiplicity.relation,unfinishedMultiplicityName(lowerMultiplicity)->lowerMultiplicity.lower) 190 unrepairableMultiplicityName(constraint)
82 } 191 else
83 return map 192 null,
193 if (indexUpperMultiplicities && constraint.constrainsRemainingInverse)
194 remainingMultiplicityName(constraint)
195 else
196 null,
197 if (indexUpperMultiplicities && constraint.constrainsRemainingContents)
198 remainingContentsName(constraint)
199 else
200 null
201 )
202 ]
84 } 203 }
85} 204}
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 e03a8c35..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,98 +1,26 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules 1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules
2 2
3import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.LowerMultiplicityAssertion
4import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.ComplexTypeReference
5import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Relation
6import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type
7import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem 3import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem
8import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.MultiplicityGoalConstraintCalculator 4import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.MultiplicityGoalConstraintCalculator
9import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.GeneratedPatterns 5import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.GeneratedPatterns
10import java.util.ArrayList 6import java.util.ArrayList
11import java.util.HashMap
12import java.util.LinkedList
13import java.util.List
14import java.util.Map
15import org.eclipse.viatra.query.runtime.api.IPatternMatch
16import org.eclipse.viatra.query.runtime.api.IQuerySpecification
17import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher
18
19import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.*
20 7
21class GoalConstraintProvider { 8class GoalConstraintProvider {
22 9
23 def public getUnfinishedMultiplicityQueries(LogicProblem p, GeneratedPatterns patterns, boolean calculateObjectCost) { 10 def getUnfinishedMultiplicityQueries(LogicProblem p, GeneratedPatterns patterns) {
24 val res = new ArrayList() 11 val res = new ArrayList()
25 12 for (entry : patterns.multiplicityConstraintQueries.entrySet) {
26 res.addAll(patterns.unfinishedNonContainmentMulticiplicityQueries,false) 13 val constraint = entry.key
27 if(calculateObjectCost) { 14 if (constraint.constrainsUnfinished) {
28 val missingObjectCost = calculateMissingObjectCost(p) 15 val queries = entry.value
29 res.addAll(patterns.unfinishedContainmentMulticiplicityQueries,true,missingObjectCost) 16 val targetRelationName = constraint.relation.name
30 } else { 17 val query = queries.unfinishedMultiplicityQuery
31 res.addAll(patterns.unfinishedContainmentMulticiplicityQueries,true) 18 val minValue = constraint.lowerBound
32 } 19 val containment = constraint.containment
33 return res 20 res += new MultiplicityGoalConstraintCalculator(targetRelationName, query, minValue, containment, 1)
34 }
35
36 def addAll(ArrayList<MultiplicityGoalConstraintCalculator> res, Map<Relation, Pair<IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>,Integer>> queries, boolean containment) {
37 for(multiplicityQuery : queries.entrySet) {
38 val targetRelationName = multiplicityQuery.key.name
39 val query = multiplicityQuery.value.key
40 val minValue = multiplicityQuery.value.value
41 res += new MultiplicityGoalConstraintCalculator(targetRelationName,query,minValue,containment,1);
42 }
43 }
44 def addAll(
45 ArrayList<MultiplicityGoalConstraintCalculator> res,
46 Map<Relation, Pair<IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>,Integer>> queries,
47 boolean containment,
48 Map<Relation, Integer> cost
49 ) {
50 for(multiplicityQuery : queries.entrySet) {
51 val targetRelationName = multiplicityQuery.key.name
52 val query = multiplicityQuery.value.key
53 val minValue = multiplicityQuery.value.value
54 res += new MultiplicityGoalConstraintCalculator(targetRelationName,query,minValue,containment,multiplicityQuery.key.lookup(cost))
55 }
56 }
57
58 def calculateMissingObjectCost(LogicProblem p) {
59 val containments = p.containmentHierarchies.head.containmentRelations
60 val containment2Lower = containments.toInvertedMap[containment |
61 val lower = p.annotations.filter(LowerMultiplicityAssertion).filter[it.relation === containment].head
62 if(lower !== null) { lower.lower }
63 else { 0 }
64 ]
65 val types = p.types
66 val Map<Type,List<? extends Pair<Type,Integer>>> type2NewCost = new HashMap
67 for(type:types) {
68 val allSupertypes = (#[type] + type.supertypes).toSet
69 val allOutgoingContainments = containments.filter[allSupertypes.contains((it.parameters.get(0) as ComplexTypeReference).referred)]
70 val list = new LinkedList
71 for(outgoingContainment : allOutgoingContainments) {
72 val value = containment2Lower.get(outgoingContainment)
73 if(value>0) {
74 list.add((outgoingContainment.parameters.get(1) as ComplexTypeReference).referred
75 -> value)
76 }
77 } 21 }
78 type2NewCost.put(type, list)
79 }
80 val res = new HashMap
81 for(containment : containments) {
82 val key = containment
83 val value = (containment.parameters.get(1) as ComplexTypeReference).referred.count(type2NewCost)
84// println('''«key.name» --> «value» new''')
85 res.put(key,value)
86 } 22 }
87 return res 23 return res
88 } 24 }
89 25
90 private def int count(Type t, Map<Type,List<? extends Pair<Type,Integer>>> containments) {
91 val list = containments.get(t)
92 var r = 1
93 for(element : list) {
94 r += element.value * element.key.count(containments)
95 }
96 return r
97 }
98} \ 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 23ea118b..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
@@ -15,7 +15,7 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.StringTypeReference
15import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type 15import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type
16import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem 16import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem
17import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationStatistics 17import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationStatistics
18import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ScopePropagator 18import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagator
19import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.GeneratedPatterns 19import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.GeneratedPatterns
20import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.ObjectCreationPrecondition 20import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.ObjectCreationPrecondition
21import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialBooleanInterpretation 21import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialBooleanInterpretation
@@ -84,13 +84,13 @@ class RefinementRuleProvider {
84 { 84 {
85 val name = '''addObject_«type.name.canonizeName»« 85 val name = '''addObject_«type.name.canonizeName»«
86 IF containmentRelation!==null»_by_«containmentRelation.name.canonizeName»«ENDIF»''' 86 IF containmentRelation!==null»_by_«containmentRelation.name.canonizeName»«ENDIF»'''
87 val ruleBuilder = factory.createRule 87 val ruleBuilder = factory.createRule(lhs)
88 .name(name) 88 .name(name)
89 .precondition(lhs)
90 if(containmentRelation !== null) { 89 if(containmentRelation !== null) {
91 if(inverseRelation!== null) { 90 if(inverseRelation!== null) {
92 ruleBuilder.action[match | 91 ruleBuilder.action[match |
93 //println(name) 92 statistics.incrementTransformationCount
93// println(name)
94 val startTime = System.nanoTime 94 val startTime = System.nanoTime
95 //val problem = match.get(0) as LogicProblem 95 //val problem = match.get(0) as LogicProblem
96 val interpretation = match.get(1) as PartialInterpretation 96 val interpretation = match.get(1) as PartialInterpretation
@@ -111,11 +111,17 @@ class RefinementRuleProvider {
111 scopePropagator 111 scopePropagator
112 ) 112 )
113 113
114 statistics.addExecutionTime(System.nanoTime-startTime) 114 val propagatorStartTime = System.nanoTime
115 statistics.addExecutionTime(propagatorStartTime-startTime)
116
117 // Scope propagation
118 scopePropagator.propagateAllScopeConstraints()
119 statistics.addScopePropagationTime(System.nanoTime-propagatorStartTime)
115 ] 120 ]
116 } else { 121 } else {
117 ruleBuilder.action[match | 122 ruleBuilder.action[match |
118 //println(name) 123 statistics.incrementTransformationCount
124// println(name)
119 val startTime = System.nanoTime 125 val startTime = System.nanoTime
120 //val problem = match.get(0) as LogicProblem 126 //val problem = match.get(0) as LogicProblem
121 val interpretation = match.get(1) as PartialInterpretation 127 val interpretation = match.get(1) as PartialInterpretation
@@ -134,17 +140,23 @@ class RefinementRuleProvider {
134 scopePropagator 140 scopePropagator
135 ) 141 )
136 142
137 statistics.addExecutionTime(System.nanoTime-startTime) 143 val propagatorStartTime = System.nanoTime
144 statistics.addExecutionTime(propagatorStartTime-startTime)
145
146 // Scope propagation
147 scopePropagator.propagateAllScopeConstraints()
148 statistics.addScopePropagationTime(System.nanoTime-propagatorStartTime)
138 ] 149 ]
139 } 150 }
140 } else { 151 } else {
141 ruleBuilder.action[match | 152 ruleBuilder.action[match |
142 //println(name) 153 statistics.incrementTransformationCount
154// println(name)
143 val startTime = System.nanoTime 155 val startTime = System.nanoTime
144 //val problem = match.get(0) as LogicProblem 156 //val problem = match.get(0) as LogicProblem
145 val interpretation = match.get(1) as PartialInterpretation 157 val interpretation = match.get(1) as PartialInterpretation
146 val typeInterpretation = match.get(2) as PartialComplexTypeInterpretation 158 val typeInterpretation = match.get(2) as PartialComplexTypeInterpretation
147 159
148 createObjectAction( 160 createObjectAction(
149 nameNewElement, 161 nameNewElement,
150 interpretation, 162 interpretation,
@@ -154,14 +166,18 @@ class RefinementRuleProvider {
154 scopePropagator 166 scopePropagator
155 ) 167 )
156 168
157 statistics.addExecutionTime(System.nanoTime-startTime) 169 val propagatorStartTime = System.nanoTime
170 statistics.addExecutionTime(propagatorStartTime-startTime)
171
172 // Scope propagation
173 scopePropagator.propagateAllScopeConstraints()
174 statistics.addScopePropagationTime(System.nanoTime-propagatorStartTime)
158 ] 175 ]
159 } 176 }
160 return ruleBuilder.build 177 return ruleBuilder.build
161 } 178 }
162 179
163 def private recursiveObjectCreation(LogicProblem p, PartialInterpretation i) 180 def private recursiveObjectCreation(LogicProblem p, PartialInterpretation i) {
164 {
165 val Map<Type,List<ObjectCreationInterpretationData>> recursiveObjectCreation = new HashMap 181 val Map<Type,List<ObjectCreationInterpretationData>> recursiveObjectCreation = new HashMap
166 for(type : p.types) { 182 for(type : p.types) {
167 recursiveObjectCreation.put(type,new LinkedList) 183 recursiveObjectCreation.put(type,new LinkedList)
@@ -305,49 +321,64 @@ class RefinementRuleProvider {
305 private dispatch def Function0<DefinedElement> getTypeConstructor(PartialStringInterpretation reference) { [createStringElement] } 321 private dispatch def Function0<DefinedElement> getTypeConstructor(PartialStringInterpretation reference) { [createStringElement] }
306 322
307 323
308 def createRelationRefinementRules(GeneratedPatterns patterns, ModelGenerationStatistics statistics) { 324 def createRelationRefinementRules(GeneratedPatterns patterns, ScopePropagator scopePropagator, ModelGenerationStatistics statistics) {
309 val res = new LinkedHashMap 325 val res = new LinkedHashMap
310 for(LHSEntry: patterns.refinerelationQueries.entrySet) { 326 for(LHSEntry: patterns.refinerelationQueries.entrySet) {
311 val declaration = LHSEntry.key.key 327 val declaration = LHSEntry.key.key
312 val inverseReference = LHSEntry.key.value 328 val inverseReference = LHSEntry.key.value
313 val lhs = LHSEntry.value as IQuerySpecification<ViatraQueryMatcher<GenericPatternMatch>> 329 val lhs = LHSEntry.value as IQuerySpecification<ViatraQueryMatcher<GenericPatternMatch>>
314 val rule = createRelationRefinementRule(declaration,inverseReference,lhs,statistics) 330 val rule = createRelationRefinementRule(declaration,inverseReference,lhs,scopePropagator,statistics)
315 res.put(LHSEntry.key,rule) 331 res.put(LHSEntry.key,rule)
316 } 332 }
317 return res 333 return res
318 } 334 }
319 335
320 def private BatchTransformationRule<GenericPatternMatch, ViatraQueryMatcher<GenericPatternMatch>> 336 def private BatchTransformationRule<GenericPatternMatch, ViatraQueryMatcher<GenericPatternMatch>>
321 createRelationRefinementRule(RelationDeclaration declaration, Relation inverseRelation, IQuerySpecification<ViatraQueryMatcher<GenericPatternMatch>> lhs, ModelGenerationStatistics statistics) 337 createRelationRefinementRule(RelationDeclaration declaration, Relation inverseRelation, IQuerySpecification<ViatraQueryMatcher<GenericPatternMatch>> lhs, ScopePropagator scopePropagator, ModelGenerationStatistics statistics)
322 { 338 {
323 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»'''
324 val ruleBuilder = factory.createRule 340 val ruleBuilder = factory.createRule(lhs)
325 .name(name) 341 .name(name)
326 .precondition(lhs)
327 if (inverseRelation === null) { 342 if (inverseRelation === null) {
328 ruleBuilder.action [ match | 343 ruleBuilder.action [ match |
344 statistics.incrementTransformationCount
329 val startTime = System.nanoTime 345 val startTime = System.nanoTime
330 //println(name) 346// println(name)
331 // val problem = match.get(0) as LogicProblem 347 // val problem = match.get(0) as LogicProblem
332 // val interpretation = match.get(1) as PartialInterpretation 348 // val interpretation = match.get(1) as PartialInterpretation
333 val relationInterpretation = match.get(2) as PartialRelationInterpretation 349 val relationInterpretation = match.get(2) as PartialRelationInterpretation
334 val src = match.get(3) as DefinedElement 350 val src = match.get(3) as DefinedElement
335 val trg = match.get(4) as DefinedElement 351 val trg = match.get(4) as DefinedElement
352
336 createRelationLinkAction(src, trg, relationInterpretation) 353 createRelationLinkAction(src, trg, relationInterpretation)
337 statistics.addExecutionTime(System.nanoTime-startTime) 354
355 val propagatorStartTime = System.nanoTime
356 statistics.addExecutionTime(propagatorStartTime-startTime)
357
358 // Scope propagation
359 scopePropagator.propagateAdditionToRelation(declaration)
360 statistics.addScopePropagationTime(System.nanoTime-propagatorStartTime)
338 ] 361 ]
339 } else { 362 } else {
340 ruleBuilder.action [ match | 363 ruleBuilder.action [ match |
364 statistics.incrementTransformationCount
341 val startTime = System.nanoTime 365 val startTime = System.nanoTime
342 //println(name) 366// println(name)
343 // val problem = match.get(0) as LogicProblem 367 // val problem = match.get(0) as LogicProblem
344 // val interpretation = match.get(1) as PartialInterpretation 368 // val interpretation = match.get(1) as PartialInterpretation
345 val relationInterpretation = match.get(2) as PartialRelationInterpretation 369 val relationInterpretation = match.get(2) as PartialRelationInterpretation
346 val inverseInterpretation = match.get(3) as PartialRelationInterpretation 370 val inverseInterpretation = match.get(3) as PartialRelationInterpretation
347 val src = match.get(4) as DefinedElement 371 val src = match.get(4) as DefinedElement
348 val trg = match.get(5) as DefinedElement 372 val trg = match.get(5) as DefinedElement
373
349 createRelationLinkWithInverse(src, trg, relationInterpretation, inverseInterpretation) 374 createRelationLinkWithInverse(src, trg, relationInterpretation, inverseInterpretation)
350 statistics.addExecutionTime(System.nanoTime-startTime) 375
376 val propagatorStartTime = System.nanoTime
377 statistics.addExecutionTime(propagatorStartTime-startTime)
378
379 // Scope propagation
380 scopePropagator.propagateAdditionToRelation(declaration)
381 statistics.addScopePropagationTime(System.nanoTime-propagatorStartTime)
351 ] 382 ]
352 } 383 }
353 384
@@ -426,7 +457,7 @@ class RefinementRuleProvider {
426 inverseRelationInterpretation.relationlinks+=newLink2 457 inverseRelationInterpretation.relationlinks+=newLink2
427 458
428 // Scope propagation 459 // Scope propagation
429 scopePropagator.propagateAdditionToType(typeInterpretation) 460 scopePropagator.decrementTypeScope(typeInterpretation)
430 461
431 // Existence 462 // Existence
432 interpretation.newElements+=newElement 463 interpretation.newElements+=newElement
@@ -464,7 +495,7 @@ class RefinementRuleProvider {
464 relationInterpretation.relationlinks+=newLink 495 relationInterpretation.relationlinks+=newLink
465 496
466 // Scope propagation 497 // Scope propagation
467 scopePropagator.propagateAdditionToType(typeInterpretation) 498 scopePropagator.decrementTypeScope(typeInterpretation)
468 499
469 // Existence 500 // Existence
470 interpretation.newElements+=newElement 501 interpretation.newElements+=newElement
@@ -497,7 +528,7 @@ class RefinementRuleProvider {
497 } 528 }
498 529
499 // Scope propagation 530 // Scope propagation
500 scopePropagator.propagateAdditionToType(typeInterpretation) 531 scopePropagator.decrementTypeScope(typeInterpretation)
501 532
502 // Existence 533 // Existence
503 interpretation.newElements+=newElement 534 interpretation.newElements+=newElement
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/PartialInterpretation.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/PartialInterpretation.java
index 098cc15b..9d0c3fea 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/PartialInterpretation.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/PartialInterpretation.java
@@ -30,6 +30,7 @@ import org.eclipse.emf.ecore.EObject;
30 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation#getScopes <em>Scopes</em>}</li> 30 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation#getScopes <em>Scopes</em>}</li>
31 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation#getMinNewElements <em>Min New Elements</em>}</li> 31 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation#getMinNewElements <em>Min New Elements</em>}</li>
32 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation#getMaxNewElements <em>Max New Elements</em>}</li> 32 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation#getMaxNewElements <em>Max New Elements</em>}</li>
33 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation#getMinNewElementsHeuristic <em>Min New Elements Heuristic</em>}</li>
33 * </ul> 34 * </ul>
34 * 35 *
35 * @see hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationPackage#getPartialInterpretation() 36 * @see hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationPackage#getPartialInterpretation()
@@ -255,4 +256,27 @@ public interface PartialInterpretation extends EObject {
255 */ 256 */
256 void setMaxNewElements(int value); 257 void setMaxNewElements(int value);
257 258
259 /**
260 * Returns the value of the '<em><b>Min New Elements Heuristic</b></em>' attribute.
261 * The default value is <code>"0"</code>.
262 * <!-- begin-user-doc -->
263 * <!-- end-user-doc -->
264 * @return the value of the '<em>Min New Elements Heuristic</em>' attribute.
265 * @see #setMinNewElementsHeuristic(int)
266 * @see hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationPackage#getPartialInterpretation_MinNewElementsHeuristic()
267 * @model default="0" required="true"
268 * @generated
269 */
270 int getMinNewElementsHeuristic();
271
272 /**
273 * Sets the value of the '{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation#getMinNewElementsHeuristic <em>Min New Elements Heuristic</em>}' attribute.
274 * <!-- begin-user-doc -->
275 * <!-- end-user-doc -->
276 * @param value the new value of the '<em>Min New Elements Heuristic</em>' attribute.
277 * @see #getMinNewElementsHeuristic()
278 * @generated
279 */
280 void setMinNewElementsHeuristic(int value);
281
258} // PartialInterpretation 282} // PartialInterpretation
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/PartialinterpretationPackage.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/PartialinterpretationPackage.java
index 4f34b9b7..f462ebe4 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/PartialinterpretationPackage.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/PartialinterpretationPackage.java
@@ -167,13 +167,22 @@ public interface PartialinterpretationPackage extends EPackage {
167 int PARTIAL_INTERPRETATION__MAX_NEW_ELEMENTS = 10; 167 int PARTIAL_INTERPRETATION__MAX_NEW_ELEMENTS = 10;
168 168
169 /** 169 /**
170 * The feature id for the '<em><b>Min New Elements Heuristic</b></em>' attribute.
171 * <!-- begin-user-doc -->
172 * <!-- end-user-doc -->
173 * @generated
174 * @ordered
175 */
176 int PARTIAL_INTERPRETATION__MIN_NEW_ELEMENTS_HEURISTIC = 11;
177
178 /**
170 * The number of structural features of the '<em>Partial Interpretation</em>' class. 179 * The number of structural features of the '<em>Partial Interpretation</em>' class.
171 * <!-- begin-user-doc --> 180 * <!-- begin-user-doc -->
172 * <!-- end-user-doc --> 181 * <!-- end-user-doc -->
173 * @generated 182 * @generated
174 * @ordered 183 * @ordered
175 */ 184 */
176 int PARTIAL_INTERPRETATION_FEATURE_COUNT = 11; 185 int PARTIAL_INTERPRETATION_FEATURE_COUNT = 12;
177 186
178 /** 187 /**
179 * The number of operations of the '<em>Partial Interpretation</em>' class. 188 * The number of operations of the '<em>Partial Interpretation</em>' class.
@@ -913,13 +922,22 @@ public interface PartialinterpretationPackage extends EPackage {
913 int SCOPE__TARGET_TYPE_INTERPRETATION = 2; 922 int SCOPE__TARGET_TYPE_INTERPRETATION = 2;
914 923
915 /** 924 /**
925 * The feature id for the '<em><b>Min New Elements Heuristic</b></em>' attribute.
926 * <!-- begin-user-doc -->
927 * <!-- end-user-doc -->
928 * @generated
929 * @ordered
930 */
931 int SCOPE__MIN_NEW_ELEMENTS_HEURISTIC = 3;
932
933 /**
916 * The number of structural features of the '<em>Scope</em>' class. 934 * The number of structural features of the '<em>Scope</em>' class.
917 * <!-- begin-user-doc --> 935 * <!-- begin-user-doc -->
918 * <!-- end-user-doc --> 936 * <!-- end-user-doc -->
919 * @generated 937 * @generated
920 * @ordered 938 * @ordered
921 */ 939 */
922 int SCOPE_FEATURE_COUNT = 3; 940 int SCOPE_FEATURE_COUNT = 4;
923 941
924 /** 942 /**
925 * The number of operations of the '<em>Scope</em>' class. 943 * The number of operations of the '<em>Scope</em>' class.
@@ -1358,6 +1376,17 @@ public interface PartialinterpretationPackage extends EPackage {
1358 EAttribute getPartialInterpretation_MaxNewElements(); 1376 EAttribute getPartialInterpretation_MaxNewElements();
1359 1377
1360 /** 1378 /**
1379 * Returns the meta object for the attribute '{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation#getMinNewElementsHeuristic <em>Min New Elements Heuristic</em>}'.
1380 * <!-- begin-user-doc -->
1381 * <!-- end-user-doc -->
1382 * @return the meta object for the attribute '<em>Min New Elements Heuristic</em>'.
1383 * @see hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation#getMinNewElementsHeuristic()
1384 * @see #getPartialInterpretation()
1385 * @generated
1386 */
1387 EAttribute getPartialInterpretation_MinNewElementsHeuristic();
1388
1389 /**
1361 * Returns the meta object for class '{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialConstantInterpretation <em>Partial Constant Interpretation</em>}'. 1390 * Returns the meta object for class '{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialConstantInterpretation <em>Partial Constant Interpretation</em>}'.
1362 * <!-- begin-user-doc --> 1391 * <!-- begin-user-doc -->
1363 * <!-- end-user-doc --> 1392 * <!-- end-user-doc -->
@@ -1750,6 +1779,17 @@ public interface PartialinterpretationPackage extends EPackage {
1750 EReference getScope_TargetTypeInterpretation(); 1779 EReference getScope_TargetTypeInterpretation();
1751 1780
1752 /** 1781 /**
1782 * Returns the meta object for the attribute '{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope#getMinNewElementsHeuristic <em>Min New Elements Heuristic</em>}'.
1783 * <!-- begin-user-doc -->
1784 * <!-- end-user-doc -->
1785 * @return the meta object for the attribute '<em>Min New Elements Heuristic</em>'.
1786 * @see hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope#getMinNewElementsHeuristic()
1787 * @see #getScope()
1788 * @generated
1789 */
1790 EAttribute getScope_MinNewElementsHeuristic();
1791
1792 /**
1753 * Returns the meta object for class '{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialPrimitiveInterpretation <em>Partial Primitive Interpretation</em>}'. 1793 * Returns the meta object for class '{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialPrimitiveInterpretation <em>Partial Primitive Interpretation</em>}'.
1754 * <!-- begin-user-doc --> 1794 * <!-- begin-user-doc -->
1755 * <!-- end-user-doc --> 1795 * <!-- end-user-doc -->
@@ -1953,6 +1993,14 @@ public interface PartialinterpretationPackage extends EPackage {
1953 EAttribute PARTIAL_INTERPRETATION__MAX_NEW_ELEMENTS = eINSTANCE.getPartialInterpretation_MaxNewElements(); 1993 EAttribute PARTIAL_INTERPRETATION__MAX_NEW_ELEMENTS = eINSTANCE.getPartialInterpretation_MaxNewElements();
1954 1994
1955 /** 1995 /**
1996 * The meta object literal for the '<em><b>Min New Elements Heuristic</b></em>' attribute feature.
1997 * <!-- begin-user-doc -->
1998 * <!-- end-user-doc -->
1999 * @generated
2000 */
2001 EAttribute PARTIAL_INTERPRETATION__MIN_NEW_ELEMENTS_HEURISTIC = eINSTANCE.getPartialInterpretation_MinNewElementsHeuristic();
2002
2003 /**
1956 * The meta object literal for the '{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.PartialConstantInterpretationImpl <em>Partial Constant Interpretation</em>}' class. 2004 * The meta object literal for the '{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.PartialConstantInterpretationImpl <em>Partial Constant Interpretation</em>}' class.
1957 * <!-- begin-user-doc --> 2005 * <!-- begin-user-doc -->
1958 * <!-- end-user-doc --> 2006 * <!-- end-user-doc -->
@@ -2279,6 +2327,14 @@ public interface PartialinterpretationPackage extends EPackage {
2279 EReference SCOPE__TARGET_TYPE_INTERPRETATION = eINSTANCE.getScope_TargetTypeInterpretation(); 2327 EReference SCOPE__TARGET_TYPE_INTERPRETATION = eINSTANCE.getScope_TargetTypeInterpretation();
2280 2328
2281 /** 2329 /**
2330 * The meta object literal for the '<em><b>Min New Elements Heuristic</b></em>' attribute feature.
2331 * <!-- begin-user-doc -->
2332 * <!-- end-user-doc -->
2333 * @generated
2334 */
2335 EAttribute SCOPE__MIN_NEW_ELEMENTS_HEURISTIC = eINSTANCE.getScope_MinNewElementsHeuristic();
2336
2337 /**
2282 * The meta object literal for the '{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.PartialPrimitiveInterpretationImpl <em>Partial Primitive Interpretation</em>}' class. 2338 * The meta object literal for the '{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.PartialPrimitiveInterpretationImpl <em>Partial Primitive Interpretation</em>}' class.
2283 * <!-- begin-user-doc --> 2339 * <!-- begin-user-doc -->
2284 * <!-- end-user-doc --> 2340 * <!-- end-user-doc -->
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/Scope.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/Scope.java
index 155b9f00..a0b58615 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/Scope.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/Scope.java
@@ -16,6 +16,7 @@ import org.eclipse.emf.ecore.EObject;
16 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope#getMinNewElements <em>Min New Elements</em>}</li> 16 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope#getMinNewElements <em>Min New Elements</em>}</li>
17 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope#getMaxNewElements <em>Max New Elements</em>}</li> 17 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope#getMaxNewElements <em>Max New Elements</em>}</li>
18 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope#getTargetTypeInterpretation <em>Target Type Interpretation</em>}</li> 18 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope#getTargetTypeInterpretation <em>Target Type Interpretation</em>}</li>
19 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope#getMinNewElementsHeuristic <em>Min New Elements Heuristic</em>}</li>
19 * </ul> 20 * </ul>
20 * 21 *
21 * @see hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationPackage#getScope() 22 * @see hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationPackage#getScope()
@@ -105,4 +106,27 @@ public interface Scope extends EObject {
105 */ 106 */
106 void setTargetTypeInterpretation(PartialTypeInterpratation value); 107 void setTargetTypeInterpretation(PartialTypeInterpratation value);
107 108
109 /**
110 * Returns the value of the '<em><b>Min New Elements Heuristic</b></em>' attribute.
111 * The default value is <code>"0"</code>.
112 * <!-- begin-user-doc -->
113 * <!-- end-user-doc -->
114 * @return the value of the '<em>Min New Elements Heuristic</em>' attribute.
115 * @see #setMinNewElementsHeuristic(int)
116 * @see hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationPackage#getScope_MinNewElementsHeuristic()
117 * @model default="0" required="true"
118 * @generated
119 */
120 int getMinNewElementsHeuristic();
121
122 /**
123 * Sets the value of the '{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope#getMinNewElementsHeuristic <em>Min New Elements Heuristic</em>}' attribute.
124 * <!-- begin-user-doc -->
125 * <!-- end-user-doc -->
126 * @param value the new value of the '<em>Min New Elements Heuristic</em>' attribute.
127 * @see #getMinNewElementsHeuristic()
128 * @generated
129 */
130 void setMinNewElementsHeuristic(int value);
131
108} // Scope 132} // Scope
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/BinaryElementRelationLinkImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/BinaryElementRelationLinkImpl.java
index f5efe02a..ca33dd65 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/BinaryElementRelationLinkImpl.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/BinaryElementRelationLinkImpl.java
@@ -73,6 +73,7 @@ public class BinaryElementRelationLinkImpl extends RelationLinkImpl implements B
73 * <!-- end-user-doc --> 73 * <!-- end-user-doc -->
74 * @generated 74 * @generated
75 */ 75 */
76 @Override
76 public DefinedElement getParam1() { 77 public DefinedElement getParam1() {
77 if (param1 != null && param1.eIsProxy()) { 78 if (param1 != null && param1.eIsProxy()) {
78 InternalEObject oldParam1 = (InternalEObject)param1; 79 InternalEObject oldParam1 = (InternalEObject)param1;
@@ -99,6 +100,7 @@ public class BinaryElementRelationLinkImpl extends RelationLinkImpl implements B
99 * <!-- end-user-doc --> 100 * <!-- end-user-doc -->
100 * @generated 101 * @generated
101 */ 102 */
103 @Override
102 public void setParam1(DefinedElement newParam1) { 104 public void setParam1(DefinedElement newParam1) {
103 DefinedElement oldParam1 = param1; 105 DefinedElement oldParam1 = param1;
104 param1 = newParam1; 106 param1 = newParam1;
@@ -111,6 +113,7 @@ public class BinaryElementRelationLinkImpl extends RelationLinkImpl implements B
111 * <!-- end-user-doc --> 113 * <!-- end-user-doc -->
112 * @generated 114 * @generated
113 */ 115 */
116 @Override
114 public DefinedElement getParam2() { 117 public DefinedElement getParam2() {
115 if (param2 != null && param2.eIsProxy()) { 118 if (param2 != null && param2.eIsProxy()) {
116 InternalEObject oldParam2 = (InternalEObject)param2; 119 InternalEObject oldParam2 = (InternalEObject)param2;
@@ -137,6 +140,7 @@ public class BinaryElementRelationLinkImpl extends RelationLinkImpl implements B
137 * <!-- end-user-doc --> 140 * <!-- end-user-doc -->
138 * @generated 141 * @generated
139 */ 142 */
143 @Override
140 public void setParam2(DefinedElement newParam2) { 144 public void setParam2(DefinedElement newParam2) {
141 DefinedElement oldParam2 = param2; 145 DefinedElement oldParam2 = param2;
142 param2 = newParam2; 146 param2 = newParam2;
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/BooleanElementImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/BooleanElementImpl.java
index e906e07d..5f12d9e4 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/BooleanElementImpl.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/BooleanElementImpl.java
@@ -69,6 +69,7 @@ public class BooleanElementImpl extends PrimitiveElementImpl implements BooleanE
69 * <!-- end-user-doc --> 69 * <!-- end-user-doc -->
70 * @generated 70 * @generated
71 */ 71 */
72 @Override
72 public boolean isValue() { 73 public boolean isValue() {
73 return value; 74 return value;
74 } 75 }
@@ -78,6 +79,7 @@ public class BooleanElementImpl extends PrimitiveElementImpl implements BooleanE
78 * <!-- end-user-doc --> 79 * <!-- end-user-doc -->
79 * @generated 80 * @generated
80 */ 81 */
82 @Override
81 public void setValue(boolean newValue) { 83 public void setValue(boolean newValue) {
82 boolean oldValue = value; 84 boolean oldValue = value;
83 value = newValue; 85 value = newValue;
@@ -152,7 +154,7 @@ public class BooleanElementImpl extends PrimitiveElementImpl implements BooleanE
152 public String toString() { 154 public String toString() {
153 if (eIsProxy()) return super.toString(); 155 if (eIsProxy()) return super.toString();
154 156
155 StringBuffer result = new StringBuffer(super.toString()); 157 StringBuilder result = new StringBuilder(super.toString());
156 result.append(" (value: "); 158 result.append(" (value: ");
157 result.append(value); 159 result.append(value);
158 result.append(')'); 160 result.append(')');
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/IntegerElementImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/IntegerElementImpl.java
index ef1a4b96..c8fbe1dd 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/IntegerElementImpl.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/IntegerElementImpl.java
@@ -69,6 +69,7 @@ public class IntegerElementImpl extends PrimitiveElementImpl implements IntegerE
69 * <!-- end-user-doc --> 69 * <!-- end-user-doc -->
70 * @generated 70 * @generated
71 */ 71 */
72 @Override
72 public int getValue() { 73 public int getValue() {
73 return value; 74 return value;
74 } 75 }
@@ -78,6 +79,7 @@ public class IntegerElementImpl extends PrimitiveElementImpl implements IntegerE
78 * <!-- end-user-doc --> 79 * <!-- end-user-doc -->
79 * @generated 80 * @generated
80 */ 81 */
82 @Override
81 public void setValue(int newValue) { 83 public void setValue(int newValue) {
82 int oldValue = value; 84 int oldValue = value;
83 value = newValue; 85 value = newValue;
@@ -152,7 +154,7 @@ public class IntegerElementImpl extends PrimitiveElementImpl implements IntegerE
152 public String toString() { 154 public String toString() {
153 if (eIsProxy()) return super.toString(); 155 if (eIsProxy()) return super.toString();
154 156
155 StringBuffer result = new StringBuffer(super.toString()); 157 StringBuilder result = new StringBuilder(super.toString());
156 result.append(" (value: "); 158 result.append(" (value: ");
157 result.append(value); 159 result.append(value);
158 result.append(')'); 160 result.append(')');
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/NaryRelationLinkElementImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/NaryRelationLinkElementImpl.java
index 749a03c5..c319a3f4 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/NaryRelationLinkElementImpl.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/NaryRelationLinkElementImpl.java
@@ -83,6 +83,7 @@ public class NaryRelationLinkElementImpl extends MinimalEObjectImpl.Container im
83 * <!-- end-user-doc --> 83 * <!-- end-user-doc -->
84 * @generated 84 * @generated
85 */ 85 */
86 @Override
86 public int getIndex() { 87 public int getIndex() {
87 return index; 88 return index;
88 } 89 }
@@ -92,6 +93,7 @@ public class NaryRelationLinkElementImpl extends MinimalEObjectImpl.Container im
92 * <!-- end-user-doc --> 93 * <!-- end-user-doc -->
93 * @generated 94 * @generated
94 */ 95 */
96 @Override
95 public void setIndex(int newIndex) { 97 public void setIndex(int newIndex) {
96 int oldIndex = index; 98 int oldIndex = index;
97 index = newIndex; 99 index = newIndex;
@@ -104,6 +106,7 @@ public class NaryRelationLinkElementImpl extends MinimalEObjectImpl.Container im
104 * <!-- end-user-doc --> 106 * <!-- end-user-doc -->
105 * @generated 107 * @generated
106 */ 108 */
109 @Override
107 public DefinedElement getParam() { 110 public DefinedElement getParam() {
108 if (param != null && param.eIsProxy()) { 111 if (param != null && param.eIsProxy()) {
109 InternalEObject oldParam = (InternalEObject)param; 112 InternalEObject oldParam = (InternalEObject)param;
@@ -130,6 +133,7 @@ public class NaryRelationLinkElementImpl extends MinimalEObjectImpl.Container im
130 * <!-- end-user-doc --> 133 * <!-- end-user-doc -->
131 * @generated 134 * @generated
132 */ 135 */
136 @Override
133 public void setParam(DefinedElement newParam) { 137 public void setParam(DefinedElement newParam) {
134 DefinedElement oldParam = param; 138 DefinedElement oldParam = param;
135 param = newParam; 139 param = newParam;
@@ -215,7 +219,7 @@ public class NaryRelationLinkElementImpl extends MinimalEObjectImpl.Container im
215 public String toString() { 219 public String toString() {
216 if (eIsProxy()) return super.toString(); 220 if (eIsProxy()) return super.toString();
217 221
218 StringBuffer result = new StringBuffer(super.toString()); 222 StringBuilder result = new StringBuilder(super.toString());
219 result.append(" (index: "); 223 result.append(" (index: ");
220 result.append(index); 224 result.append(index);
221 result.append(')'); 225 result.append(')');
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/NaryRelationLinkImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/NaryRelationLinkImpl.java
index f387ee06..9f7628cf 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/NaryRelationLinkImpl.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/NaryRelationLinkImpl.java
@@ -66,6 +66,7 @@ public class NaryRelationLinkImpl extends RelationLinkImpl implements NaryRelati
66 * <!-- end-user-doc --> 66 * <!-- end-user-doc -->
67 * @generated 67 * @generated
68 */ 68 */
69 @Override
69 public EList<NaryRelationLinkElement> getElements() { 70 public EList<NaryRelationLinkElement> getElements() {
70 if (elements == null) { 71 if (elements == null) {
71 elements = new EObjectContainmentEList<NaryRelationLinkElement>(NaryRelationLinkElement.class, this, PartialinterpretationPackage.NARY_RELATION_LINK__ELEMENTS); 72 elements = new EObjectContainmentEList<NaryRelationLinkElement>(NaryRelationLinkElement.class, this, PartialinterpretationPackage.NARY_RELATION_LINK__ELEMENTS);
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialComplexTypeInterpretationImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialComplexTypeInterpretationImpl.java
index 07ee282d..c00b4278 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialComplexTypeInterpretationImpl.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialComplexTypeInterpretationImpl.java
@@ -79,6 +79,7 @@ public class PartialComplexTypeInterpretationImpl extends PartialTypeInterpratat
79 * <!-- end-user-doc --> 79 * <!-- end-user-doc -->
80 * @generated 80 * @generated
81 */ 81 */
82 @Override
82 public EList<PartialComplexTypeInterpretation> getSupertypeInterpretation() { 83 public EList<PartialComplexTypeInterpretation> getSupertypeInterpretation() {
83 if (supertypeInterpretation == null) { 84 if (supertypeInterpretation == null) {
84 supertypeInterpretation = new EObjectResolvingEList<PartialComplexTypeInterpretation>(PartialComplexTypeInterpretation.class, this, PartialinterpretationPackage.PARTIAL_COMPLEX_TYPE_INTERPRETATION__SUPERTYPE_INTERPRETATION); 85 supertypeInterpretation = new EObjectResolvingEList<PartialComplexTypeInterpretation>(PartialComplexTypeInterpretation.class, this, PartialinterpretationPackage.PARTIAL_COMPLEX_TYPE_INTERPRETATION__SUPERTYPE_INTERPRETATION);
@@ -91,6 +92,7 @@ public class PartialComplexTypeInterpretationImpl extends PartialTypeInterpratat
91 * <!-- end-user-doc --> 92 * <!-- end-user-doc -->
92 * @generated 93 * @generated
93 */ 94 */
95 @Override
94 public TypeDeclaration getInterpretationOf() { 96 public TypeDeclaration getInterpretationOf() {
95 if (interpretationOf != null && interpretationOf.eIsProxy()) { 97 if (interpretationOf != null && interpretationOf.eIsProxy()) {
96 InternalEObject oldInterpretationOf = (InternalEObject)interpretationOf; 98 InternalEObject oldInterpretationOf = (InternalEObject)interpretationOf;
@@ -117,6 +119,7 @@ public class PartialComplexTypeInterpretationImpl extends PartialTypeInterpratat
117 * <!-- end-user-doc --> 119 * <!-- end-user-doc -->
118 * @generated 120 * @generated
119 */ 121 */
122 @Override
120 public void setInterpretationOf(TypeDeclaration newInterpretationOf) { 123 public void setInterpretationOf(TypeDeclaration newInterpretationOf) {
121 TypeDeclaration oldInterpretationOf = interpretationOf; 124 TypeDeclaration oldInterpretationOf = interpretationOf;
122 interpretationOf = newInterpretationOf; 125 interpretationOf = newInterpretationOf;
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialConstantInterpretationImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialConstantInterpretationImpl.java
index 81b2ce8d..6d51f0db 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialConstantInterpretationImpl.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialConstantInterpretationImpl.java
@@ -63,6 +63,7 @@ public class PartialConstantInterpretationImpl extends MinimalEObjectImpl.Contai
63 * <!-- end-user-doc --> 63 * <!-- end-user-doc -->
64 * @generated 64 * @generated
65 */ 65 */
66 @Override
66 public ConstantDeclaration getInterpretationOf() { 67 public ConstantDeclaration getInterpretationOf() {
67 if (interpretationOf != null && interpretationOf.eIsProxy()) { 68 if (interpretationOf != null && interpretationOf.eIsProxy()) {
68 InternalEObject oldInterpretationOf = (InternalEObject)interpretationOf; 69 InternalEObject oldInterpretationOf = (InternalEObject)interpretationOf;
@@ -89,6 +90,7 @@ public class PartialConstantInterpretationImpl extends MinimalEObjectImpl.Contai
89 * <!-- end-user-doc --> 90 * <!-- end-user-doc -->
90 * @generated 91 * @generated
91 */ 92 */
93 @Override
92 public void setInterpretationOf(ConstantDeclaration newInterpretationOf) { 94 public void setInterpretationOf(ConstantDeclaration newInterpretationOf) {
93 ConstantDeclaration oldInterpretationOf = interpretationOf; 95 ConstantDeclaration oldInterpretationOf = interpretationOf;
94 interpretationOf = newInterpretationOf; 96 interpretationOf = newInterpretationOf;
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialFunctionInterpretationImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialFunctionInterpretationImpl.java
index 2d361e8e..855c4abc 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialFunctionInterpretationImpl.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialFunctionInterpretationImpl.java
@@ -63,6 +63,7 @@ public class PartialFunctionInterpretationImpl extends MinimalEObjectImpl.Contai
63 * <!-- end-user-doc --> 63 * <!-- end-user-doc -->
64 * @generated 64 * @generated
65 */ 65 */
66 @Override
66 public FunctionDeclaration getInterpretationOf() { 67 public FunctionDeclaration getInterpretationOf() {
67 if (interpretationOf != null && interpretationOf.eIsProxy()) { 68 if (interpretationOf != null && interpretationOf.eIsProxy()) {
68 InternalEObject oldInterpretationOf = (InternalEObject)interpretationOf; 69 InternalEObject oldInterpretationOf = (InternalEObject)interpretationOf;
@@ -89,6 +90,7 @@ public class PartialFunctionInterpretationImpl extends MinimalEObjectImpl.Contai
89 * <!-- end-user-doc --> 90 * <!-- end-user-doc -->
90 * @generated 91 * @generated
91 */ 92 */
93 @Override
92 public void setInterpretationOf(FunctionDeclaration newInterpretationOf) { 94 public void setInterpretationOf(FunctionDeclaration newInterpretationOf) {
93 FunctionDeclaration oldInterpretationOf = interpretationOf; 95 FunctionDeclaration oldInterpretationOf = interpretationOf;
94 interpretationOf = newInterpretationOf; 96 interpretationOf = newInterpretationOf;
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialInterpretationImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialInterpretationImpl.java
index bce3e2e0..9afdd8d2 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialInterpretationImpl.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialInterpretationImpl.java
@@ -47,6 +47,7 @@ import org.eclipse.emf.ecore.util.InternalEList;
47 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.PartialInterpretationImpl#getScopes <em>Scopes</em>}</li> 47 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.PartialInterpretationImpl#getScopes <em>Scopes</em>}</li>
48 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.PartialInterpretationImpl#getMinNewElements <em>Min New Elements</em>}</li> 48 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.PartialInterpretationImpl#getMinNewElements <em>Min New Elements</em>}</li>
49 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.PartialInterpretationImpl#getMaxNewElements <em>Max New Elements</em>}</li> 49 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.PartialInterpretationImpl#getMaxNewElements <em>Max New Elements</em>}</li>
50 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.PartialInterpretationImpl#getMinNewElementsHeuristic <em>Min New Elements Heuristic</em>}</li>
50 * </ul> 51 * </ul>
51 * 52 *
52 * @generated 53 * @generated
@@ -183,6 +184,26 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl
183 protected int maxNewElements = MAX_NEW_ELEMENTS_EDEFAULT; 184 protected int maxNewElements = MAX_NEW_ELEMENTS_EDEFAULT;
184 185
185 /** 186 /**
187 * The default value of the '{@link #getMinNewElementsHeuristic() <em>Min New Elements Heuristic</em>}' attribute.
188 * <!-- begin-user-doc -->
189 * <!-- end-user-doc -->
190 * @see #getMinNewElementsHeuristic()
191 * @generated
192 * @ordered
193 */
194 protected static final int MIN_NEW_ELEMENTS_HEURISTIC_EDEFAULT = 0;
195
196 /**
197 * The cached value of the '{@link #getMinNewElementsHeuristic() <em>Min New Elements Heuristic</em>}' attribute.
198 * <!-- begin-user-doc -->
199 * <!-- end-user-doc -->
200 * @see #getMinNewElementsHeuristic()
201 * @generated
202 * @ordered
203 */
204 protected int minNewElementsHeuristic = MIN_NEW_ELEMENTS_HEURISTIC_EDEFAULT;
205
206 /**
186 * <!-- begin-user-doc --> 207 * <!-- begin-user-doc -->
187 * <!-- end-user-doc --> 208 * <!-- end-user-doc -->
188 * @generated 209 * @generated
@@ -206,6 +227,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl
206 * <!-- end-user-doc --> 227 * <!-- end-user-doc -->
207 * @generated 228 * @generated
208 */ 229 */
230 @Override
209 public LogicProblem getProblem() { 231 public LogicProblem getProblem() {
210 if (problem != null && problem.eIsProxy()) { 232 if (problem != null && problem.eIsProxy()) {
211 InternalEObject oldProblem = (InternalEObject)problem; 233 InternalEObject oldProblem = (InternalEObject)problem;
@@ -232,6 +254,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl
232 * <!-- end-user-doc --> 254 * <!-- end-user-doc -->
233 * @generated 255 * @generated
234 */ 256 */
257 @Override
235 public void setProblem(LogicProblem newProblem) { 258 public void setProblem(LogicProblem newProblem) {
236 LogicProblem oldProblem = problem; 259 LogicProblem oldProblem = problem;
237 problem = newProblem; 260 problem = newProblem;
@@ -244,6 +267,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl
244 * <!-- end-user-doc --> 267 * <!-- end-user-doc -->
245 * @generated 268 * @generated
246 */ 269 */
270 @Override
247 public EList<PartialConstantInterpretation> getPartialconstantinterpretation() { 271 public EList<PartialConstantInterpretation> getPartialconstantinterpretation() {
248 if (partialconstantinterpretation == null) { 272 if (partialconstantinterpretation == null) {
249 partialconstantinterpretation = new EObjectContainmentEList<PartialConstantInterpretation>(PartialConstantInterpretation.class, this, PartialinterpretationPackage.PARTIAL_INTERPRETATION__PARTIALCONSTANTINTERPRETATION); 273 partialconstantinterpretation = new EObjectContainmentEList<PartialConstantInterpretation>(PartialConstantInterpretation.class, this, PartialinterpretationPackage.PARTIAL_INTERPRETATION__PARTIALCONSTANTINTERPRETATION);
@@ -256,6 +280,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl
256 * <!-- end-user-doc --> 280 * <!-- end-user-doc -->
257 * @generated 281 * @generated
258 */ 282 */
283 @Override
259 public EList<PartialRelationInterpretation> getPartialrelationinterpretation() { 284 public EList<PartialRelationInterpretation> getPartialrelationinterpretation() {
260 if (partialrelationinterpretation == null) { 285 if (partialrelationinterpretation == null) {
261 partialrelationinterpretation = new EObjectContainmentEList<PartialRelationInterpretation>(PartialRelationInterpretation.class, this, PartialinterpretationPackage.PARTIAL_INTERPRETATION__PARTIALRELATIONINTERPRETATION); 286 partialrelationinterpretation = new EObjectContainmentEList<PartialRelationInterpretation>(PartialRelationInterpretation.class, this, PartialinterpretationPackage.PARTIAL_INTERPRETATION__PARTIALRELATIONINTERPRETATION);
@@ -268,6 +293,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl
268 * <!-- end-user-doc --> 293 * <!-- end-user-doc -->
269 * @generated 294 * @generated
270 */ 295 */
296 @Override
271 public EList<PartialFunctionInterpretation> getPartialfunctioninterpretation() { 297 public EList<PartialFunctionInterpretation> getPartialfunctioninterpretation() {
272 if (partialfunctioninterpretation == null) { 298 if (partialfunctioninterpretation == null) {
273 partialfunctioninterpretation = new EObjectContainmentEList<PartialFunctionInterpretation>(PartialFunctionInterpretation.class, this, PartialinterpretationPackage.PARTIAL_INTERPRETATION__PARTIALFUNCTIONINTERPRETATION); 299 partialfunctioninterpretation = new EObjectContainmentEList<PartialFunctionInterpretation>(PartialFunctionInterpretation.class, this, PartialinterpretationPackage.PARTIAL_INTERPRETATION__PARTIALFUNCTIONINTERPRETATION);
@@ -280,6 +306,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl
280 * <!-- end-user-doc --> 306 * <!-- end-user-doc -->
281 * @generated 307 * @generated
282 */ 308 */
309 @Override
283 public EList<DefinedElement> getNewElements() { 310 public EList<DefinedElement> getNewElements() {
284 if (newElements == null) { 311 if (newElements == null) {
285 newElements = new EObjectContainmentEList<DefinedElement>(DefinedElement.class, this, PartialinterpretationPackage.PARTIAL_INTERPRETATION__NEW_ELEMENTS); 312 newElements = new EObjectContainmentEList<DefinedElement>(DefinedElement.class, this, PartialinterpretationPackage.PARTIAL_INTERPRETATION__NEW_ELEMENTS);
@@ -292,6 +319,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl
292 * <!-- end-user-doc --> 319 * <!-- end-user-doc -->
293 * @generated 320 * @generated
294 */ 321 */
322 @Override
295 public EList<PartialTypeInterpratation> getPartialtypeinterpratation() { 323 public EList<PartialTypeInterpratation> getPartialtypeinterpratation() {
296 if (partialtypeinterpratation == null) { 324 if (partialtypeinterpratation == null) {
297 partialtypeinterpratation = new EObjectContainmentEList<PartialTypeInterpratation>(PartialTypeInterpratation.class, this, PartialinterpretationPackage.PARTIAL_INTERPRETATION__PARTIALTYPEINTERPRATATION); 325 partialtypeinterpratation = new EObjectContainmentEList<PartialTypeInterpratation>(PartialTypeInterpratation.class, this, PartialinterpretationPackage.PARTIAL_INTERPRETATION__PARTIALTYPEINTERPRATATION);
@@ -304,6 +332,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl
304 * <!-- end-user-doc --> 332 * <!-- end-user-doc -->
305 * @generated 333 * @generated
306 */ 334 */
335 @Override
307 public EList<DefinedElement> getOpenWorldElements() { 336 public EList<DefinedElement> getOpenWorldElements() {
308 if (openWorldElements == null) { 337 if (openWorldElements == null) {
309 openWorldElements = new EObjectContainmentEList<DefinedElement>(DefinedElement.class, this, PartialinterpretationPackage.PARTIAL_INTERPRETATION__OPEN_WORLD_ELEMENTS); 338 openWorldElements = new EObjectContainmentEList<DefinedElement>(DefinedElement.class, this, PartialinterpretationPackage.PARTIAL_INTERPRETATION__OPEN_WORLD_ELEMENTS);
@@ -316,6 +345,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl
316 * <!-- end-user-doc --> 345 * <!-- end-user-doc -->
317 * @generated 346 * @generated
318 */ 347 */
348 @Override
319 public LogicProblem getProblemConainer() { 349 public LogicProblem getProblemConainer() {
320 return problemConainer; 350 return problemConainer;
321 } 351 }
@@ -340,6 +370,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl
340 * <!-- end-user-doc --> 370 * <!-- end-user-doc -->
341 * @generated 371 * @generated
342 */ 372 */
373 @Override
343 public void setProblemConainer(LogicProblem newProblemConainer) { 374 public void setProblemConainer(LogicProblem newProblemConainer) {
344 if (newProblemConainer != problemConainer) { 375 if (newProblemConainer != problemConainer) {
345 NotificationChain msgs = null; 376 NotificationChain msgs = null;
@@ -359,6 +390,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl
359 * <!-- end-user-doc --> 390 * <!-- end-user-doc -->
360 * @generated 391 * @generated
361 */ 392 */
393 @Override
362 public EList<Scope> getScopes() { 394 public EList<Scope> getScopes() {
363 if (scopes == null) { 395 if (scopes == null) {
364 scopes = new EObjectContainmentEList<Scope>(Scope.class, this, PartialinterpretationPackage.PARTIAL_INTERPRETATION__SCOPES); 396 scopes = new EObjectContainmentEList<Scope>(Scope.class, this, PartialinterpretationPackage.PARTIAL_INTERPRETATION__SCOPES);
@@ -371,6 +403,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl
371 * <!-- end-user-doc --> 403 * <!-- end-user-doc -->
372 * @generated 404 * @generated
373 */ 405 */
406 @Override
374 public int getMinNewElements() { 407 public int getMinNewElements() {
375 return minNewElements; 408 return minNewElements;
376 } 409 }
@@ -380,6 +413,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl
380 * <!-- end-user-doc --> 413 * <!-- end-user-doc -->
381 * @generated 414 * @generated
382 */ 415 */
416 @Override
383 public void setMinNewElements(int newMinNewElements) { 417 public void setMinNewElements(int newMinNewElements) {
384 int oldMinNewElements = minNewElements; 418 int oldMinNewElements = minNewElements;
385 minNewElements = newMinNewElements; 419 minNewElements = newMinNewElements;
@@ -392,6 +426,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl
392 * <!-- end-user-doc --> 426 * <!-- end-user-doc -->
393 * @generated 427 * @generated
394 */ 428 */
429 @Override
395 public int getMaxNewElements() { 430 public int getMaxNewElements() {
396 return maxNewElements; 431 return maxNewElements;
397 } 432 }
@@ -401,6 +436,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl
401 * <!-- end-user-doc --> 436 * <!-- end-user-doc -->
402 * @generated 437 * @generated
403 */ 438 */
439 @Override
404 public void setMaxNewElements(int newMaxNewElements) { 440 public void setMaxNewElements(int newMaxNewElements) {
405 int oldMaxNewElements = maxNewElements; 441 int oldMaxNewElements = maxNewElements;
406 maxNewElements = newMaxNewElements; 442 maxNewElements = newMaxNewElements;
@@ -414,6 +450,29 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl
414 * @generated 450 * @generated
415 */ 451 */
416 @Override 452 @Override
453 public int getMinNewElementsHeuristic() {
454 return minNewElementsHeuristic;
455 }
456
457 /**
458 * <!-- begin-user-doc -->
459 * <!-- end-user-doc -->
460 * @generated
461 */
462 @Override
463 public void setMinNewElementsHeuristic(int newMinNewElementsHeuristic) {
464 int oldMinNewElementsHeuristic = minNewElementsHeuristic;
465 minNewElementsHeuristic = newMinNewElementsHeuristic;
466 if (eNotificationRequired())
467 eNotify(new ENotificationImpl(this, Notification.SET, PartialinterpretationPackage.PARTIAL_INTERPRETATION__MIN_NEW_ELEMENTS_HEURISTIC, oldMinNewElementsHeuristic, minNewElementsHeuristic));
468 }
469
470 /**
471 * <!-- begin-user-doc -->
472 * <!-- end-user-doc -->
473 * @generated
474 */
475 @Override
417 public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { 476 public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
418 switch (featureID) { 477 switch (featureID) {
419 case PartialinterpretationPackage.PARTIAL_INTERPRETATION__PARTIALCONSTANTINTERPRETATION: 478 case PartialinterpretationPackage.PARTIAL_INTERPRETATION__PARTIALCONSTANTINTERPRETATION:
@@ -467,6 +526,8 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl
467 return getMinNewElements(); 526 return getMinNewElements();
468 case PartialinterpretationPackage.PARTIAL_INTERPRETATION__MAX_NEW_ELEMENTS: 527 case PartialinterpretationPackage.PARTIAL_INTERPRETATION__MAX_NEW_ELEMENTS:
469 return getMaxNewElements(); 528 return getMaxNewElements();
529 case PartialinterpretationPackage.PARTIAL_INTERPRETATION__MIN_NEW_ELEMENTS_HEURISTIC:
530 return getMinNewElementsHeuristic();
470 } 531 }
471 return super.eGet(featureID, resolve, coreType); 532 return super.eGet(featureID, resolve, coreType);
472 } 533 }
@@ -520,6 +581,9 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl
520 case PartialinterpretationPackage.PARTIAL_INTERPRETATION__MAX_NEW_ELEMENTS: 581 case PartialinterpretationPackage.PARTIAL_INTERPRETATION__MAX_NEW_ELEMENTS:
521 setMaxNewElements((Integer)newValue); 582 setMaxNewElements((Integer)newValue);
522 return; 583 return;
584 case PartialinterpretationPackage.PARTIAL_INTERPRETATION__MIN_NEW_ELEMENTS_HEURISTIC:
585 setMinNewElementsHeuristic((Integer)newValue);
586 return;
523 } 587 }
524 super.eSet(featureID, newValue); 588 super.eSet(featureID, newValue);
525 } 589 }
@@ -565,6 +629,9 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl
565 case PartialinterpretationPackage.PARTIAL_INTERPRETATION__MAX_NEW_ELEMENTS: 629 case PartialinterpretationPackage.PARTIAL_INTERPRETATION__MAX_NEW_ELEMENTS:
566 setMaxNewElements(MAX_NEW_ELEMENTS_EDEFAULT); 630 setMaxNewElements(MAX_NEW_ELEMENTS_EDEFAULT);
567 return; 631 return;
632 case PartialinterpretationPackage.PARTIAL_INTERPRETATION__MIN_NEW_ELEMENTS_HEURISTIC:
633 setMinNewElementsHeuristic(MIN_NEW_ELEMENTS_HEURISTIC_EDEFAULT);
634 return;
568 } 635 }
569 super.eUnset(featureID); 636 super.eUnset(featureID);
570 } 637 }
@@ -599,6 +666,8 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl
599 return minNewElements != MIN_NEW_ELEMENTS_EDEFAULT; 666 return minNewElements != MIN_NEW_ELEMENTS_EDEFAULT;
600 case PartialinterpretationPackage.PARTIAL_INTERPRETATION__MAX_NEW_ELEMENTS: 667 case PartialinterpretationPackage.PARTIAL_INTERPRETATION__MAX_NEW_ELEMENTS:
601 return maxNewElements != MAX_NEW_ELEMENTS_EDEFAULT; 668 return maxNewElements != MAX_NEW_ELEMENTS_EDEFAULT;
669 case PartialinterpretationPackage.PARTIAL_INTERPRETATION__MIN_NEW_ELEMENTS_HEURISTIC:
670 return minNewElementsHeuristic != MIN_NEW_ELEMENTS_HEURISTIC_EDEFAULT;
602 } 671 }
603 return super.eIsSet(featureID); 672 return super.eIsSet(featureID);
604 } 673 }
@@ -612,11 +681,13 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl
612 public String toString() { 681 public String toString() {
613 if (eIsProxy()) return super.toString(); 682 if (eIsProxy()) return super.toString();
614 683
615 StringBuffer result = new StringBuffer(super.toString()); 684 StringBuilder result = new StringBuilder(super.toString());
616 result.append(" (minNewElements: "); 685 result.append(" (minNewElements: ");
617 result.append(minNewElements); 686 result.append(minNewElements);
618 result.append(", maxNewElements: "); 687 result.append(", maxNewElements: ");
619 result.append(maxNewElements); 688 result.append(maxNewElements);
689 result.append(", minNewElementsHeuristic: ");
690 result.append(minNewElementsHeuristic);
620 result.append(')'); 691 result.append(')');
621 return result.toString(); 692 return result.toString();
622 } 693 }
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialRelationInterpretationImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialRelationInterpretationImpl.java
index 71aef9af..7ad06504 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialRelationInterpretationImpl.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialRelationInterpretationImpl.java
@@ -106,6 +106,7 @@ public class PartialRelationInterpretationImpl extends MinimalEObjectImpl.Contai
106 * <!-- end-user-doc --> 106 * <!-- end-user-doc -->
107 * @generated 107 * @generated
108 */ 108 */
109 @Override
109 public RelationDeclaration getInterpretationOf() { 110 public RelationDeclaration getInterpretationOf() {
110 if (interpretationOf != null && interpretationOf.eIsProxy()) { 111 if (interpretationOf != null && interpretationOf.eIsProxy()) {
111 InternalEObject oldInterpretationOf = (InternalEObject)interpretationOf; 112 InternalEObject oldInterpretationOf = (InternalEObject)interpretationOf;
@@ -132,6 +133,7 @@ public class PartialRelationInterpretationImpl extends MinimalEObjectImpl.Contai
132 * <!-- end-user-doc --> 133 * <!-- end-user-doc -->
133 * @generated 134 * @generated
134 */ 135 */
136 @Override
135 public void setInterpretationOf(RelationDeclaration newInterpretationOf) { 137 public void setInterpretationOf(RelationDeclaration newInterpretationOf) {
136 RelationDeclaration oldInterpretationOf = interpretationOf; 138 RelationDeclaration oldInterpretationOf = interpretationOf;
137 interpretationOf = newInterpretationOf; 139 interpretationOf = newInterpretationOf;
@@ -144,6 +146,7 @@ public class PartialRelationInterpretationImpl extends MinimalEObjectImpl.Contai
144 * <!-- end-user-doc --> 146 * <!-- end-user-doc -->
145 * @generated 147 * @generated
146 */ 148 */
149 @Override
147 public EList<RelationLink> getRelationlinks() { 150 public EList<RelationLink> getRelationlinks() {
148 if (relationlinks == null) { 151 if (relationlinks == null) {
149 relationlinks = new EObjectContainmentEList<RelationLink>(RelationLink.class, this, PartialinterpretationPackage.PARTIAL_RELATION_INTERPRETATION__RELATIONLINKS); 152 relationlinks = new EObjectContainmentEList<RelationLink>(RelationLink.class, this, PartialinterpretationPackage.PARTIAL_RELATION_INTERPRETATION__RELATIONLINKS);
@@ -156,6 +159,7 @@ public class PartialRelationInterpretationImpl extends MinimalEObjectImpl.Contai
156 * <!-- end-user-doc --> 159 * <!-- end-user-doc -->
157 * @generated 160 * @generated
158 */ 161 */
162 @Override
159 public TypeReference getParam1() { 163 public TypeReference getParam1() {
160 if (param1 != null && param1.eIsProxy()) { 164 if (param1 != null && param1.eIsProxy()) {
161 InternalEObject oldParam1 = (InternalEObject)param1; 165 InternalEObject oldParam1 = (InternalEObject)param1;
@@ -182,6 +186,7 @@ public class PartialRelationInterpretationImpl extends MinimalEObjectImpl.Contai
182 * <!-- end-user-doc --> 186 * <!-- end-user-doc -->
183 * @generated 187 * @generated
184 */ 188 */
189 @Override
185 public void setParam1(TypeReference newParam1) { 190 public void setParam1(TypeReference newParam1) {
186 TypeReference oldParam1 = param1; 191 TypeReference oldParam1 = param1;
187 param1 = newParam1; 192 param1 = newParam1;
@@ -194,6 +199,7 @@ public class PartialRelationInterpretationImpl extends MinimalEObjectImpl.Contai
194 * <!-- end-user-doc --> 199 * <!-- end-user-doc -->
195 * @generated 200 * @generated
196 */ 201 */
202 @Override
197 public TypeReference getParam2() { 203 public TypeReference getParam2() {
198 if (param2 != null && param2.eIsProxy()) { 204 if (param2 != null && param2.eIsProxy()) {
199 InternalEObject oldParam2 = (InternalEObject)param2; 205 InternalEObject oldParam2 = (InternalEObject)param2;
@@ -220,6 +226,7 @@ public class PartialRelationInterpretationImpl extends MinimalEObjectImpl.Contai
220 * <!-- end-user-doc --> 226 * <!-- end-user-doc -->
221 * @generated 227 * @generated
222 */ 228 */
229 @Override
223 public void setParam2(TypeReference newParam2) { 230 public void setParam2(TypeReference newParam2) {
224 TypeReference oldParam2 = param2; 231 TypeReference oldParam2 = param2;
225 param2 = newParam2; 232 param2 = newParam2;
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialTypeInterpratationImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialTypeInterpratationImpl.java
index da9b1472..51eabd2c 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialTypeInterpratationImpl.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialTypeInterpratationImpl.java
@@ -76,6 +76,7 @@ public abstract class PartialTypeInterpratationImpl extends MinimalEObjectImpl.C
76 * <!-- end-user-doc --> 76 * <!-- end-user-doc -->
77 * @generated 77 * @generated
78 */ 78 */
79 @Override
79 public EList<DefinedElement> getElements() { 80 public EList<DefinedElement> getElements() {
80 if (elements == null) { 81 if (elements == null) {
81 elements = new EObjectResolvingEList<DefinedElement>(DefinedElement.class, this, PartialinterpretationPackage.PARTIAL_TYPE_INTERPRATATION__ELEMENTS); 82 elements = new EObjectResolvingEList<DefinedElement>(DefinedElement.class, this, PartialinterpretationPackage.PARTIAL_TYPE_INTERPRATATION__ELEMENTS);
@@ -88,6 +89,7 @@ public abstract class PartialTypeInterpratationImpl extends MinimalEObjectImpl.C
88 * <!-- end-user-doc --> 89 * <!-- end-user-doc -->
89 * @generated 90 * @generated
90 */ 91 */
92 @Override
91 public EList<Scope> getScopes() { 93 public EList<Scope> getScopes() {
92 if (scopes == null) { 94 if (scopes == null) {
93 scopes = new EObjectWithInverseResolvingEList<Scope>(Scope.class, this, PartialinterpretationPackage.PARTIAL_TYPE_INTERPRATATION__SCOPES, PartialinterpretationPackage.SCOPE__TARGET_TYPE_INTERPRETATION); 95 scopes = new EObjectWithInverseResolvingEList<Scope>(Scope.class, this, PartialinterpretationPackage.PARTIAL_TYPE_INTERPRATATION__SCOPES, PartialinterpretationPackage.SCOPE__TARGET_TYPE_INTERPRETATION);
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialinterpretationFactoryImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialinterpretationFactoryImpl.java
index af1db8a1..06ca4e37 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialinterpretationFactoryImpl.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialinterpretationFactoryImpl.java
@@ -84,6 +84,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa
84 * <!-- end-user-doc --> 84 * <!-- end-user-doc -->
85 * @generated 85 * @generated
86 */ 86 */
87 @Override
87 public PartialInterpretation createPartialInterpretation() { 88 public PartialInterpretation createPartialInterpretation() {
88 PartialInterpretationImpl partialInterpretation = new PartialInterpretationImpl(); 89 PartialInterpretationImpl partialInterpretation = new PartialInterpretationImpl();
89 return partialInterpretation; 90 return partialInterpretation;
@@ -94,6 +95,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa
94 * <!-- end-user-doc --> 95 * <!-- end-user-doc -->
95 * @generated 96 * @generated
96 */ 97 */
98 @Override
97 public PartialConstantInterpretation createPartialConstantInterpretation() { 99 public PartialConstantInterpretation createPartialConstantInterpretation() {
98 PartialConstantInterpretationImpl partialConstantInterpretation = new PartialConstantInterpretationImpl(); 100 PartialConstantInterpretationImpl partialConstantInterpretation = new PartialConstantInterpretationImpl();
99 return partialConstantInterpretation; 101 return partialConstantInterpretation;
@@ -104,6 +106,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa
104 * <!-- end-user-doc --> 106 * <!-- end-user-doc -->
105 * @generated 107 * @generated
106 */ 108 */
109 @Override
107 public PartialRelationInterpretation createPartialRelationInterpretation() { 110 public PartialRelationInterpretation createPartialRelationInterpretation() {
108 PartialRelationInterpretationImpl partialRelationInterpretation = new PartialRelationInterpretationImpl(); 111 PartialRelationInterpretationImpl partialRelationInterpretation = new PartialRelationInterpretationImpl();
109 return partialRelationInterpretation; 112 return partialRelationInterpretation;
@@ -114,6 +117,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa
114 * <!-- end-user-doc --> 117 * <!-- end-user-doc -->
115 * @generated 118 * @generated
116 */ 119 */
120 @Override
117 public PartialFunctionInterpretation createPartialFunctionInterpretation() { 121 public PartialFunctionInterpretation createPartialFunctionInterpretation() {
118 PartialFunctionInterpretationImpl partialFunctionInterpretation = new PartialFunctionInterpretationImpl(); 122 PartialFunctionInterpretationImpl partialFunctionInterpretation = new PartialFunctionInterpretationImpl();
119 return partialFunctionInterpretation; 123 return partialFunctionInterpretation;
@@ -124,6 +128,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa
124 * <!-- end-user-doc --> 128 * <!-- end-user-doc -->
125 * @generated 129 * @generated
126 */ 130 */
131 @Override
127 public UnaryElementRelationLink createUnaryElementRelationLink() { 132 public UnaryElementRelationLink createUnaryElementRelationLink() {
128 UnaryElementRelationLinkImpl unaryElementRelationLink = new UnaryElementRelationLinkImpl(); 133 UnaryElementRelationLinkImpl unaryElementRelationLink = new UnaryElementRelationLinkImpl();
129 return unaryElementRelationLink; 134 return unaryElementRelationLink;
@@ -134,6 +139,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa
134 * <!-- end-user-doc --> 139 * <!-- end-user-doc -->
135 * @generated 140 * @generated
136 */ 141 */
142 @Override
137 public BinaryElementRelationLink createBinaryElementRelationLink() { 143 public BinaryElementRelationLink createBinaryElementRelationLink() {
138 BinaryElementRelationLinkImpl binaryElementRelationLink = new BinaryElementRelationLinkImpl(); 144 BinaryElementRelationLinkImpl binaryElementRelationLink = new BinaryElementRelationLinkImpl();
139 return binaryElementRelationLink; 145 return binaryElementRelationLink;
@@ -144,6 +150,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa
144 * <!-- end-user-doc --> 150 * <!-- end-user-doc -->
145 * @generated 151 * @generated
146 */ 152 */
153 @Override
147 public NaryRelationLink createNaryRelationLink() { 154 public NaryRelationLink createNaryRelationLink() {
148 NaryRelationLinkImpl naryRelationLink = new NaryRelationLinkImpl(); 155 NaryRelationLinkImpl naryRelationLink = new NaryRelationLinkImpl();
149 return naryRelationLink; 156 return naryRelationLink;
@@ -154,6 +161,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa
154 * <!-- end-user-doc --> 161 * <!-- end-user-doc -->
155 * @generated 162 * @generated
156 */ 163 */
164 @Override
157 public NaryRelationLinkElement createNaryRelationLinkElement() { 165 public NaryRelationLinkElement createNaryRelationLinkElement() {
158 NaryRelationLinkElementImpl naryRelationLinkElement = new NaryRelationLinkElementImpl(); 166 NaryRelationLinkElementImpl naryRelationLinkElement = new NaryRelationLinkElementImpl();
159 return naryRelationLinkElement; 167 return naryRelationLinkElement;
@@ -164,6 +172,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa
164 * <!-- end-user-doc --> 172 * <!-- end-user-doc -->
165 * @generated 173 * @generated
166 */ 174 */
175 @Override
167 public BooleanElement createBooleanElement() { 176 public BooleanElement createBooleanElement() {
168 BooleanElementImpl booleanElement = new BooleanElementImpl(); 177 BooleanElementImpl booleanElement = new BooleanElementImpl();
169 return booleanElement; 178 return booleanElement;
@@ -174,6 +183,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa
174 * <!-- end-user-doc --> 183 * <!-- end-user-doc -->
175 * @generated 184 * @generated
176 */ 185 */
186 @Override
177 public IntegerElement createIntegerElement() { 187 public IntegerElement createIntegerElement() {
178 IntegerElementImpl integerElement = new IntegerElementImpl(); 188 IntegerElementImpl integerElement = new IntegerElementImpl();
179 return integerElement; 189 return integerElement;
@@ -184,6 +194,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa
184 * <!-- end-user-doc --> 194 * <!-- end-user-doc -->
185 * @generated 195 * @generated
186 */ 196 */
197 @Override
187 public RealElement createRealElement() { 198 public RealElement createRealElement() {
188 RealElementImpl realElement = new RealElementImpl(); 199 RealElementImpl realElement = new RealElementImpl();
189 return realElement; 200 return realElement;
@@ -194,6 +205,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa
194 * <!-- end-user-doc --> 205 * <!-- end-user-doc -->
195 * @generated 206 * @generated
196 */ 207 */
208 @Override
197 public StringElement createStringElement() { 209 public StringElement createStringElement() {
198 StringElementImpl stringElement = new StringElementImpl(); 210 StringElementImpl stringElement = new StringElementImpl();
199 return stringElement; 211 return stringElement;
@@ -204,6 +216,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa
204 * <!-- end-user-doc --> 216 * <!-- end-user-doc -->
205 * @generated 217 * @generated
206 */ 218 */
219 @Override
207 public Scope createScope() { 220 public Scope createScope() {
208 ScopeImpl scope = new ScopeImpl(); 221 ScopeImpl scope = new ScopeImpl();
209 return scope; 222 return scope;
@@ -214,6 +227,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa
214 * <!-- end-user-doc --> 227 * <!-- end-user-doc -->
215 * @generated 228 * @generated
216 */ 229 */
230 @Override
217 public PartialBooleanInterpretation createPartialBooleanInterpretation() { 231 public PartialBooleanInterpretation createPartialBooleanInterpretation() {
218 PartialBooleanInterpretationImpl partialBooleanInterpretation = new PartialBooleanInterpretationImpl(); 232 PartialBooleanInterpretationImpl partialBooleanInterpretation = new PartialBooleanInterpretationImpl();
219 return partialBooleanInterpretation; 233 return partialBooleanInterpretation;
@@ -224,6 +238,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa
224 * <!-- end-user-doc --> 238 * <!-- end-user-doc -->
225 * @generated 239 * @generated
226 */ 240 */
241 @Override
227 public PartialIntegerInterpretation createPartialIntegerInterpretation() { 242 public PartialIntegerInterpretation createPartialIntegerInterpretation() {
228 PartialIntegerInterpretationImpl partialIntegerInterpretation = new PartialIntegerInterpretationImpl(); 243 PartialIntegerInterpretationImpl partialIntegerInterpretation = new PartialIntegerInterpretationImpl();
229 return partialIntegerInterpretation; 244 return partialIntegerInterpretation;
@@ -234,6 +249,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa
234 * <!-- end-user-doc --> 249 * <!-- end-user-doc -->
235 * @generated 250 * @generated
236 */ 251 */
252 @Override
237 public PartialRealInterpretation createPartialRealInterpretation() { 253 public PartialRealInterpretation createPartialRealInterpretation() {
238 PartialRealInterpretationImpl partialRealInterpretation = new PartialRealInterpretationImpl(); 254 PartialRealInterpretationImpl partialRealInterpretation = new PartialRealInterpretationImpl();
239 return partialRealInterpretation; 255 return partialRealInterpretation;
@@ -244,6 +260,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa
244 * <!-- end-user-doc --> 260 * <!-- end-user-doc -->
245 * @generated 261 * @generated
246 */ 262 */
263 @Override
247 public PartialStringInterpretation createPartialStringInterpretation() { 264 public PartialStringInterpretation createPartialStringInterpretation() {
248 PartialStringInterpretationImpl partialStringInterpretation = new PartialStringInterpretationImpl(); 265 PartialStringInterpretationImpl partialStringInterpretation = new PartialStringInterpretationImpl();
249 return partialStringInterpretation; 266 return partialStringInterpretation;
@@ -254,6 +271,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa
254 * <!-- end-user-doc --> 271 * <!-- end-user-doc -->
255 * @generated 272 * @generated
256 */ 273 */
274 @Override
257 public PartialComplexTypeInterpretation createPartialComplexTypeInterpretation() { 275 public PartialComplexTypeInterpretation createPartialComplexTypeInterpretation() {
258 PartialComplexTypeInterpretationImpl partialComplexTypeInterpretation = new PartialComplexTypeInterpretationImpl(); 276 PartialComplexTypeInterpretationImpl partialComplexTypeInterpretation = new PartialComplexTypeInterpretationImpl();
259 return partialComplexTypeInterpretation; 277 return partialComplexTypeInterpretation;
@@ -264,6 +282,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa
264 * <!-- end-user-doc --> 282 * <!-- end-user-doc -->
265 * @generated 283 * @generated
266 */ 284 */
285 @Override
267 public PartialinterpretationPackage getPartialinterpretationPackage() { 286 public PartialinterpretationPackage getPartialinterpretationPackage() {
268 return (PartialinterpretationPackage)getEPackage(); 287 return (PartialinterpretationPackage)getEPackage();
269 } 288 }
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialinterpretationPackageImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialinterpretationPackageImpl.java
index a21dc306..1ea3a11d 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialinterpretationPackageImpl.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialinterpretationPackageImpl.java
@@ -227,7 +227,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
227 227
228 /** 228 /**
229 * Creates, registers, and initializes the <b>Package</b> for this model, and for any others upon which it depends. 229 * Creates, registers, and initializes the <b>Package</b> for this model, and for any others upon which it depends.
230 * 230 *
231 * <p>This method is used to initialize {@link PartialinterpretationPackage#eINSTANCE} when that field is accessed. 231 * <p>This method is used to initialize {@link PartialinterpretationPackage#eINSTANCE} when that field is accessed.
232 * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package. 232 * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package.
233 * <!-- begin-user-doc --> 233 * <!-- begin-user-doc -->
@@ -241,7 +241,8 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
241 if (isInited) return (PartialinterpretationPackage)EPackage.Registry.INSTANCE.getEPackage(PartialinterpretationPackage.eNS_URI); 241 if (isInited) return (PartialinterpretationPackage)EPackage.Registry.INSTANCE.getEPackage(PartialinterpretationPackage.eNS_URI);
242 242
243 // Obtain or create and register package 243 // Obtain or create and register package
244 PartialinterpretationPackageImpl thePartialinterpretationPackage = (PartialinterpretationPackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof PartialinterpretationPackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new PartialinterpretationPackageImpl()); 244 Object registeredPartialinterpretationPackage = EPackage.Registry.INSTANCE.get(eNS_URI);
245 PartialinterpretationPackageImpl thePartialinterpretationPackage = registeredPartialinterpretationPackage instanceof PartialinterpretationPackageImpl ? (PartialinterpretationPackageImpl)registeredPartialinterpretationPackage : new PartialinterpretationPackageImpl();
245 246
246 isInited = true; 247 isInited = true;
247 248
@@ -258,7 +259,6 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
258 // Mark meta-data to indicate it can't be changed 259 // Mark meta-data to indicate it can't be changed
259 thePartialinterpretationPackage.freeze(); 260 thePartialinterpretationPackage.freeze();
260 261
261
262 // Update the registry and return the package 262 // Update the registry and return the package
263 EPackage.Registry.INSTANCE.put(PartialinterpretationPackage.eNS_URI, thePartialinterpretationPackage); 263 EPackage.Registry.INSTANCE.put(PartialinterpretationPackage.eNS_URI, thePartialinterpretationPackage);
264 return thePartialinterpretationPackage; 264 return thePartialinterpretationPackage;
@@ -269,6 +269,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
269 * <!-- end-user-doc --> 269 * <!-- end-user-doc -->
270 * @generated 270 * @generated
271 */ 271 */
272 @Override
272 public EClass getPartialInterpretation() { 273 public EClass getPartialInterpretation() {
273 return partialInterpretationEClass; 274 return partialInterpretationEClass;
274 } 275 }
@@ -278,6 +279,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
278 * <!-- end-user-doc --> 279 * <!-- end-user-doc -->
279 * @generated 280 * @generated
280 */ 281 */
282 @Override
281 public EReference getPartialInterpretation_Problem() { 283 public EReference getPartialInterpretation_Problem() {
282 return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(0); 284 return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(0);
283 } 285 }
@@ -287,6 +289,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
287 * <!-- end-user-doc --> 289 * <!-- end-user-doc -->
288 * @generated 290 * @generated
289 */ 291 */
292 @Override
290 public EReference getPartialInterpretation_Partialconstantinterpretation() { 293 public EReference getPartialInterpretation_Partialconstantinterpretation() {
291 return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(1); 294 return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(1);
292 } 295 }
@@ -296,6 +299,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
296 * <!-- end-user-doc --> 299 * <!-- end-user-doc -->
297 * @generated 300 * @generated
298 */ 301 */
302 @Override
299 public EReference getPartialInterpretation_Partialrelationinterpretation() { 303 public EReference getPartialInterpretation_Partialrelationinterpretation() {
300 return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(2); 304 return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(2);
301 } 305 }
@@ -305,6 +309,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
305 * <!-- end-user-doc --> 309 * <!-- end-user-doc -->
306 * @generated 310 * @generated
307 */ 311 */
312 @Override
308 public EReference getPartialInterpretation_Partialfunctioninterpretation() { 313 public EReference getPartialInterpretation_Partialfunctioninterpretation() {
309 return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(3); 314 return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(3);
310 } 315 }
@@ -314,6 +319,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
314 * <!-- end-user-doc --> 319 * <!-- end-user-doc -->
315 * @generated 320 * @generated
316 */ 321 */
322 @Override
317 public EReference getPartialInterpretation_NewElements() { 323 public EReference getPartialInterpretation_NewElements() {
318 return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(4); 324 return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(4);
319 } 325 }
@@ -323,6 +329,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
323 * <!-- end-user-doc --> 329 * <!-- end-user-doc -->
324 * @generated 330 * @generated
325 */ 331 */
332 @Override
326 public EReference getPartialInterpretation_Partialtypeinterpratation() { 333 public EReference getPartialInterpretation_Partialtypeinterpratation() {
327 return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(5); 334 return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(5);
328 } 335 }
@@ -332,6 +339,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
332 * <!-- end-user-doc --> 339 * <!-- end-user-doc -->
333 * @generated 340 * @generated
334 */ 341 */
342 @Override
335 public EReference getPartialInterpretation_OpenWorldElements() { 343 public EReference getPartialInterpretation_OpenWorldElements() {
336 return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(6); 344 return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(6);
337 } 345 }
@@ -341,6 +349,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
341 * <!-- end-user-doc --> 349 * <!-- end-user-doc -->
342 * @generated 350 * @generated
343 */ 351 */
352 @Override
344 public EReference getPartialInterpretation_ProblemConainer() { 353 public EReference getPartialInterpretation_ProblemConainer() {
345 return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(7); 354 return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(7);
346 } 355 }
@@ -350,6 +359,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
350 * <!-- end-user-doc --> 359 * <!-- end-user-doc -->
351 * @generated 360 * @generated
352 */ 361 */
362 @Override
353 public EReference getPartialInterpretation_Scopes() { 363 public EReference getPartialInterpretation_Scopes() {
354 return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(8); 364 return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(8);
355 } 365 }
@@ -359,6 +369,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
359 * <!-- end-user-doc --> 369 * <!-- end-user-doc -->
360 * @generated 370 * @generated
361 */ 371 */
372 @Override
362 public EAttribute getPartialInterpretation_MinNewElements() { 373 public EAttribute getPartialInterpretation_MinNewElements() {
363 return (EAttribute)partialInterpretationEClass.getEStructuralFeatures().get(9); 374 return (EAttribute)partialInterpretationEClass.getEStructuralFeatures().get(9);
364 } 375 }
@@ -368,6 +379,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
368 * <!-- end-user-doc --> 379 * <!-- end-user-doc -->
369 * @generated 380 * @generated
370 */ 381 */
382 @Override
371 public EAttribute getPartialInterpretation_MaxNewElements() { 383 public EAttribute getPartialInterpretation_MaxNewElements() {
372 return (EAttribute)partialInterpretationEClass.getEStructuralFeatures().get(10); 384 return (EAttribute)partialInterpretationEClass.getEStructuralFeatures().get(10);
373 } 385 }
@@ -377,6 +389,17 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
377 * <!-- end-user-doc --> 389 * <!-- end-user-doc -->
378 * @generated 390 * @generated
379 */ 391 */
392 @Override
393 public EAttribute getPartialInterpretation_MinNewElementsHeuristic() {
394 return (EAttribute)partialInterpretationEClass.getEStructuralFeatures().get(11);
395 }
396
397 /**
398 * <!-- begin-user-doc -->
399 * <!-- end-user-doc -->
400 * @generated
401 */
402 @Override
380 public EClass getPartialConstantInterpretation() { 403 public EClass getPartialConstantInterpretation() {
381 return partialConstantInterpretationEClass; 404 return partialConstantInterpretationEClass;
382 } 405 }
@@ -386,6 +409,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
386 * <!-- end-user-doc --> 409 * <!-- end-user-doc -->
387 * @generated 410 * @generated
388 */ 411 */
412 @Override
389 public EReference getPartialConstantInterpretation_InterpretationOf() { 413 public EReference getPartialConstantInterpretation_InterpretationOf() {
390 return (EReference)partialConstantInterpretationEClass.getEStructuralFeatures().get(0); 414 return (EReference)partialConstantInterpretationEClass.getEStructuralFeatures().get(0);
391 } 415 }
@@ -395,6 +419,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
395 * <!-- end-user-doc --> 419 * <!-- end-user-doc -->
396 * @generated 420 * @generated
397 */ 421 */
422 @Override
398 public EClass getPartialRelationInterpretation() { 423 public EClass getPartialRelationInterpretation() {
399 return partialRelationInterpretationEClass; 424 return partialRelationInterpretationEClass;
400 } 425 }
@@ -404,6 +429,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
404 * <!-- end-user-doc --> 429 * <!-- end-user-doc -->
405 * @generated 430 * @generated
406 */ 431 */
432 @Override
407 public EReference getPartialRelationInterpretation_InterpretationOf() { 433 public EReference getPartialRelationInterpretation_InterpretationOf() {
408 return (EReference)partialRelationInterpretationEClass.getEStructuralFeatures().get(0); 434 return (EReference)partialRelationInterpretationEClass.getEStructuralFeatures().get(0);
409 } 435 }
@@ -413,6 +439,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
413 * <!-- end-user-doc --> 439 * <!-- end-user-doc -->
414 * @generated 440 * @generated
415 */ 441 */
442 @Override
416 public EReference getPartialRelationInterpretation_Relationlinks() { 443 public EReference getPartialRelationInterpretation_Relationlinks() {
417 return (EReference)partialRelationInterpretationEClass.getEStructuralFeatures().get(1); 444 return (EReference)partialRelationInterpretationEClass.getEStructuralFeatures().get(1);
418 } 445 }
@@ -422,6 +449,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
422 * <!-- end-user-doc --> 449 * <!-- end-user-doc -->
423 * @generated 450 * @generated
424 */ 451 */
452 @Override
425 public EReference getPartialRelationInterpretation_Param1() { 453 public EReference getPartialRelationInterpretation_Param1() {
426 return (EReference)partialRelationInterpretationEClass.getEStructuralFeatures().get(2); 454 return (EReference)partialRelationInterpretationEClass.getEStructuralFeatures().get(2);
427 } 455 }
@@ -431,6 +459,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
431 * <!-- end-user-doc --> 459 * <!-- end-user-doc -->
432 * @generated 460 * @generated
433 */ 461 */
462 @Override
434 public EReference getPartialRelationInterpretation_Param2() { 463 public EReference getPartialRelationInterpretation_Param2() {
435 return (EReference)partialRelationInterpretationEClass.getEStructuralFeatures().get(3); 464 return (EReference)partialRelationInterpretationEClass.getEStructuralFeatures().get(3);
436 } 465 }
@@ -440,6 +469,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
440 * <!-- end-user-doc --> 469 * <!-- end-user-doc -->
441 * @generated 470 * @generated
442 */ 471 */
472 @Override
443 public EClass getPartialFunctionInterpretation() { 473 public EClass getPartialFunctionInterpretation() {
444 return partialFunctionInterpretationEClass; 474 return partialFunctionInterpretationEClass;
445 } 475 }
@@ -449,6 +479,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
449 * <!-- end-user-doc --> 479 * <!-- end-user-doc -->
450 * @generated 480 * @generated
451 */ 481 */
482 @Override
452 public EReference getPartialFunctionInterpretation_InterpretationOf() { 483 public EReference getPartialFunctionInterpretation_InterpretationOf() {
453 return (EReference)partialFunctionInterpretationEClass.getEStructuralFeatures().get(0); 484 return (EReference)partialFunctionInterpretationEClass.getEStructuralFeatures().get(0);
454 } 485 }
@@ -458,6 +489,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
458 * <!-- end-user-doc --> 489 * <!-- end-user-doc -->
459 * @generated 490 * @generated
460 */ 491 */
492 @Override
461 public EClass getPartialTypeInterpratation() { 493 public EClass getPartialTypeInterpratation() {
462 return partialTypeInterpratationEClass; 494 return partialTypeInterpratationEClass;
463 } 495 }
@@ -467,6 +499,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
467 * <!-- end-user-doc --> 499 * <!-- end-user-doc -->
468 * @generated 500 * @generated
469 */ 501 */
502 @Override
470 public EReference getPartialTypeInterpratation_Elements() { 503 public EReference getPartialTypeInterpratation_Elements() {
471 return (EReference)partialTypeInterpratationEClass.getEStructuralFeatures().get(0); 504 return (EReference)partialTypeInterpratationEClass.getEStructuralFeatures().get(0);
472 } 505 }
@@ -476,6 +509,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
476 * <!-- end-user-doc --> 509 * <!-- end-user-doc -->
477 * @generated 510 * @generated
478 */ 511 */
512 @Override
479 public EReference getPartialTypeInterpratation_Scopes() { 513 public EReference getPartialTypeInterpratation_Scopes() {
480 return (EReference)partialTypeInterpratationEClass.getEStructuralFeatures().get(1); 514 return (EReference)partialTypeInterpratationEClass.getEStructuralFeatures().get(1);
481 } 515 }
@@ -485,6 +519,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
485 * <!-- end-user-doc --> 519 * <!-- end-user-doc -->
486 * @generated 520 * @generated
487 */ 521 */
522 @Override
488 public EClass getRelationLink() { 523 public EClass getRelationLink() {
489 return relationLinkEClass; 524 return relationLinkEClass;
490 } 525 }
@@ -494,6 +529,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
494 * <!-- end-user-doc --> 529 * <!-- end-user-doc -->
495 * @generated 530 * @generated
496 */ 531 */
532 @Override
497 public EClass getUnaryElementRelationLink() { 533 public EClass getUnaryElementRelationLink() {
498 return unaryElementRelationLinkEClass; 534 return unaryElementRelationLinkEClass;
499 } 535 }
@@ -503,6 +539,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
503 * <!-- end-user-doc --> 539 * <!-- end-user-doc -->
504 * @generated 540 * @generated
505 */ 541 */
542 @Override
506 public EReference getUnaryElementRelationLink_Param1() { 543 public EReference getUnaryElementRelationLink_Param1() {
507 return (EReference)unaryElementRelationLinkEClass.getEStructuralFeatures().get(0); 544 return (EReference)unaryElementRelationLinkEClass.getEStructuralFeatures().get(0);
508 } 545 }
@@ -512,6 +549,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
512 * <!-- end-user-doc --> 549 * <!-- end-user-doc -->
513 * @generated 550 * @generated
514 */ 551 */
552 @Override
515 public EClass getBinaryElementRelationLink() { 553 public EClass getBinaryElementRelationLink() {
516 return binaryElementRelationLinkEClass; 554 return binaryElementRelationLinkEClass;
517 } 555 }
@@ -521,6 +559,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
521 * <!-- end-user-doc --> 559 * <!-- end-user-doc -->
522 * @generated 560 * @generated
523 */ 561 */
562 @Override
524 public EReference getBinaryElementRelationLink_Param1() { 563 public EReference getBinaryElementRelationLink_Param1() {
525 return (EReference)binaryElementRelationLinkEClass.getEStructuralFeatures().get(0); 564 return (EReference)binaryElementRelationLinkEClass.getEStructuralFeatures().get(0);
526 } 565 }
@@ -530,6 +569,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
530 * <!-- end-user-doc --> 569 * <!-- end-user-doc -->
531 * @generated 570 * @generated
532 */ 571 */
572 @Override
533 public EReference getBinaryElementRelationLink_Param2() { 573 public EReference getBinaryElementRelationLink_Param2() {
534 return (EReference)binaryElementRelationLinkEClass.getEStructuralFeatures().get(1); 574 return (EReference)binaryElementRelationLinkEClass.getEStructuralFeatures().get(1);
535 } 575 }
@@ -539,6 +579,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
539 * <!-- end-user-doc --> 579 * <!-- end-user-doc -->
540 * @generated 580 * @generated
541 */ 581 */
582 @Override
542 public EClass getNaryRelationLink() { 583 public EClass getNaryRelationLink() {
543 return naryRelationLinkEClass; 584 return naryRelationLinkEClass;
544 } 585 }
@@ -548,6 +589,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
548 * <!-- end-user-doc --> 589 * <!-- end-user-doc -->
549 * @generated 590 * @generated
550 */ 591 */
592 @Override
551 public EReference getNaryRelationLink_Elements() { 593 public EReference getNaryRelationLink_Elements() {
552 return (EReference)naryRelationLinkEClass.getEStructuralFeatures().get(0); 594 return (EReference)naryRelationLinkEClass.getEStructuralFeatures().get(0);
553 } 595 }
@@ -557,6 +599,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
557 * <!-- end-user-doc --> 599 * <!-- end-user-doc -->
558 * @generated 600 * @generated
559 */ 601 */
602 @Override
560 public EClass getNaryRelationLinkElement() { 603 public EClass getNaryRelationLinkElement() {
561 return naryRelationLinkElementEClass; 604 return naryRelationLinkElementEClass;
562 } 605 }
@@ -566,6 +609,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
566 * <!-- end-user-doc --> 609 * <!-- end-user-doc -->
567 * @generated 610 * @generated
568 */ 611 */
612 @Override
569 public EAttribute getNaryRelationLinkElement_Index() { 613 public EAttribute getNaryRelationLinkElement_Index() {
570 return (EAttribute)naryRelationLinkElementEClass.getEStructuralFeatures().get(0); 614 return (EAttribute)naryRelationLinkElementEClass.getEStructuralFeatures().get(0);
571 } 615 }
@@ -575,6 +619,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
575 * <!-- end-user-doc --> 619 * <!-- end-user-doc -->
576 * @generated 620 * @generated
577 */ 621 */
622 @Override
578 public EReference getNaryRelationLinkElement_Param() { 623 public EReference getNaryRelationLinkElement_Param() {
579 return (EReference)naryRelationLinkElementEClass.getEStructuralFeatures().get(1); 624 return (EReference)naryRelationLinkElementEClass.getEStructuralFeatures().get(1);
580 } 625 }
@@ -584,6 +629,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
584 * <!-- end-user-doc --> 629 * <!-- end-user-doc -->
585 * @generated 630 * @generated
586 */ 631 */
632 @Override
587 public EClass getPrimitiveElement() { 633 public EClass getPrimitiveElement() {
588 return primitiveElementEClass; 634 return primitiveElementEClass;
589 } 635 }
@@ -593,6 +639,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
593 * <!-- end-user-doc --> 639 * <!-- end-user-doc -->
594 * @generated 640 * @generated
595 */ 641 */
642 @Override
596 public EAttribute getPrimitiveElement_ValueSet() { 643 public EAttribute getPrimitiveElement_ValueSet() {
597 return (EAttribute)primitiveElementEClass.getEStructuralFeatures().get(0); 644 return (EAttribute)primitiveElementEClass.getEStructuralFeatures().get(0);
598 } 645 }
@@ -602,6 +649,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
602 * <!-- end-user-doc --> 649 * <!-- end-user-doc -->
603 * @generated 650 * @generated
604 */ 651 */
652 @Override
605 public EClass getBooleanElement() { 653 public EClass getBooleanElement() {
606 return booleanElementEClass; 654 return booleanElementEClass;
607 } 655 }
@@ -611,6 +659,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
611 * <!-- end-user-doc --> 659 * <!-- end-user-doc -->
612 * @generated 660 * @generated
613 */ 661 */
662 @Override
614 public EAttribute getBooleanElement_Value() { 663 public EAttribute getBooleanElement_Value() {
615 return (EAttribute)booleanElementEClass.getEStructuralFeatures().get(0); 664 return (EAttribute)booleanElementEClass.getEStructuralFeatures().get(0);
616 } 665 }
@@ -620,6 +669,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
620 * <!-- end-user-doc --> 669 * <!-- end-user-doc -->
621 * @generated 670 * @generated
622 */ 671 */
672 @Override
623 public EClass getIntegerElement() { 673 public EClass getIntegerElement() {
624 return integerElementEClass; 674 return integerElementEClass;
625 } 675 }
@@ -629,6 +679,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
629 * <!-- end-user-doc --> 679 * <!-- end-user-doc -->
630 * @generated 680 * @generated
631 */ 681 */
682 @Override
632 public EAttribute getIntegerElement_Value() { 683 public EAttribute getIntegerElement_Value() {
633 return (EAttribute)integerElementEClass.getEStructuralFeatures().get(0); 684 return (EAttribute)integerElementEClass.getEStructuralFeatures().get(0);
634 } 685 }
@@ -638,6 +689,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
638 * <!-- end-user-doc --> 689 * <!-- end-user-doc -->
639 * @generated 690 * @generated
640 */ 691 */
692 @Override
641 public EClass getRealElement() { 693 public EClass getRealElement() {
642 return realElementEClass; 694 return realElementEClass;
643 } 695 }
@@ -647,6 +699,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
647 * <!-- end-user-doc --> 699 * <!-- end-user-doc -->
648 * @generated 700 * @generated
649 */ 701 */
702 @Override
650 public EAttribute getRealElement_Value() { 703 public EAttribute getRealElement_Value() {
651 return (EAttribute)realElementEClass.getEStructuralFeatures().get(0); 704 return (EAttribute)realElementEClass.getEStructuralFeatures().get(0);
652 } 705 }
@@ -656,6 +709,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
656 * <!-- end-user-doc --> 709 * <!-- end-user-doc -->
657 * @generated 710 * @generated
658 */ 711 */
712 @Override
659 public EClass getStringElement() { 713 public EClass getStringElement() {
660 return stringElementEClass; 714 return stringElementEClass;
661 } 715 }
@@ -665,6 +719,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
665 * <!-- end-user-doc --> 719 * <!-- end-user-doc -->
666 * @generated 720 * @generated
667 */ 721 */
722 @Override
668 public EAttribute getStringElement_Value() { 723 public EAttribute getStringElement_Value() {
669 return (EAttribute)stringElementEClass.getEStructuralFeatures().get(0); 724 return (EAttribute)stringElementEClass.getEStructuralFeatures().get(0);
670 } 725 }
@@ -674,6 +729,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
674 * <!-- end-user-doc --> 729 * <!-- end-user-doc -->
675 * @generated 730 * @generated
676 */ 731 */
732 @Override
677 public EClass getScope() { 733 public EClass getScope() {
678 return scopeEClass; 734 return scopeEClass;
679 } 735 }
@@ -683,6 +739,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
683 * <!-- end-user-doc --> 739 * <!-- end-user-doc -->
684 * @generated 740 * @generated
685 */ 741 */
742 @Override
686 public EAttribute getScope_MinNewElements() { 743 public EAttribute getScope_MinNewElements() {
687 return (EAttribute)scopeEClass.getEStructuralFeatures().get(0); 744 return (EAttribute)scopeEClass.getEStructuralFeatures().get(0);
688 } 745 }
@@ -692,6 +749,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
692 * <!-- end-user-doc --> 749 * <!-- end-user-doc -->
693 * @generated 750 * @generated
694 */ 751 */
752 @Override
695 public EAttribute getScope_MaxNewElements() { 753 public EAttribute getScope_MaxNewElements() {
696 return (EAttribute)scopeEClass.getEStructuralFeatures().get(1); 754 return (EAttribute)scopeEClass.getEStructuralFeatures().get(1);
697 } 755 }
@@ -701,6 +759,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
701 * <!-- end-user-doc --> 759 * <!-- end-user-doc -->
702 * @generated 760 * @generated
703 */ 761 */
762 @Override
704 public EReference getScope_TargetTypeInterpretation() { 763 public EReference getScope_TargetTypeInterpretation() {
705 return (EReference)scopeEClass.getEStructuralFeatures().get(2); 764 return (EReference)scopeEClass.getEStructuralFeatures().get(2);
706 } 765 }
@@ -710,6 +769,17 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
710 * <!-- end-user-doc --> 769 * <!-- end-user-doc -->
711 * @generated 770 * @generated
712 */ 771 */
772 @Override
773 public EAttribute getScope_MinNewElementsHeuristic() {
774 return (EAttribute)scopeEClass.getEStructuralFeatures().get(3);
775 }
776
777 /**
778 * <!-- begin-user-doc -->
779 * <!-- end-user-doc -->
780 * @generated
781 */
782 @Override
713 public EClass getPartialPrimitiveInterpretation() { 783 public EClass getPartialPrimitiveInterpretation() {
714 return partialPrimitiveInterpretationEClass; 784 return partialPrimitiveInterpretationEClass;
715 } 785 }
@@ -719,6 +789,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
719 * <!-- end-user-doc --> 789 * <!-- end-user-doc -->
720 * @generated 790 * @generated
721 */ 791 */
792 @Override
722 public EClass getPartialBooleanInterpretation() { 793 public EClass getPartialBooleanInterpretation() {
723 return partialBooleanInterpretationEClass; 794 return partialBooleanInterpretationEClass;
724 } 795 }
@@ -728,6 +799,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
728 * <!-- end-user-doc --> 799 * <!-- end-user-doc -->
729 * @generated 800 * @generated
730 */ 801 */
802 @Override
731 public EClass getPartialIntegerInterpretation() { 803 public EClass getPartialIntegerInterpretation() {
732 return partialIntegerInterpretationEClass; 804 return partialIntegerInterpretationEClass;
733 } 805 }
@@ -737,6 +809,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
737 * <!-- end-user-doc --> 809 * <!-- end-user-doc -->
738 * @generated 810 * @generated
739 */ 811 */
812 @Override
740 public EClass getPartialRealInterpretation() { 813 public EClass getPartialRealInterpretation() {
741 return partialRealInterpretationEClass; 814 return partialRealInterpretationEClass;
742 } 815 }
@@ -746,6 +819,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
746 * <!-- end-user-doc --> 819 * <!-- end-user-doc -->
747 * @generated 820 * @generated
748 */ 821 */
822 @Override
749 public EClass getPartialStringInterpretation() { 823 public EClass getPartialStringInterpretation() {
750 return partialStringInterpretationEClass; 824 return partialStringInterpretationEClass;
751 } 825 }
@@ -755,6 +829,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
755 * <!-- end-user-doc --> 829 * <!-- end-user-doc -->
756 * @generated 830 * @generated
757 */ 831 */
832 @Override
758 public EClass getPartialComplexTypeInterpretation() { 833 public EClass getPartialComplexTypeInterpretation() {
759 return partialComplexTypeInterpretationEClass; 834 return partialComplexTypeInterpretationEClass;
760 } 835 }
@@ -764,6 +839,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
764 * <!-- end-user-doc --> 839 * <!-- end-user-doc -->
765 * @generated 840 * @generated
766 */ 841 */
842 @Override
767 public EReference getPartialComplexTypeInterpretation_SupertypeInterpretation() { 843 public EReference getPartialComplexTypeInterpretation_SupertypeInterpretation() {
768 return (EReference)partialComplexTypeInterpretationEClass.getEStructuralFeatures().get(0); 844 return (EReference)partialComplexTypeInterpretationEClass.getEStructuralFeatures().get(0);
769 } 845 }
@@ -773,6 +849,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
773 * <!-- end-user-doc --> 849 * <!-- end-user-doc -->
774 * @generated 850 * @generated
775 */ 851 */
852 @Override
776 public EReference getPartialComplexTypeInterpretation_InterpretationOf() { 853 public EReference getPartialComplexTypeInterpretation_InterpretationOf() {
777 return (EReference)partialComplexTypeInterpretationEClass.getEStructuralFeatures().get(1); 854 return (EReference)partialComplexTypeInterpretationEClass.getEStructuralFeatures().get(1);
778 } 855 }
@@ -782,6 +859,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
782 * <!-- end-user-doc --> 859 * <!-- end-user-doc -->
783 * @generated 860 * @generated
784 */ 861 */
862 @Override
785 public PartialinterpretationFactory getPartialinterpretationFactory() { 863 public PartialinterpretationFactory getPartialinterpretationFactory() {
786 return (PartialinterpretationFactory)getEFactoryInstance(); 864 return (PartialinterpretationFactory)getEFactoryInstance();
787 } 865 }
@@ -817,6 +895,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
817 createEReference(partialInterpretationEClass, PARTIAL_INTERPRETATION__SCOPES); 895 createEReference(partialInterpretationEClass, PARTIAL_INTERPRETATION__SCOPES);
818 createEAttribute(partialInterpretationEClass, PARTIAL_INTERPRETATION__MIN_NEW_ELEMENTS); 896 createEAttribute(partialInterpretationEClass, PARTIAL_INTERPRETATION__MIN_NEW_ELEMENTS);
819 createEAttribute(partialInterpretationEClass, PARTIAL_INTERPRETATION__MAX_NEW_ELEMENTS); 897 createEAttribute(partialInterpretationEClass, PARTIAL_INTERPRETATION__MAX_NEW_ELEMENTS);
898 createEAttribute(partialInterpretationEClass, PARTIAL_INTERPRETATION__MIN_NEW_ELEMENTS_HEURISTIC);
820 899
821 partialConstantInterpretationEClass = createEClass(PARTIAL_CONSTANT_INTERPRETATION); 900 partialConstantInterpretationEClass = createEClass(PARTIAL_CONSTANT_INTERPRETATION);
822 createEReference(partialConstantInterpretationEClass, PARTIAL_CONSTANT_INTERPRETATION__INTERPRETATION_OF); 901 createEReference(partialConstantInterpretationEClass, PARTIAL_CONSTANT_INTERPRETATION__INTERPRETATION_OF);
@@ -869,6 +948,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
869 createEAttribute(scopeEClass, SCOPE__MIN_NEW_ELEMENTS); 948 createEAttribute(scopeEClass, SCOPE__MIN_NEW_ELEMENTS);
870 createEAttribute(scopeEClass, SCOPE__MAX_NEW_ELEMENTS); 949 createEAttribute(scopeEClass, SCOPE__MAX_NEW_ELEMENTS);
871 createEReference(scopeEClass, SCOPE__TARGET_TYPE_INTERPRETATION); 950 createEReference(scopeEClass, SCOPE__TARGET_TYPE_INTERPRETATION);
951 createEAttribute(scopeEClass, SCOPE__MIN_NEW_ELEMENTS_HEURISTIC);
872 952
873 partialPrimitiveInterpretationEClass = createEClass(PARTIAL_PRIMITIVE_INTERPRETATION); 953 partialPrimitiveInterpretationEClass = createEClass(PARTIAL_PRIMITIVE_INTERPRETATION);
874 954
@@ -945,6 +1025,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
945 initEReference(getPartialInterpretation_Scopes(), this.getScope(), null, "scopes", null, 0, -1, PartialInterpretation.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); 1025 initEReference(getPartialInterpretation_Scopes(), this.getScope(), null, "scopes", null, 0, -1, PartialInterpretation.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
946 initEAttribute(getPartialInterpretation_MinNewElements(), ecorePackage.getEInt(), "minNewElements", "0", 1, 1, PartialInterpretation.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); 1026 initEAttribute(getPartialInterpretation_MinNewElements(), ecorePackage.getEInt(), "minNewElements", "0", 1, 1, PartialInterpretation.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
947 initEAttribute(getPartialInterpretation_MaxNewElements(), ecorePackage.getEInt(), "maxNewElements", "-1", 1, 1, PartialInterpretation.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); 1027 initEAttribute(getPartialInterpretation_MaxNewElements(), ecorePackage.getEInt(), "maxNewElements", "-1", 1, 1, PartialInterpretation.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
1028 initEAttribute(getPartialInterpretation_MinNewElementsHeuristic(), ecorePackage.getEInt(), "minNewElementsHeuristic", "0", 1, 1, PartialInterpretation.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
948 1029
949 initEClass(partialConstantInterpretationEClass, PartialConstantInterpretation.class, "PartialConstantInterpretation", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); 1030 initEClass(partialConstantInterpretationEClass, PartialConstantInterpretation.class, "PartialConstantInterpretation", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
950 initEReference(getPartialConstantInterpretation_InterpretationOf(), theLogiclanguagePackage.getConstantDeclaration(), null, "interpretationOf", null, 1, 1, PartialConstantInterpretation.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); 1031 initEReference(getPartialConstantInterpretation_InterpretationOf(), theLogiclanguagePackage.getConstantDeclaration(), null, "interpretationOf", null, 1, 1, PartialConstantInterpretation.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
@@ -997,6 +1078,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa
997 initEAttribute(getScope_MinNewElements(), ecorePackage.getEInt(), "minNewElements", "0", 1, 1, Scope.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); 1078 initEAttribute(getScope_MinNewElements(), ecorePackage.getEInt(), "minNewElements", "0", 1, 1, Scope.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
998 initEAttribute(getScope_MaxNewElements(), ecorePackage.getEInt(), "maxNewElements", "-1", 1, 1, Scope.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); 1079 initEAttribute(getScope_MaxNewElements(), ecorePackage.getEInt(), "maxNewElements", "-1", 1, 1, Scope.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
999 initEReference(getScope_TargetTypeInterpretation(), this.getPartialTypeInterpratation(), this.getPartialTypeInterpratation_Scopes(), "targetTypeInterpretation", null, 1, 1, Scope.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); 1080 initEReference(getScope_TargetTypeInterpretation(), this.getPartialTypeInterpratation(), this.getPartialTypeInterpratation_Scopes(), "targetTypeInterpretation", null, 1, 1, Scope.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
1081 initEAttribute(getScope_MinNewElementsHeuristic(), ecorePackage.getEInt(), "minNewElementsHeuristic", "0", 1, 1, Scope.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
1000 1082
1001 initEClass(partialPrimitiveInterpretationEClass, PartialPrimitiveInterpretation.class, "PartialPrimitiveInterpretation", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); 1083 initEClass(partialPrimitiveInterpretationEClass, PartialPrimitiveInterpretation.class, "PartialPrimitiveInterpretation", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
1002 1084
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PrimitiveElementImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PrimitiveElementImpl.java
index 29a1e1be..a8ef81b0 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PrimitiveElementImpl.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PrimitiveElementImpl.java
@@ -71,6 +71,7 @@ public abstract class PrimitiveElementImpl extends DefinedElementImpl implements
71 * <!-- end-user-doc --> 71 * <!-- end-user-doc -->
72 * @generated 72 * @generated
73 */ 73 */
74 @Override
74 public boolean isValueSet() { 75 public boolean isValueSet() {
75 return valueSet; 76 return valueSet;
76 } 77 }
@@ -80,6 +81,7 @@ public abstract class PrimitiveElementImpl extends DefinedElementImpl implements
80 * <!-- end-user-doc --> 81 * <!-- end-user-doc -->
81 * @generated 82 * @generated
82 */ 83 */
84 @Override
83 public void setValueSet(boolean newValueSet) { 85 public void setValueSet(boolean newValueSet) {
84 boolean oldValueSet = valueSet; 86 boolean oldValueSet = valueSet;
85 valueSet = newValueSet; 87 valueSet = newValueSet;
@@ -154,7 +156,7 @@ public abstract class PrimitiveElementImpl extends DefinedElementImpl implements
154 public String toString() { 156 public String toString() {
155 if (eIsProxy()) return super.toString(); 157 if (eIsProxy()) return super.toString();
156 158
157 StringBuffer result = new StringBuffer(super.toString()); 159 StringBuilder result = new StringBuilder(super.toString());
158 result.append(" (valueSet: "); 160 result.append(" (valueSet: ");
159 result.append(valueSet); 161 result.append(valueSet);
160 result.append(')'); 162 result.append(')');
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/RealElementImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/RealElementImpl.java
index 0361a3e9..67cff5a2 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/RealElementImpl.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/RealElementImpl.java
@@ -71,6 +71,7 @@ public class RealElementImpl extends PrimitiveElementImpl implements RealElement
71 * <!-- end-user-doc --> 71 * <!-- end-user-doc -->
72 * @generated 72 * @generated
73 */ 73 */
74 @Override
74 public BigDecimal getValue() { 75 public BigDecimal getValue() {
75 return value; 76 return value;
76 } 77 }
@@ -80,6 +81,7 @@ public class RealElementImpl extends PrimitiveElementImpl implements RealElement
80 * <!-- end-user-doc --> 81 * <!-- end-user-doc -->
81 * @generated 82 * @generated
82 */ 83 */
84 @Override
83 public void setValue(BigDecimal newValue) { 85 public void setValue(BigDecimal newValue) {
84 BigDecimal oldValue = value; 86 BigDecimal oldValue = value;
85 value = newValue; 87 value = newValue;
@@ -154,7 +156,7 @@ public class RealElementImpl extends PrimitiveElementImpl implements RealElement
154 public String toString() { 156 public String toString() {
155 if (eIsProxy()) return super.toString(); 157 if (eIsProxy()) return super.toString();
156 158
157 StringBuffer result = new StringBuffer(super.toString()); 159 StringBuilder result = new StringBuilder(super.toString());
158 result.append(" (value: "); 160 result.append(" (value: ");
159 result.append(value); 161 result.append(value);
160 result.append(')'); 162 result.append(')');
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/ScopeImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/ScopeImpl.java
index d8ade871..a1b6de35 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/ScopeImpl.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/ScopeImpl.java
@@ -26,6 +26,7 @@ import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
26 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.ScopeImpl#getMinNewElements <em>Min New Elements</em>}</li> 26 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.ScopeImpl#getMinNewElements <em>Min New Elements</em>}</li>
27 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.ScopeImpl#getMaxNewElements <em>Max New Elements</em>}</li> 27 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.ScopeImpl#getMaxNewElements <em>Max New Elements</em>}</li>
28 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.ScopeImpl#getTargetTypeInterpretation <em>Target Type Interpretation</em>}</li> 28 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.ScopeImpl#getTargetTypeInterpretation <em>Target Type Interpretation</em>}</li>
29 * <li>{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.ScopeImpl#getMinNewElementsHeuristic <em>Min New Elements Heuristic</em>}</li>
29 * </ul> 30 * </ul>
30 * 31 *
31 * @generated 32 * @generated
@@ -82,6 +83,26 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope {
82 protected PartialTypeInterpratation targetTypeInterpretation; 83 protected PartialTypeInterpratation targetTypeInterpretation;
83 84
84 /** 85 /**
86 * The default value of the '{@link #getMinNewElementsHeuristic() <em>Min New Elements Heuristic</em>}' attribute.
87 * <!-- begin-user-doc -->
88 * <!-- end-user-doc -->
89 * @see #getMinNewElementsHeuristic()
90 * @generated
91 * @ordered
92 */
93 protected static final int MIN_NEW_ELEMENTS_HEURISTIC_EDEFAULT = 0;
94
95 /**
96 * The cached value of the '{@link #getMinNewElementsHeuristic() <em>Min New Elements Heuristic</em>}' attribute.
97 * <!-- begin-user-doc -->
98 * <!-- end-user-doc -->
99 * @see #getMinNewElementsHeuristic()
100 * @generated
101 * @ordered
102 */
103 protected int minNewElementsHeuristic = MIN_NEW_ELEMENTS_HEURISTIC_EDEFAULT;
104
105 /**
85 * <!-- begin-user-doc --> 106 * <!-- begin-user-doc -->
86 * <!-- end-user-doc --> 107 * <!-- end-user-doc -->
87 * @generated 108 * @generated
@@ -105,6 +126,7 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope {
105 * <!-- end-user-doc --> 126 * <!-- end-user-doc -->
106 * @generated 127 * @generated
107 */ 128 */
129 @Override
108 public int getMinNewElements() { 130 public int getMinNewElements() {
109 return minNewElements; 131 return minNewElements;
110 } 132 }
@@ -114,6 +136,7 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope {
114 * <!-- end-user-doc --> 136 * <!-- end-user-doc -->
115 * @generated 137 * @generated
116 */ 138 */
139 @Override
117 public void setMinNewElements(int newMinNewElements) { 140 public void setMinNewElements(int newMinNewElements) {
118 int oldMinNewElements = minNewElements; 141 int oldMinNewElements = minNewElements;
119 minNewElements = newMinNewElements; 142 minNewElements = newMinNewElements;
@@ -126,6 +149,7 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope {
126 * <!-- end-user-doc --> 149 * <!-- end-user-doc -->
127 * @generated 150 * @generated
128 */ 151 */
152 @Override
129 public int getMaxNewElements() { 153 public int getMaxNewElements() {
130 return maxNewElements; 154 return maxNewElements;
131 } 155 }
@@ -135,6 +159,7 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope {
135 * <!-- end-user-doc --> 159 * <!-- end-user-doc -->
136 * @generated 160 * @generated
137 */ 161 */
162 @Override
138 public void setMaxNewElements(int newMaxNewElements) { 163 public void setMaxNewElements(int newMaxNewElements) {
139 int oldMaxNewElements = maxNewElements; 164 int oldMaxNewElements = maxNewElements;
140 maxNewElements = newMaxNewElements; 165 maxNewElements = newMaxNewElements;
@@ -147,6 +172,7 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope {
147 * <!-- end-user-doc --> 172 * <!-- end-user-doc -->
148 * @generated 173 * @generated
149 */ 174 */
175 @Override
150 public PartialTypeInterpratation getTargetTypeInterpretation() { 176 public PartialTypeInterpratation getTargetTypeInterpretation() {
151 if (targetTypeInterpretation != null && targetTypeInterpretation.eIsProxy()) { 177 if (targetTypeInterpretation != null && targetTypeInterpretation.eIsProxy()) {
152 InternalEObject oldTargetTypeInterpretation = (InternalEObject)targetTypeInterpretation; 178 InternalEObject oldTargetTypeInterpretation = (InternalEObject)targetTypeInterpretation;
@@ -188,6 +214,7 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope {
188 * <!-- end-user-doc --> 214 * <!-- end-user-doc -->
189 * @generated 215 * @generated
190 */ 216 */
217 @Override
191 public void setTargetTypeInterpretation(PartialTypeInterpratation newTargetTypeInterpretation) { 218 public void setTargetTypeInterpretation(PartialTypeInterpratation newTargetTypeInterpretation) {
192 if (newTargetTypeInterpretation != targetTypeInterpretation) { 219 if (newTargetTypeInterpretation != targetTypeInterpretation) {
193 NotificationChain msgs = null; 220 NotificationChain msgs = null;
@@ -208,6 +235,29 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope {
208 * @generated 235 * @generated
209 */ 236 */
210 @Override 237 @Override
238 public int getMinNewElementsHeuristic() {
239 return minNewElementsHeuristic;
240 }
241
242 /**
243 * <!-- begin-user-doc -->
244 * <!-- end-user-doc -->
245 * @generated
246 */
247 @Override
248 public void setMinNewElementsHeuristic(int newMinNewElementsHeuristic) {
249 int oldMinNewElementsHeuristic = minNewElementsHeuristic;
250 minNewElementsHeuristic = newMinNewElementsHeuristic;
251 if (eNotificationRequired())
252 eNotify(new ENotificationImpl(this, Notification.SET, PartialinterpretationPackage.SCOPE__MIN_NEW_ELEMENTS_HEURISTIC, oldMinNewElementsHeuristic, minNewElementsHeuristic));
253 }
254
255 /**
256 * <!-- begin-user-doc -->
257 * <!-- end-user-doc -->
258 * @generated
259 */
260 @Override
211 public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { 261 public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
212 switch (featureID) { 262 switch (featureID) {
213 case PartialinterpretationPackage.SCOPE__TARGET_TYPE_INTERPRETATION: 263 case PartialinterpretationPackage.SCOPE__TARGET_TYPE_INTERPRETATION:
@@ -247,6 +297,8 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope {
247 case PartialinterpretationPackage.SCOPE__TARGET_TYPE_INTERPRETATION: 297 case PartialinterpretationPackage.SCOPE__TARGET_TYPE_INTERPRETATION:
248 if (resolve) return getTargetTypeInterpretation(); 298 if (resolve) return getTargetTypeInterpretation();
249 return basicGetTargetTypeInterpretation(); 299 return basicGetTargetTypeInterpretation();
300 case PartialinterpretationPackage.SCOPE__MIN_NEW_ELEMENTS_HEURISTIC:
301 return getMinNewElementsHeuristic();
250 } 302 }
251 return super.eGet(featureID, resolve, coreType); 303 return super.eGet(featureID, resolve, coreType);
252 } 304 }
@@ -268,6 +320,9 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope {
268 case PartialinterpretationPackage.SCOPE__TARGET_TYPE_INTERPRETATION: 320 case PartialinterpretationPackage.SCOPE__TARGET_TYPE_INTERPRETATION:
269 setTargetTypeInterpretation((PartialTypeInterpratation)newValue); 321 setTargetTypeInterpretation((PartialTypeInterpratation)newValue);
270 return; 322 return;
323 case PartialinterpretationPackage.SCOPE__MIN_NEW_ELEMENTS_HEURISTIC:
324 setMinNewElementsHeuristic((Integer)newValue);
325 return;
271 } 326 }
272 super.eSet(featureID, newValue); 327 super.eSet(featureID, newValue);
273 } 328 }
@@ -289,6 +344,9 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope {
289 case PartialinterpretationPackage.SCOPE__TARGET_TYPE_INTERPRETATION: 344 case PartialinterpretationPackage.SCOPE__TARGET_TYPE_INTERPRETATION:
290 setTargetTypeInterpretation((PartialTypeInterpratation)null); 345 setTargetTypeInterpretation((PartialTypeInterpratation)null);
291 return; 346 return;
347 case PartialinterpretationPackage.SCOPE__MIN_NEW_ELEMENTS_HEURISTIC:
348 setMinNewElementsHeuristic(MIN_NEW_ELEMENTS_HEURISTIC_EDEFAULT);
349 return;
292 } 350 }
293 super.eUnset(featureID); 351 super.eUnset(featureID);
294 } 352 }
@@ -307,6 +365,8 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope {
307 return maxNewElements != MAX_NEW_ELEMENTS_EDEFAULT; 365 return maxNewElements != MAX_NEW_ELEMENTS_EDEFAULT;
308 case PartialinterpretationPackage.SCOPE__TARGET_TYPE_INTERPRETATION: 366 case PartialinterpretationPackage.SCOPE__TARGET_TYPE_INTERPRETATION:
309 return targetTypeInterpretation != null; 367 return targetTypeInterpretation != null;
368 case PartialinterpretationPackage.SCOPE__MIN_NEW_ELEMENTS_HEURISTIC:
369 return minNewElementsHeuristic != MIN_NEW_ELEMENTS_HEURISTIC_EDEFAULT;
310 } 370 }
311 return super.eIsSet(featureID); 371 return super.eIsSet(featureID);
312 } 372 }
@@ -320,11 +380,13 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope {
320 public String toString() { 380 public String toString() {
321 if (eIsProxy()) return super.toString(); 381 if (eIsProxy()) return super.toString();
322 382
323 StringBuffer result = new StringBuffer(super.toString()); 383 StringBuilder result = new StringBuilder(super.toString());
324 result.append(" (minNewElements: "); 384 result.append(" (minNewElements: ");
325 result.append(minNewElements); 385 result.append(minNewElements);
326 result.append(", maxNewElements: "); 386 result.append(", maxNewElements: ");
327 result.append(maxNewElements); 387 result.append(maxNewElements);
388 result.append(", minNewElementsHeuristic: ");
389 result.append(minNewElementsHeuristic);
328 result.append(')'); 390 result.append(')');
329 return result.toString(); 391 return result.toString();
330 } 392 }
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/StringElementImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/StringElementImpl.java
index f207401d..0242c9b2 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/StringElementImpl.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/StringElementImpl.java
@@ -69,6 +69,7 @@ public class StringElementImpl extends PrimitiveElementImpl implements StringEle
69 * <!-- end-user-doc --> 69 * <!-- end-user-doc -->
70 * @generated 70 * @generated
71 */ 71 */
72 @Override
72 public String getValue() { 73 public String getValue() {
73 return value; 74 return value;
74 } 75 }
@@ -78,6 +79,7 @@ public class StringElementImpl extends PrimitiveElementImpl implements StringEle
78 * <!-- end-user-doc --> 79 * <!-- end-user-doc -->
79 * @generated 80 * @generated
80 */ 81 */
82 @Override
81 public void setValue(String newValue) { 83 public void setValue(String newValue) {
82 String oldValue = value; 84 String oldValue = value;
83 value = newValue; 85 value = newValue;
@@ -152,7 +154,7 @@ public class StringElementImpl extends PrimitiveElementImpl implements StringEle
152 public String toString() { 154 public String toString() {
153 if (eIsProxy()) return super.toString(); 155 if (eIsProxy()) return super.toString();
154 156
155 StringBuffer result = new StringBuffer(super.toString()); 157 StringBuilder result = new StringBuilder(super.toString());
156 result.append(" (value: "); 158 result.append(" (value: ");
157 result.append(value); 159 result.append(value);
158 result.append(')'); 160 result.append(')');
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/UnaryElementRelationLinkImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/UnaryElementRelationLinkImpl.java
index 2cb56323..e76a89b7 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/UnaryElementRelationLinkImpl.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/UnaryElementRelationLinkImpl.java
@@ -62,6 +62,7 @@ public class UnaryElementRelationLinkImpl extends RelationLinkImpl implements Un
62 * <!-- end-user-doc --> 62 * <!-- end-user-doc -->
63 * @generated 63 * @generated
64 */ 64 */
65 @Override
65 public DefinedElement getParam1() { 66 public DefinedElement getParam1() {
66 if (param1 != null && param1.eIsProxy()) { 67 if (param1 != null && param1.eIsProxy()) {
67 InternalEObject oldParam1 = (InternalEObject)param1; 68 InternalEObject oldParam1 = (InternalEObject)param1;
@@ -88,6 +89,7 @@ public class UnaryElementRelationLinkImpl extends RelationLinkImpl implements Un
88 * <!-- end-user-doc --> 89 * <!-- end-user-doc -->
89 * @generated 90 * @generated
90 */ 91 */
92 @Override
91 public void setParam1(DefinedElement newParam1) { 93 public void setParam1(DefinedElement newParam1) {
92 DefinedElement oldParam1 = param1; 94 DefinedElement oldParam1 = param1;
93 param1 = newParam1; 95 param1 = newParam1;
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/model/PartialInterpretation.ecore b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/model/PartialInterpretation.ecore
index acf82a3f..47d54258 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/model/PartialInterpretation.ecore
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/model/PartialInterpretation.ecore
@@ -27,6 +27,9 @@
27 eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EInt" defaultValueLiteral="0"/> 27 eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EInt" defaultValueLiteral="0"/>
28 <eStructuralFeatures xsi:type="ecore:EAttribute" name="maxNewElements" lowerBound="1" 28 <eStructuralFeatures xsi:type="ecore:EAttribute" name="maxNewElements" lowerBound="1"
29 eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EInt" defaultValueLiteral="-1"/> 29 eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EInt" defaultValueLiteral="-1"/>
30 <eStructuralFeatures xsi:type="ecore:EAttribute" name="minNewElementsHeuristic"
31 lowerBound="1" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EInt"
32 defaultValueLiteral="0"/>
30 </eClassifiers> 33 </eClassifiers>
31 <eClassifiers xsi:type="ecore:EClass" name="PartialConstantInterpretation"> 34 <eClassifiers xsi:type="ecore:EClass" name="PartialConstantInterpretation">
32 <eStructuralFeatures xsi:type="ecore:EReference" name="interpretationOf" lowerBound="1" 35 <eStructuralFeatures xsi:type="ecore:EReference" name="interpretationOf" lowerBound="1"
@@ -92,6 +95,9 @@
92 eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EInt" defaultValueLiteral="-1"/> 95 eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EInt" defaultValueLiteral="-1"/>
93 <eStructuralFeatures xsi:type="ecore:EReference" name="targetTypeInterpretation" 96 <eStructuralFeatures xsi:type="ecore:EReference" name="targetTypeInterpretation"
94 lowerBound="1" eType="#//PartialTypeInterpratation" eOpposite="#//PartialTypeInterpratation/scopes"/> 97 lowerBound="1" eType="#//PartialTypeInterpratation" eOpposite="#//PartialTypeInterpratation/scopes"/>
98 <eStructuralFeatures xsi:type="ecore:EAttribute" name="minNewElementsHeuristic"
99 lowerBound="1" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EInt"
100 defaultValueLiteral="0"/>
95 </eClassifiers> 101 </eClassifiers>
96 <eClassifiers xsi:type="ecore:EClass" name="PartialPrimitiveInterpretation" abstract="true" 102 <eClassifiers xsi:type="ecore:EClass" name="PartialPrimitiveInterpretation" abstract="true"
97 eSuperTypes="#//PartialTypeInterpratation"/> 103 eSuperTypes="#//PartialTypeInterpratation"/>
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/model/PartialInterpretation.genmodel b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/model/PartialInterpretation.genmodel
index 2ac0a4f3..daeaf594 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/model/PartialInterpretation.genmodel
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/model/PartialInterpretation.genmodel
@@ -18,7 +18,10 @@
18 <genFeatures property="None" children="true" createChild="true" ecoreFeature="ecore:EReference PartialInterpretation.ecore#//PartialInterpretation/partialtypeinterpratation"/> 18 <genFeatures property="None" children="true" createChild="true" ecoreFeature="ecore:EReference PartialInterpretation.ecore#//PartialInterpretation/partialtypeinterpratation"/>
19 <genFeatures property="None" children="true" createChild="true" ecoreFeature="ecore:EReference PartialInterpretation.ecore#//PartialInterpretation/openWorldElements"/> 19 <genFeatures property="None" children="true" createChild="true" ecoreFeature="ecore:EReference PartialInterpretation.ecore#//PartialInterpretation/openWorldElements"/>
20 <genFeatures property="None" children="true" createChild="true" ecoreFeature="ecore:EReference PartialInterpretation.ecore#//PartialInterpretation/problemConainer"/> 20 <genFeatures property="None" children="true" createChild="true" ecoreFeature="ecore:EReference PartialInterpretation.ecore#//PartialInterpretation/problemConainer"/>
21 <genFeatures property="None" children="true" createChild="true" ecoreFeature="ecore:EReference PartialInterpretation.ecore#//PartialInterpretation/scope"/> 21 <genFeatures property="None" children="true" createChild="true" ecoreFeature="ecore:EReference PartialInterpretation.ecore#//PartialInterpretation/scopes"/>
22 <genFeatures createChild="false" ecoreFeature="ecore:EAttribute PartialInterpretation.ecore#//PartialInterpretation/minNewElements"/>
23 <genFeatures createChild="false" ecoreFeature="ecore:EAttribute PartialInterpretation.ecore#//PartialInterpretation/maxNewElements"/>
24 <genFeatures createChild="false" ecoreFeature="ecore:EAttribute PartialInterpretation.ecore#//PartialInterpretation/minNewElementsHeuristic"/>
22 </genClasses> 25 </genClasses>
23 <genClasses ecoreClass="PartialInterpretation.ecore#//PartialConstantInterpretation"> 26 <genClasses ecoreClass="PartialInterpretation.ecore#//PartialConstantInterpretation">
24 <genFeatures notify="false" createChild="false" propertySortChoices="true" ecoreFeature="ecore:EReference PartialInterpretation.ecore#//PartialConstantInterpretation/interpretationOf"/> 27 <genFeatures notify="false" createChild="false" propertySortChoices="true" ecoreFeature="ecore:EReference PartialInterpretation.ecore#//PartialConstantInterpretation/interpretationOf"/>
@@ -33,9 +36,8 @@
33 <genFeatures notify="false" createChild="false" propertySortChoices="true" ecoreFeature="ecore:EReference PartialInterpretation.ecore#//PartialFunctionInterpretation/interpretationOf"/> 36 <genFeatures notify="false" createChild="false" propertySortChoices="true" ecoreFeature="ecore:EReference PartialInterpretation.ecore#//PartialFunctionInterpretation/interpretationOf"/>
34 </genClasses> 37 </genClasses>
35 <genClasses ecoreClass="PartialInterpretation.ecore#//PartialTypeInterpratation"> 38 <genClasses ecoreClass="PartialInterpretation.ecore#//PartialTypeInterpratation">
36 <genFeatures notify="false" createChild="false" propertySortChoices="true" ecoreFeature="ecore:EReference PartialInterpretation.ecore#//PartialTypeInterpratation/interpretationOf"/>
37 <genFeatures notify="false" createChild="false" propertySortChoices="true" ecoreFeature="ecore:EReference PartialInterpretation.ecore#//PartialTypeInterpratation/elements"/> 39 <genFeatures notify="false" createChild="false" propertySortChoices="true" ecoreFeature="ecore:EReference PartialInterpretation.ecore#//PartialTypeInterpratation/elements"/>
38 <genFeatures notify="false" createChild="false" propertySortChoices="true" ecoreFeature="ecore:EReference PartialInterpretation.ecore#//PartialTypeInterpratation/supertypeInterpretation"/> 40 <genFeatures notify="false" createChild="false" propertySortChoices="true" ecoreFeature="ecore:EReference PartialInterpretation.ecore#//PartialTypeInterpratation/scopes"/>
39 </genClasses> 41 </genClasses>
40 <genClasses image="false" ecoreClass="PartialInterpretation.ecore#//RelationLink"/> 42 <genClasses image="false" ecoreClass="PartialInterpretation.ecore#//RelationLink"/>
41 <genClasses ecoreClass="PartialInterpretation.ecore#//UnaryElementRelationLink"> 43 <genClasses ecoreClass="PartialInterpretation.ecore#//UnaryElementRelationLink">
@@ -50,6 +52,7 @@
50 </genClasses> 52 </genClasses>
51 <genClasses ecoreClass="PartialInterpretation.ecore#//NaryRelationLinkElement"> 53 <genClasses ecoreClass="PartialInterpretation.ecore#//NaryRelationLinkElement">
52 <genFeatures createChild="false" ecoreFeature="ecore:EAttribute PartialInterpretation.ecore#//NaryRelationLinkElement/index"/> 54 <genFeatures createChild="false" ecoreFeature="ecore:EAttribute PartialInterpretation.ecore#//NaryRelationLinkElement/index"/>
55 <genFeatures notify="false" createChild="false" propertySortChoices="true" ecoreFeature="ecore:EReference PartialInterpretation.ecore#//NaryRelationLinkElement/param"/>
53 </genClasses> 56 </genClasses>
54 <genClasses image="false" ecoreClass="PartialInterpretation.ecore#//PrimitiveElement"> 57 <genClasses image="false" ecoreClass="PartialInterpretation.ecore#//PrimitiveElement">
55 <genFeatures createChild="false" ecoreFeature="ecore:EAttribute PartialInterpretation.ecore#//PrimitiveElement/valueSet"/> 58 <genFeatures createChild="false" ecoreFeature="ecore:EAttribute PartialInterpretation.ecore#//PrimitiveElement/valueSet"/>
@@ -70,11 +73,16 @@
70 <genFeatures createChild="false" ecoreFeature="ecore:EAttribute PartialInterpretation.ecore#//Scope/minNewElements"/> 73 <genFeatures createChild="false" ecoreFeature="ecore:EAttribute PartialInterpretation.ecore#//Scope/minNewElements"/>
71 <genFeatures createChild="false" ecoreFeature="ecore:EAttribute PartialInterpretation.ecore#//Scope/maxNewElements"/> 74 <genFeatures createChild="false" ecoreFeature="ecore:EAttribute PartialInterpretation.ecore#//Scope/maxNewElements"/>
72 <genFeatures notify="false" createChild="false" propertySortChoices="true" ecoreFeature="ecore:EReference PartialInterpretation.ecore#//Scope/targetTypeInterpretation"/> 75 <genFeatures notify="false" createChild="false" propertySortChoices="true" ecoreFeature="ecore:EReference PartialInterpretation.ecore#//Scope/targetTypeInterpretation"/>
76 <genFeatures createChild="false" ecoreFeature="ecore:EAttribute PartialInterpretation.ecore#//Scope/minNewElementsHeuristic"/>
73 </genClasses> 77 </genClasses>
74 <genClasses image="false" ecoreClass="PartialInterpretation.ecore#//PartialPrimitiveInterpretation"/> 78 <genClasses image="false" ecoreClass="PartialInterpretation.ecore#//PartialPrimitiveInterpretation"/>
75 <genClasses ecoreClass="PartialInterpretation.ecore#//PartialBooleanInterpretation"/> 79 <genClasses ecoreClass="PartialInterpretation.ecore#//PartialBooleanInterpretation"/>
76 <genClasses ecoreClass="PartialInterpretation.ecore#//PartialIntegerInterpretation"/> 80 <genClasses ecoreClass="PartialInterpretation.ecore#//PartialIntegerInterpretation"/>
77 <genClasses ecoreClass="PartialInterpretation.ecore#//PartialRealInterpretation"/> 81 <genClasses ecoreClass="PartialInterpretation.ecore#//PartialRealInterpretation"/>
78 <genClasses ecoreClass="PartialInterpretation.ecore#//PartialStringInterpretation"/> 82 <genClasses ecoreClass="PartialInterpretation.ecore#//PartialStringInterpretation"/>
83 <genClasses ecoreClass="PartialInterpretation.ecore#//PartialComplexTypeInterpretation">
84 <genFeatures notify="false" createChild="false" propertySortChoices="true" ecoreFeature="ecore:EReference PartialInterpretation.ecore#//PartialComplexTypeInterpretation/supertypeInterpretation"/>
85 <genFeatures notify="false" createChild="false" propertySortChoices="true" ecoreFeature="ecore:EReference PartialInterpretation.ecore#//PartialComplexTypeInterpretation/interpretationOf"/>
86 </genClasses>
79 </genPackages> 87 </genPackages>
80</genmodel:GenModel> 88</genmodel:GenModel>
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretation2logic/InstanceModel2PartialInterpretation.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretation2logic/InstanceModel2PartialInterpretation.xtend
index 8aaaacb5..cb5b587f 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretation2logic/InstanceModel2PartialInterpretation.xtend
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretation2logic/InstanceModel2PartialInterpretation.xtend
@@ -1,5 +1,6 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic 1package hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic
2 2
3import com.google.common.collect.ImmutableList
3import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic 4import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic
4import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace 5import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace
5import hu.bme.mit.inf.dslreasoner.logic.model.builder.TracedOutput 6import hu.bme.mit.inf.dslreasoner.logic.model.builder.TracedOutput
@@ -12,18 +13,18 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.Par
12import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.Problem2PartialInterpretationTrace 13import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.Problem2PartialInterpretationTrace
13import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialRelationInterpretation 14import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialRelationInterpretation
14import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationFactory 15import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationFactory
16import java.math.BigDecimal
15import java.util.HashMap 17import java.util.HashMap
18import java.util.HashSet
16import java.util.List 19import java.util.List
17import java.util.Map 20import java.util.Map
21import java.util.Set
18import org.eclipse.emf.common.util.Enumerator 22import org.eclipse.emf.common.util.Enumerator
23import org.eclipse.emf.ecore.EAttribute
19import org.eclipse.emf.ecore.EObject 24import org.eclipse.emf.ecore.EObject
20import org.eclipse.emf.ecore.resource.Resource 25import org.eclipse.emf.ecore.resource.Resource
21 26
22import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.* 27import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.*
23import java.util.HashSet
24import java.util.Set
25import java.math.BigDecimal
26import org.eclipse.emf.ecore.EAttribute
27 28
28class InstanceModel2PartialInterpretation { 29class InstanceModel2PartialInterpretation {
29 val extension LogiclanguageFactory factory = LogiclanguageFactory.eINSTANCE 30 val extension LogiclanguageFactory factory = LogiclanguageFactory.eINSTANCE
@@ -36,7 +37,19 @@ class InstanceModel2PartialInterpretation {
36 Resource resource, 37 Resource resource,
37 boolean withID) 38 boolean withID)
38 { 39 {
39 val objects = resource.allContents.toList 40 val objectsBuilder = ImmutableList.builder
41 val treeIterator = resource.allContents
42 val referencesUsed = ecore2Logic.allReferencesInScope(metamodelTranslationResult.trace).toSet
43 while (treeIterator.hasNext) {
44 val object = treeIterator.next
45 val containingReference = object.eContainmentFeature
46 if (containingReference === null || referencesUsed.contains(containingReference)) {
47 objectsBuilder.add(object)
48 } else {
49 treeIterator.prune
50 }
51 }
52 val objects = objectsBuilder.build
40 return transform(metamodelTranslationResult,objects,withID) 53 return transform(metamodelTranslationResult,objects,withID)
41 } 54 }
42 55
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/META-INF/MANIFEST.MF b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/META-INF/MANIFEST.MF
index 2a271acf..4ad61ccb 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/META-INF/MANIFEST.MF
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/META-INF/MANIFEST.MF
@@ -3,7 +3,8 @@ Bundle-ManifestVersion: 2
3Bundle-Name: Reasoner 3Bundle-Name: Reasoner
4Bundle-SymbolicName: hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner 4Bundle-SymbolicName: hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner
5Bundle-Version: 1.0.0.qualifier 5Bundle-Version: 1.0.0.qualifier
6Export-Package: hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner 6Export-Package: hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner,
7 hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization
7Require-Bundle: hu.bme.mit.inf.dslreasoner.ecore2logic;bundle-version="1.0.0", 8Require-Bundle: hu.bme.mit.inf.dslreasoner.ecore2logic;bundle-version="1.0.0",
8 hu.bme.mit.inf.dslreasoner.logic.model;bundle-version="1.0.0", 9 hu.bme.mit.inf.dslreasoner.logic.model;bundle-version="1.0.0",
9 hu.bme.mit.inf.dslreasoner.viatra2logic;bundle-version="1.0.0", 10 hu.bme.mit.inf.dslreasoner.viatra2logic;bundle-version="1.0.0",
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 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner 1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner
2 2
3import org.eclipse.viatra.dse.objectives.IGlobalConstraint 3import org.eclipse.viatra.dse.objectives.IGlobalConstraint
4import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod 4import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod
5 5
6abstract class ModelGenerationMethodBasedGlobalConstraint implements IGlobalConstraint { 6abstract 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 0411ccdd..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
@@ -1,5 +1,7 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner 1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner
2 2
3import com.google.common.collect.ImmutableList
4import com.google.common.collect.Lists
3import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel 5import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel
4import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasoner 6import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasoner
5import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasonerException 7import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasonerException
@@ -10,19 +12,28 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicproblemPackage
10import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicresultFactory 12import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicresultFactory
11import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult 13import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult
12import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethodProvider 14import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethodProvider
13import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ScopePropagator 15import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy
14import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.PartialInterpretationInitialiser 16import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.PartialInterpretationInitialiser
15import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation 17import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
16import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationPackage 18import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationPackage
19import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.AbstractNeighbourhoodBasedStateCoderFactory
17import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.IdentifierBasedStateCoderFactory 20import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.IdentifierBasedStateCoderFactory
18import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.NeighbourhoodBasedStateCoderFactory 21import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.NeighbourhoodBasedHashStateCoderFactory
22import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.PairwiseNeighbourhoodBasedStateCoderFactory
23import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.BasicScopeGlobalConstraint
19import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.BestFirstStrategyForModelGeneration 24import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.BestFirstStrategyForModelGeneration
25import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.DiversityChecker
26import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.InconsistentScopeGlobalConstraint
27import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.LoggerSolutionFoundHandler
20import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.ModelGenerationCompositeObjective 28import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.ModelGenerationCompositeObjective
21import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.PartialModelAsLogicInterpretation 29import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.PartialModelAsLogicInterpretation
22import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.ScopeObjective 30import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.ScopeObjective
31import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.SurelyViolatedObjectiveGlobalConstraint
23import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.UnfinishedMultiplicityObjective 32import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.UnfinishedMultiplicityObjective
24import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.UnfinishedWFObjective 33import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.ViatraReasonerSolutionSaver
25import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.WF2ObjectiveConverter 34import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.WF2ObjectiveConverter
35import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ThreeValuedCostElement
36import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ThreeValuedCostObjective
26import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace 37import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace
27import java.util.List 38import java.util.List
28import java.util.Map 39import java.util.Map
@@ -31,114 +42,159 @@ import org.eclipse.viatra.dse.api.DesignSpaceExplorer
31import org.eclipse.viatra.dse.api.DesignSpaceExplorer.DseLoggingLevel 42import org.eclipse.viatra.dse.api.DesignSpaceExplorer.DseLoggingLevel
32import org.eclipse.viatra.dse.solutionstore.SolutionStore 43import org.eclipse.viatra.dse.solutionstore.SolutionStore
33import org.eclipse.viatra.dse.statecode.IStateCoderFactory 44import org.eclipse.viatra.dse.statecode.IStateCoderFactory
45import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.NumericSolver
34 46
35class ViatraReasoner extends LogicReasoner{ 47class ViatraReasoner extends LogicReasoner {
36 val PartialInterpretationInitialiser initialiser = new PartialInterpretationInitialiser() 48 val PartialInterpretationInitialiser initialiser = new PartialInterpretationInitialiser()
37 val ModelGenerationMethodProvider modelGenerationMethodProvider = new ModelGenerationMethodProvider 49 val ModelGenerationMethodProvider modelGenerationMethodProvider = new ModelGenerationMethodProvider
38 val extension LogicresultFactory factory = LogicresultFactory.eINSTANCE 50 val extension LogicresultFactory factory = LogicresultFactory.eINSTANCE
39 val WF2ObjectiveConverter wf2ObjectiveConverter = new WF2ObjectiveConverter 51 val WF2ObjectiveConverter wf2ObjectiveConverter = new WF2ObjectiveConverter
40 52
41 53 override solve(LogicProblem problem, LogicSolverConfiguration configuration,
42 override solve(LogicProblem problem, LogicSolverConfiguration configuration, ReasonerWorkspace workspace) throws LogicReasonerException { 54 ReasonerWorkspace workspace) throws LogicReasonerException {
43 val viatraConfig = configuration.asConfig 55 val viatraConfig = configuration.asConfig
44 56
45 if(viatraConfig.debugCongiguration.logging) { 57 if (viatraConfig.documentationLevel == DocumentationLevel.FULL) {
46 DesignSpaceExplorer.turnOnLogging(DseLoggingLevel.VERBOSE_FULL) 58 DesignSpaceExplorer.turnOnLogging(DseLoggingLevel.VERBOSE_FULL)
47 } else { 59 } else {
48 DesignSpaceExplorer.turnOnLogging(DseLoggingLevel.WARN) 60 DesignSpaceExplorer.turnOnLogging(DseLoggingLevel.WARN)
49 } 61 }
50 62
51 val DesignSpaceExplorer dse = new DesignSpaceExplorer(); 63 val DesignSpaceExplorer dse = new DesignSpaceExplorer();
52 64
53 dse.addMetaModelPackage(LogiclanguagePackage.eINSTANCE) 65 dse.addMetaModelPackage(LogiclanguagePackage.eINSTANCE)
54 dse.addMetaModelPackage(LogicproblemPackage.eINSTANCE) 66 dse.addMetaModelPackage(LogicproblemPackage.eINSTANCE)
55 dse.addMetaModelPackage(PartialinterpretationPackage.eINSTANCE) 67 dse.addMetaModelPackage(PartialinterpretationPackage.eINSTANCE)
56 68
57 val transformationStartTime = System.nanoTime 69 val transformationStartTime = System.nanoTime
58 70 val emptySolution = initialiser.initialisePartialInterpretation(problem, viatraConfig.typeScopes).output
59 71 if ((viatraConfig.documentationLevel == DocumentationLevel::FULL ||
60 val emptySolution = initialiser.initialisePartialInterpretation(problem,viatraConfig.typeScopes).output 72 viatraConfig.documentationLevel == DocumentationLevel::NORMAL) && workspace !== null) {
61 if((viatraConfig.documentationLevel == DocumentationLevel::FULL || viatraConfig.documentationLevel == DocumentationLevel::NORMAL) && workspace !== null) { 73 workspace.writeModel(emptySolution, "init.partialmodel")
62 workspace.writeModel(emptySolution,"init.partialmodel") 74 }
63 } 75
64 emptySolution.problemConainer = problem 76 emptySolution.problemConainer = problem
65 77 var BasicScopeGlobalConstraint basicScopeGlobalConstraint = null
66 val ScopePropagator scopePropagator = new ScopePropagator(emptySolution) 78 if (viatraConfig.scopePropagatorStrategy == ScopePropagatorStrategy.None) {
67 scopePropagator.propagateAllScopeConstraints 79 basicScopeGlobalConstraint = new BasicScopeGlobalConstraint(emptySolution)
68 80 emptySolution.scopes.clear
81 }
82
69 val method = modelGenerationMethodProvider.createModelGenerationMethod( 83 val method = modelGenerationMethodProvider.createModelGenerationMethod(
70 problem, 84 problem,
71 emptySolution, 85 emptySolution,
72 workspace, 86 workspace,
73 viatraConfig.nameNewElements, 87 viatraConfig.nameNewElements,
74 viatraConfig.typeInferenceMethod, 88 viatraConfig.typeInferenceMethod,
75 scopePropagator, 89 viatraConfig.scopePropagatorStrategy,
76 viatraConfig.documentationLevel, 90 viatraConfig.hints,
77 viatraConfig.calculateObjectCreationCosts 91 viatraConfig.documentationLevel
78 ) 92 )
79 //println("parsed") 93
80
81 dse.addObjective(new ModelGenerationCompositeObjective( 94 dse.addObjective(new ModelGenerationCompositeObjective(
82 new ScopeObjective, 95 basicScopeGlobalConstraint ?: new ScopeObjective,
83 method.unfinishedMultiplicities.map[new UnfinishedMultiplicityObjective(it)], 96 method.unfinishedMultiplicities.map[new UnfinishedMultiplicityObjective(it)],
84 new UnfinishedWFObjective(method.unfinishedWF), 97 wf2ObjectiveConverter.createCompletenessObjective(method.unfinishedWF),
85 viatraConfig 98 viatraConfig
86 )) 99 ))
87 100
88 dse.addGlobalConstraint(wf2ObjectiveConverter.createInvalidationObjective(method.invalidWF)) 101 val extremalObjectives = Lists.newArrayListWithExpectedSize(viatraConfig.costObjectives.size)
89 for(additionalConstraint : viatraConfig.searchSpaceConstraints.additionalGlobalConstraints) { 102 for (entry : viatraConfig.costObjectives.indexed) {
103 val objectiveName = '''costObjective«entry.key»'''
104 val objectiveConfig = entry.value
105 val elementsBuilder = ImmutableList.builder
106 for (elementConfig : objectiveConfig.elements) {
107 val relationName = elementConfig.patternQualifiedName
108 val modalQueries = method.modalRelationQueries.get(relationName)
109 if (modalQueries === null) {
110 throw new IllegalArgumentException("Unknown relation: " + relationName)
111 }
112 elementsBuilder.add(new ThreeValuedCostElement(
113 modalQueries.currentQuery,
114 modalQueries.mayQuery,
115 modalQueries.mustQuery,
116 elementConfig.weight
117 ))
118 }
119 val costElements = elementsBuilder.build
120 val costObjective = new ThreeValuedCostObjective(objectiveName, costElements, objectiveConfig.kind,
121 objectiveConfig.threshold, 3)
122 dse.addObjective(costObjective)
123 if (objectiveConfig.findExtremum) {
124 extremalObjectives += costObjective
125 }
126 }
127
128 val numberOfRequiredSolutions = configuration.solutionScope.numberOfRequiredSolutions
129 val solutionStore = if (extremalObjectives.empty) {
130 new SolutionStore(numberOfRequiredSolutions)
131 } else {
132 new SolutionStore()
133 }
134 solutionStore.registerSolutionFoundHandler(new LoggerSolutionFoundHandler(viatraConfig))
135 val diversityChecker = DiversityChecker.of(viatraConfig.diversityRequirement)
136 val numericSolver = new NumericSolver(method, viatraConfig.runIntermediateNumericalConsistencyChecks, false)
137 val solutionSaver = new ViatraReasonerSolutionSaver(newArrayList(extremalObjectives), numberOfRequiredSolutions,
138 diversityChecker, numericSolver)
139 val solutionCopier = solutionSaver.solutionCopier
140 solutionStore.withSolutionSaver(solutionSaver)
141 dse.solutionStore = solutionStore
142
143 dse.addGlobalConstraint(wf2ObjectiveConverter.createInvalidationGlobalConstraint(method.invalidWF))
144 dse.addGlobalConstraint(new SurelyViolatedObjectiveGlobalConstraint(solutionSaver))
145 dse.addGlobalConstraint(new InconsistentScopeGlobalConstraint)
146 if (basicScopeGlobalConstraint !== null) {
147 dse.addGlobalConstraint(basicScopeGlobalConstraint)
148 }
149 for (additionalConstraint : viatraConfig.searchSpaceConstraints.additionalGlobalConstraints) {
90 dse.addGlobalConstraint(additionalConstraint.apply(method)) 150 dse.addGlobalConstraint(additionalConstraint.apply(method))
91 } 151 }
92 152
93 dse.setInitialModel(emptySolution,false) 153 dse.setInitialModel(emptySolution, false)
94 154
95 val IStateCoderFactory statecoder = if(viatraConfig.stateCoderStrategy == StateCoderStrategy.Neighbourhood) { 155 val IStateCoderFactory statecoder = switch (viatraConfig.stateCoderStrategy) {
96 new NeighbourhoodBasedStateCoderFactory 156 case Neighbourhood:
97 } else { 157 new NeighbourhoodBasedHashStateCoderFactory
98 new IdentifierBasedStateCoderFactory 158 case PairwiseNeighbourhood:
159 new PairwiseNeighbourhoodBasedStateCoderFactory
160 default:
161 new IdentifierBasedStateCoderFactory
99 } 162 }
100 dse.stateCoderFactory = statecoder 163 dse.stateCoderFactory = statecoder
101 164
102 dse.maxNumberOfThreads = 1 165 dse.maxNumberOfThreads = 1
103 166
104 val solutionStore = new SolutionStore(configuration.solutionScope.numberOfRequiredSolution) 167 for (rule : method.relationRefinementRules) {
105 dse.solutionStore = solutionStore
106
107 for(rule : method.relationRefinementRules) {
108 dse.addTransformationRule(rule) 168 dse.addTransformationRule(rule)
109 } 169 }
110 for(rule : method.objectRefinementRules) { 170 for (rule : method.objectRefinementRules) {
111 dse.addTransformationRule(rule) 171 dse.addTransformationRule(rule)
112 } 172 }
113 173
114 val strategy = new BestFirstStrategyForModelGeneration(workspace,viatraConfig,method) 174 val strategy = new BestFirstStrategyForModelGeneration(workspace, viatraConfig, method, solutionSaver, numericSolver)
115 viatraConfig.progressMonitor.workedForwardTransformation 175 viatraConfig.progressMonitor.workedForwardTransformation
116 val transformationFinished = System.nanoTime 176 val transformationFinished = System.nanoTime
117 val transformationTime = transformationFinished - transformationStartTime 177 val transformationTime = transformationFinished - transformationStartTime
118
119 val solverStartTime = System.nanoTime 178 val solverStartTime = System.nanoTime
120 179
121 var boolean stoppedByTimeout 180 var boolean stoppedByTimeout
122 var boolean stoppedByException 181 try {
123 try{ 182 stoppedByTimeout = dse.startExplorationWithTimeout(strategy, configuration.runtimeLimit * 1000);
124 stoppedByTimeout = dse.startExplorationWithTimeout(strategy,configuration.runtimeLimit*1000);
125 stoppedByException = false
126 } catch (NullPointerException npe) { 183 } catch (NullPointerException npe) {
127 stoppedByTimeout = false 184 stoppedByTimeout = false
128 stoppedByException = true
129 } 185 }
130 val solverTime = System.nanoTime - solverStartTime 186 val solverTime = System.nanoTime - solverStartTime
131 viatraConfig.progressMonitor.workedSearchFinished 187 viatraConfig.progressMonitor.workedSearchFinished
132 188
133 //additionalMatches = strategy.solutionStoreWithCopy.additionalMatches 189 // additionalMatches = strategy.solutionStoreWithCopy.additionalMatches
134 val statistics = createStatistics => [ 190 val statistics = createStatistics => [
135 //it.solverTime = viatraConfig.runtimeLimit 191 // it.solverTime = viatraConfig.runtimeLimit
136 it.solverTime = (solverTime/1000000) as int 192 it.solverTime = (solverTime / 1000000) as int
137 it.transformationTime = (transformationTime/1000000) as int 193 it.transformationTime = (transformationTime / 1000000) as int
138 for(x : 0..<strategy.solutionStoreWithCopy.allRuntimes.size) { 194 for (pair : solutionCopier.getAllCopierRuntimes(true).indexed) {
139 it.entries += createIntStatisticEntry => [ 195 it.entries += createIntStatisticEntry => [
140 it.name = '''Solution«x+1»FoundAt''' 196 it.name = '''_Solution«pair.key»FoundAt'''
141 it.value = (strategy.solutionStoreWithCopy.allRuntimes.get(x)/1000000) as int 197 it.value = (pair.value / 1000000) as int
142 ] 198 ]
143 } 199 }
144 for(x: 0..<strategy.times.size) { 200 for(x: 0..<strategy.times.size) {
@@ -151,16 +207,32 @@ class ViatraReasoner extends LogicReasoner{
151 it.name = "ExplorationInitializationTime" it.value = ((strategy.explorationStarted-transformationFinished)/1000000) as int 207 it.name = "ExplorationInitializationTime" it.value = ((strategy.explorationStarted-transformationFinished)/1000000) as int
152 ] 208 ]
153 it.entries += createIntStatisticEntry => [ 209 it.entries += createIntStatisticEntry => [
154 it.name = "TransformationExecutionTime" it.value = (method.statistics.transformationExecutionTime/1000000) as int 210 it.name = "TransformationExecutionTime"
211 it.value = (method.statistics.transformationExecutionTime / 1000000) as int
212 ]
213 it.entries += createIntStatisticEntry => [
214 it.name = "ScopePropagationTime"
215 it.value = (method.statistics.scopePropagationTime / 1000000) as int
155 ] 216 ]
156 it.entries += createIntStatisticEntry => [ 217 it.entries += createIntStatisticEntry => [
157 it.name = "TypeAnalysisTime" it.value = (method.statistics.PreliminaryTypeAnalisisTime/1000000) as int 218 it.name = "TypeAnalysisTime"
219 it.value = (method.statistics.preliminaryTypeAnalisisTime / 1000000) as int
158 ] 220 ]
159 it.entries += createIntStatisticEntry => [ 221 it.entries += createIntStatisticEntry => [
160 it.name = "StateCoderTime" it.value = (statecoder.runtime/1000000) as int 222 it.name = "StateCoderTime"
223 it.value = (statecoder.runtime / 1000000) as int
161 ] 224 ]
162 it.entries += createIntStatisticEntry => [ 225 it.entries += createIntStatisticEntry => [
163 it.name = "StateCoderFailCount" it.value = strategy.numberOfStatecoderFail 226 it.name = "StateCoderFailCount"
227 it.value = strategy.numberOfStatecoderFail
228 ]
229 it.entries += createIntStatisticEntry => [
230 it.name = "SolutionCopyTime"
231 it.value = (solutionCopier.getTotalCopierRuntime / 1000000) as int
232 ]
233 it.entries += createIntStatisticEntry => [
234 it.name = "States"
235 it.value = dse.numberOfStates as int
164 ] 236 ]
165 it.entries += createIntStatisticEntry => [ 237 it.entries += createIntStatisticEntry => [
166 it.name = "ForwardTime" it.value = (strategy.forwardTime/1000000) as int 238 it.name = "ForwardTime" it.value = (strategy.forwardTime/1000000) as int
@@ -175,12 +247,28 @@ class ViatraReasoner extends LogicReasoner{
175 it.name = "FitnessCalculationTime" it.value = (strategy.fitnessCalculationTime/1000000) as int 247 it.name = "FitnessCalculationTime" it.value = (strategy.fitnessCalculationTime/1000000) as int
176 ] 248 ]
177 it.entries += createIntStatisticEntry => [ 249 it.entries += createIntStatisticEntry => [
178 it.name = "SolutionCopyTime" it.value = (strategy.solutionStoreWithCopy.sumRuntime/1000000) as int 250 it.name = "SolutionCopyTime" it.value = (solutionSaver.totalCopierRuntime/1000000) as int
179 ] 251 ]
180 it.entries += createIntStatisticEntry => [ 252 it.entries += createIntStatisticEntry => [
181 it.name = "ActivationSelectionTime" it.value = (strategy.activationSelector.runtime/1000000) as int 253 it.name = "ActivationSelectionTime" it.value = (strategy.activationSelector.runtime/1000000) as int
182 ] 254 ]
183 it.entries += createIntStatisticEntry => [ 255 it.entries += createIntStatisticEntry => [
256 it.name = "Decisions"
257 it.value = method.statistics.decisionsTried
258 ]
259 it.entries += createIntStatisticEntry => [
260 it.name = "Transformations"
261 it.value = method.statistics.transformationInvocations
262 ]
263 it.entries += createIntStatisticEntry => [
264 it.name = "ScopePropagations"
265 it.value = method.statistics.scopePropagatorInvocations
266 ]
267 it.entries += createIntStatisticEntry => [
268 it.name = "ScopePropagationsSolverCalls"
269 it.value = method.statistics.scopePropagatorSolverInvocations
270 ]
271 it.entries += createIntStatisticEntry => [
184 it.name = "NumericalSolverSumTime" it.value = (strategy.numericSolver.runtime/1000000) as int 272 it.name = "NumericalSolverSumTime" it.value = (strategy.numericSolver.runtime/1000000) as int
185 ] 273 ]
186 it.entries += createIntStatisticEntry => [ 274 it.entries += createIntStatisticEntry => [
@@ -201,61 +289,67 @@ class ViatraReasoner extends LogicReasoner{
201 it.entries += createIntStatisticEntry => [ 289 it.entries += createIntStatisticEntry => [
202 it.name = "NumericalSolverCachedAnswerNumber" it.value = strategy.numericSolver.numberOfCachedSolverCalls 290 it.name = "NumericalSolverCachedAnswerNumber" it.value = strategy.numericSolver.numberOfCachedSolverCalls
203 ] 291 ]
204 if(strategy.solutionStoreWithDiversityDescriptor.isActive) { 292 if(diversityChecker.active) {
205 it.entries += createIntStatisticEntry => [ 293 it.entries += createIntStatisticEntry => [
206 it.name = "SolutionDiversityCheckTime" it.value = (strategy.solutionStoreWithDiversityDescriptor.sumRuntime/1000000) as int 294 it.name = "SolutionDiversityCheckTime"
295 it.value = (diversityChecker.totalRuntime / 1000000) as int
207 ] 296 ]
208 it.entries += createRealStatisticEntry => [ 297 it.entries += createRealStatisticEntry => [
209 it.name = "SolutionDiversitySuccessRate" it.value = strategy.solutionStoreWithDiversityDescriptor.successRate 298 it.name = "SolutionDiversitySuccessRate"
299 it.value = diversityChecker.successRate
210 ] 300 ]
211 } 301 }
212 ] 302 ]
213 303
214 viatraConfig.progressMonitor.workedBackwardTransformationFinished 304 viatraConfig.progressMonitor.workedBackwardTransformationFinished
215 305
216 if(stoppedByTimeout) { 306 if (stoppedByTimeout) {
217 return createInsuficientResourcesResult=>[ 307 return createInsuficientResourcesResult => [
218 it.problem = problem 308 it.problem = problem
219 it.resourceName="time" 309 it.resourceName = "time"
220 it.representation += strategy.solutionStoreWithCopy.solutions 310 it.representation += solutionCopier.getPartialInterpretations(true)
221 it.statistics = statistics 311 it.statistics = statistics
222 ] 312 ]
223 } else { 313 } else {
224 if(solutionStore.solutions.empty) { 314 if (solutionStore.solutions.empty) {
225 return createInconsistencyResult => [ 315 return createInconsistencyResult => [
226 it.problem = problem 316 it.problem = problem
227 it.representation += strategy.solutionStoreWithCopy.solutions 317 it.representation += solutionCopier.getPartialInterpretations(true)
228 it.statistics = statistics 318 it.statistics = statistics
229 ] 319 ]
230 } else { 320 } else {
231 return createModelResult => [ 321 return createModelResult => [
232 it.problem = problem 322 it.problem = problem
233 it.trace = strategy.solutionStoreWithCopy.copyTraces 323 it.trace = solutionCopier.getTraces(true)
234 it.representation += strategy.solutionStoreWithCopy.solutions 324 it.representation += solutionCopier.getPartialInterpretations(true)
235 it.statistics = statistics 325 it.statistics = statistics
236 ] 326 ]
237 } 327 }
238 } 328 }
239 } 329 }
240 330
241 private def dispatch long runtime(NeighbourhoodBasedStateCoderFactory sc) { 331 private def dispatch long runtime(AbstractNeighbourhoodBasedStateCoderFactory sc) {
242 sc.sumStatecoderRuntime 332 sc.sumStatecoderRuntime
243 } 333 }
244 334
245 private def dispatch long runtime(IdentifierBasedStateCoderFactory sc) { 335 private def dispatch long runtime(IdentifierBasedStateCoderFactory sc) {
246 sc.sumStatecoderRuntime 336 sc.sumStatecoderRuntime
247 } 337 }
248 338
249 override getInterpretations(ModelResult modelResult) { 339 override getInterpretations(ModelResult modelResult) {
250 val indexes = 0..<modelResult.representation.size 340 val indexes = 0 ..< modelResult.representation.size
251 val traces = modelResult.trace as List<Map<EObject, EObject>>; 341 val traces = modelResult.trace as List<Map<EObject, EObject>>;
252 val res = indexes.map[i | new PartialModelAsLogicInterpretation(modelResult.representation.get(i) as PartialInterpretation,traces.get(i))].toList 342 val res = indexes.map [ i |
343 new PartialModelAsLogicInterpretation(modelResult.representation.get(i) as PartialInterpretation,
344 traces.get(i))
345 ].toList
253 return res 346 return res
254 } 347 }
255 348
256 private def ViatraReasonerConfiguration asConfig(LogicSolverConfiguration configuration) { 349 private def ViatraReasonerConfiguration asConfig(LogicSolverConfiguration configuration) {
257 if(configuration instanceof ViatraReasonerConfiguration) { 350 if (configuration instanceof ViatraReasonerConfiguration) {
258 return configuration 351 return configuration
259 } else throw new IllegalArgumentException('''Wrong configuration. Expected: «ViatraReasonerConfiguration.name», but got: «configuration.class.name»"''') 352 } else
353 throw new IllegalArgumentException('''Wrong configuration. Expected: «ViatraReasonerConfiguration.name», but got: «configuration.class.name»"''')
260 } 354 }
261} 355}
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 6e3c5235..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
@@ -6,19 +6,28 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RelationDeclaration
6import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeDeclaration 6import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeDeclaration
7import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod 7import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod
8import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeInferenceMethod 8import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeInferenceMethod
9import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedralScopePropagatorConstraints
10import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedralScopePropagatorSolver
11import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy
9import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualiser 12import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualiser
13import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveKind
14import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveThreshold
10import java.util.LinkedList 15import java.util.LinkedList
11import java.util.List 16import java.util.List
12import java.util.Set 17import java.util.Set
13import org.eclipse.xtext.xbase.lib.Functions.Function1 18import org.eclipse.xtext.xbase.lib.Functions.Function1
19import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint
14 20
15public enum StateCoderStrategy { 21enum StateCoderStrategy {
16 Neighbourhood, NeighbourhoodWithEquivalence, IDBased, DefinedByDiversity 22 Neighbourhood,
23 PairwiseNeighbourhood,
24 NeighbourhoodWithEquivalence,
25 IDBased,
26 DefinedByDiversity
17} 27}
18 28
19class ViatraReasonerConfiguration extends LogicSolverConfiguration{ 29class ViatraReasonerConfiguration extends LogicSolverConfiguration {
20 //public var Iterable<PQuery> existingQueries 30 // public var Iterable<PQuery> existingQueries
21
22 public var nameNewElements = false 31 public var nameNewElements = false
23 public var StateCoderStrategy stateCoderStrategy = StateCoderStrategy.Neighbourhood 32 public var StateCoderStrategy stateCoderStrategy = StateCoderStrategy.Neighbourhood
24 public var TypeInferenceMethod typeInferenceMethod = TypeInferenceMethod.PreliminaryAnalysis 33 public var TypeInferenceMethod typeInferenceMethod = TypeInferenceMethod.PreliminaryAnalysis
@@ -26,7 +35,7 @@ class ViatraReasonerConfiguration extends LogicSolverConfiguration{
26 * Once per 1/randomBacktrackChance the search selects a random state. 35 * Once per 1/randomBacktrackChance the search selects a random state.
27 */ 36 */
28 public var int randomBacktrackChance = 20; 37 public var int randomBacktrackChance = 20;
29 38
30 /** 39 /**
31 * Describes the required diversity between the solutions. 40 * Describes the required diversity between the solutions.
32 * Null means that the solutions have to have different state codes only. 41 * Null means that the solutions have to have different state codes only.
@@ -40,7 +49,7 @@ class ViatraReasonerConfiguration extends LogicSolverConfiguration{
40 /** 49 /**
41 * Configuration for debugging support. 50 * Configuration for debugging support.
42 */ 51 */
43 public var DebugConfiguration debugCongiguration = new DebugConfiguration 52 public var DebugConfiguration debugConfiguration = new DebugConfiguration
44 /** 53 /**
45 * Configuration for cutting search space. 54 * Configuration for cutting search space.
46 */ 55 */
@@ -54,10 +63,15 @@ class ViatraReasonerConfiguration extends LogicSolverConfiguration{
54 public var nonContainmentWeight = 1 63 public var nonContainmentWeight = 1
55 public var unfinishedWFWeight = 1 64 public var unfinishedWFWeight = 1
56 65
57 public var calculateObjectCreationCosts = false 66 public var ScopePropagatorStrategy scopePropagatorStrategy = new ScopePropagatorStrategy.Polyhedral(
67 PolyhedralScopePropagatorConstraints.Relational, PolyhedralScopePropagatorSolver.Clp)
68
69 public var List<LinearTypeConstraintHint> hints = newArrayList
70
71 public var List<CostObjectiveConfiguration> costObjectives = newArrayList
58} 72}
59 73
60public class DiversityDescriptor { 74class DiversityDescriptor {
61 public var ensureDiversity = false 75 public var ensureDiversity = false
62 public static val FixPointRange = -1 76 public static val FixPointRange = -1
63 public var int range = FixPointRange 77 public var int range = FixPointRange
@@ -67,20 +81,31 @@ public class DiversityDescriptor {
67 public var Set<RelationDeclaration> relevantRelations = null 81 public var Set<RelationDeclaration> relevantRelations = null
68} 82}
69 83
70public class DebugConfiguration { 84class DebugConfiguration {
71 public var logging = false 85 public var PartialInterpretationVisualiser partialInterpretatioVisualiser = null
72 public var PartialInterpretationVisualiser partialInterpretatioVisualiser = null;
73 public var partalInterpretationVisualisationFrequency = 1 86 public var partalInterpretationVisualisationFrequency = 1
74} 87}
75 88
76public class InternalConsistencyCheckerConfiguration { 89class InternalConsistencyCheckerConfiguration {
77 public var LogicReasoner internalIncosnsitencyDetector = null 90 public var LogicReasoner internalIncosnsitencyDetector = null
78 public var LogicSolverConfiguration internalInconsistencDetectorConfiguration = null 91 public var LogicSolverConfiguration internalInconsistencDetectorConfiguration = null
79 public var incternalConsistencyCheckingFrequency = 1 92 public var incternalConsistencyCheckingFrequency = 1
80} 93}
81 94
82public class SearchSpaceConstraint { 95class SearchSpaceConstraint {
83 public static val UNLIMITED_MAXDEPTH = Integer.MAX_VALUE 96 public static val UNLIMITED_MAXDEPTH = Integer.MAX_VALUE
84 public var int maxDepth = UNLIMITED_MAXDEPTH 97 public var int maxDepth = UNLIMITED_MAXDEPTH
85 public var List<Function1<ModelGenerationMethod, ModelGenerationMethodBasedGlobalConstraint>> additionalGlobalConstraints = new LinkedList 98 public var List<Function1<ModelGenerationMethod, ModelGenerationMethodBasedGlobalConstraint>> additionalGlobalConstraints = new LinkedList
86} \ No newline at end of file 99}
100
101class CostObjectiveConfiguration {
102 public var List<CostObjectiveElementConfiguration> elements = newArrayList
103 public var ObjectiveKind kind
104 public var ObjectiveThreshold threshold
105 public var boolean findExtremum
106}
107
108class CostObjectiveElementConfiguration {
109 public var String patternQualifiedName
110 public var int weight
111}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BasicScopeGlobalConstraint.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BasicScopeGlobalConstraint.xtend
new file mode 100644
index 00000000..67f447ed
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BasicScopeGlobalConstraint.xtend
@@ -0,0 +1,103 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse
2
3import com.google.common.collect.ImmutableList
4import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
5import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialTypeInterpratation
6import java.util.Comparator
7import java.util.List
8import org.eclipse.viatra.dse.base.ThreadContext
9import org.eclipse.viatra.dse.objectives.Comparators
10import org.eclipse.viatra.dse.objectives.IGlobalConstraint
11import org.eclipse.viatra.dse.objectives.IObjective
12import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor
13
14class BasicScopeGlobalConstraint implements IGlobalConstraint, IObjective {
15 val PartialInterpretation p
16 val List<ScopeAssertion> assertions
17
18 new(PartialInterpretation p) {
19 this.p = p
20 assertions = ImmutableList.copyOf(p.scopes.map [
21 val currentSize = targetTypeInterpretation.elements.size
22 val minElements = minNewElements + currentSize
23 val maxElements = if (maxNewElements < 0) {
24 -1
25 } else {
26 maxNewElements + currentSize
27 }
28 new ScopeAssertion(minElements, maxElements, targetTypeInterpretation)
29 ])
30 }
31
32 override init(ThreadContext context) {
33 if (context.model != p) {
34 throw new IllegalArgumentException(
35 "Partial model must be passed to the constructor of BasicScopeGlobalConstraint")
36 }
37 }
38
39 override checkGlobalConstraint(ThreadContext context) {
40 assertions.forall[upperBoundSatisfied]
41 }
42
43 override getFitness(ThreadContext context) {
44 var double fitness = p.minNewElements
45 for (assertion : assertions) {
46 if (!assertion.lowerBoundSatisfied) {
47 fitness += 1
48 }
49 }
50 fitness
51 }
52
53 override satisifiesHardObjective(Double fitness) {
54 fitness <= 0.01
55 }
56
57 override BasicScopeGlobalConstraint createNew() {
58 this
59 }
60
61 override getName() {
62 class.name
63 }
64
65 override getComparator() {
66 Comparators.LOWER_IS_BETTER
67 }
68
69 override getLevel() {
70 2
71 }
72
73 override isHardObjective() {
74 true
75 }
76
77 override setComparator(Comparator<Double> comparator) {
78 throw new UnsupportedOperationException
79 }
80
81 override setLevel(int level) {
82 throw new UnsupportedOperationException
83 }
84
85 @FinalFieldsConstructor
86 private static class ScopeAssertion {
87 val int lowerBound
88 val int upperBound
89 val PartialTypeInterpratation typeDefinitions
90
91 private def getCount() {
92 typeDefinitions.elements.size
93 }
94
95 private def isLowerBoundSatisfied() {
96 count >= lowerBound
97 }
98
99 private def isUpperBoundSatisfied() {
100 upperBound < 0 || count <= upperBound
101 }
102 }
103}
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 e3603af3..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,34 +9,25 @@
9 *******************************************************************************/ 9 *******************************************************************************/
10package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse; 10package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse;
11 11
12import java.io.BufferedReader;
13import java.io.IOException;
14import java.io.InputStreamReader;
15import java.util.ArrayList;
16import java.util.Arrays; 12import java.util.Arrays;
17import java.util.Collection;
18import java.util.Collections; 13import java.util.Collections;
19import java.util.Comparator; 14import java.util.Comparator;
20import java.util.Iterator; 15import java.util.Iterator;
21import java.util.LinkedList; 16import java.util.LinkedList;
22import java.util.List; 17import java.util.List;
23import java.util.Map;
24import java.util.PriorityQueue; 18import java.util.PriorityQueue;
25import java.util.Random; 19import java.util.Random;
26 20
27import org.apache.log4j.Logger; 21import org.apache.log4j.Logger;
28import org.eclipse.emf.ecore.EObject; 22import org.eclipse.emf.ecore.EObject;
29import org.eclipse.emf.ecore.util.EcoreUtil; 23import org.eclipse.emf.ecore.util.EcoreUtil;
24import org.eclipse.viatra.dse.api.SolutionTrajectory;
30import org.eclipse.viatra.dse.api.strategy.interfaces.IStrategy; 25import org.eclipse.viatra.dse.api.strategy.interfaces.IStrategy;
31import org.eclipse.viatra.dse.base.ThreadContext; 26import org.eclipse.viatra.dse.base.ThreadContext;
32import org.eclipse.viatra.dse.objectives.Fitness; 27import org.eclipse.viatra.dse.objectives.Fitness;
33import org.eclipse.viatra.dse.objectives.ObjectiveComparatorHelper; 28import org.eclipse.viatra.dse.objectives.ObjectiveComparatorHelper;
29import org.eclipse.viatra.dse.solutionstore.ISolutionFoundHandler;
34import org.eclipse.viatra.dse.solutionstore.SolutionStore; 30import org.eclipse.viatra.dse.solutionstore.SolutionStore;
35import org.eclipse.viatra.query.runtime.api.AdvancedViatraQueryEngine;
36import org.eclipse.viatra.query.runtime.api.IPatternMatch;
37import org.eclipse.viatra.query.runtime.api.IQuerySpecification;
38import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine;
39import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher;
40 31
41import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel; 32import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel;
42import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasoner; 33import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasoner;
@@ -44,7 +35,6 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem;
44import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.InconsistencyResult; 35import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.InconsistencyResult;
45import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicResult; 36import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicResult;
46import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult; 37import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult;
47import hu.bme.mit.inf.dslreasoner.viatra2logic.NumericProblemSolver;
48import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod; 38import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod;
49import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic.PartialInterpretation2Logic; 39import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic.PartialInterpretation2Logic;
50import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation; 40import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation;
@@ -83,14 +73,13 @@ public class BestFirstStrategyForModelGeneration implements IStrategy {
83 // Running 73 // Running
84 private PriorityQueue<TrajectoryWithFitness> trajectoiresToExplore; 74 private PriorityQueue<TrajectoryWithFitness> trajectoiresToExplore;
85 private SolutionStore solutionStore; 75 private SolutionStore solutionStore;
86 private SolutionStoreWithCopy solutionStoreWithCopy;
87 private SolutionStoreWithDiversityDescriptor solutionStoreWithDiversityDescriptor;
88 private volatile boolean isInterrupted = false; 76 private volatile boolean isInterrupted = false;
89 private ModelResult modelResultByInternalSolver = null; 77 private ModelResult modelResultByInternalSolver = null;
90 private Random random = new Random(); 78 private Random random = new Random();
91 //private Collection<ViatraQueryMatcher<? extends IPatternMatch>> matchers; 79 //private Collection<ViatraQueryMatcher<? extends IPatternMatch>> matchers;
92 public ActivationSelector activationSelector = new EvenActivationSelector(random); 80 public ActivationSelector activationSelector = new EvenActivationSelector(random);
93 public NumericSolver numericSolver = null; 81 public ViatraReasonerSolutionSaver solutionSaver;
82 public NumericSolver numericSolver;
94 // Statistics 83 // Statistics
95 private int numberOfStatecoderFail = 0; 84 private int numberOfStatecoderFail = 0;
96 private int numberOfPrintedModel = 0; 85 private int numberOfPrintedModel = 0;
@@ -103,19 +92,17 @@ public class BestFirstStrategyForModelGeneration implements IStrategy {
103 public BestFirstStrategyForModelGeneration( 92 public BestFirstStrategyForModelGeneration(
104 ReasonerWorkspace workspace, 93 ReasonerWorkspace workspace,
105 ViatraReasonerConfiguration configuration, 94 ViatraReasonerConfiguration configuration,
106 ModelGenerationMethod method) 95 ModelGenerationMethod method,
107 { 96 ViatraReasonerSolutionSaver solutionSaver,
97 NumericSolver numericSolver) {
108 this.workspace = workspace; 98 this.workspace = workspace;
109 this.configuration = configuration; 99 this.configuration = configuration;
110 this.method = method; 100 this.method = method;
101 this.solutionSaver = solutionSaver;
102 this.numericSolver = numericSolver;
103 //logger.setLevel(Level.DEBUG);
111 } 104 }
112 105
113 public SolutionStoreWithCopy getSolutionStoreWithCopy() {
114 return solutionStoreWithCopy;
115 }
116 public SolutionStoreWithDiversityDescriptor getSolutionStoreWithDiversityDescriptor() {
117 return solutionStoreWithDiversityDescriptor;
118 }
119 public int getNumberOfStatecoderFail() { 106 public int getNumberOfStatecoderFail() {
120 return numberOfStatecoderFail; 107 return numberOfStatecoderFail;
121 } 108 }
@@ -125,22 +112,35 @@ public class BestFirstStrategyForModelGeneration implements IStrategy {
125 public long getBacktrackingTime() { 112 public long getBacktrackingTime() {
126 return context.getDesignSpaceManager().getBacktrackingTime(); 113 return context.getDesignSpaceManager().getBacktrackingTime();
127 } 114 }
128 //LinkedList<ViatraQueryMatcher<? extends IPatternMatch>> matchers; 115
129 @Override 116 @Override
130 public void initStrategy(ThreadContext context) { 117 public void initStrategy(ThreadContext context) {
131 this.context = context; 118 this.context = context;
132 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);
133 135
134// ViatraQueryEngine engine = context.getQueryEngine(); 136// ViatraQueryEngine engine = context.getQueryEngine();
135// // TODO: visualisation
136// matchers = new LinkedList<ViatraQueryMatcher<? extends IPatternMatch>>(); 137// matchers = new LinkedList<ViatraQueryMatcher<? extends IPatternMatch>>();
137// for(IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> p : this.method.getAllPatterns()) { 138// for(IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> p : this.method.getAllPatterns()) {
138// //System.out.println(p.getSimpleName()); 139// //System.out.println(p.getSimpleName());
139// ViatraQueryMatcher<? extends IPatternMatch> matcher = p.getMatcher(engine); 140// ViatraQueryMatcher<? extends IPatternMatch> matcher = p.getMatcher(engine);
140// matchers.add(matcher); 141// matchers.add(matcher);
141// } 142// }
142 this.solutionStoreWithCopy = new SolutionStoreWithCopy(); 143
143 this.solutionStoreWithDiversityDescriptor = new SolutionStoreWithDiversityDescriptor(configuration.diversityRequirement);
144 final ObjectiveComparatorHelper objectiveComparatorHelper = context.getObjectiveComparatorHelper(); 144 final ObjectiveComparatorHelper objectiveComparatorHelper = context.getObjectiveComparatorHelper();
145 this.comparator = new Comparator<TrajectoryWithFitness>() { 145 this.comparator = new Comparator<TrajectoryWithFitness>() {
146 @Override 146 @Override
@@ -148,8 +148,6 @@ public class BestFirstStrategyForModelGeneration implements IStrategy {
148 return objectiveComparatorHelper.compare(o2.fitness, o1.fitness); 148 return objectiveComparatorHelper.compare(o2.fitness, o1.fitness);
149 } 149 }
150 }; 150 };
151
152 this.numericSolver = new NumericSolver(context, method, this.configuration.runIntermediateNumericalConsistencyChecks, false);
153 151
154 trajectoiresToExplore = new PriorityQueue<TrajectoryWithFitness>(11, comparator); 152 trajectoiresToExplore = new PriorityQueue<TrajectoryWithFitness>(11, comparator);
155 } 153 }
@@ -176,14 +174,13 @@ public class BestFirstStrategyForModelGeneration implements IStrategy {
176 return; 174 return;
177 } 175 }
178 176
179 final Fitness firstFittness = calculateFitness(); 177 final Fitness firstFitness = calculateFitness();
180 checkForSolution(firstFittness); 178 checkForSolution(firstFitness);
181 179
182 final ObjectiveComparatorHelper objectiveComparatorHelper = context.getObjectiveComparatorHelper(); 180 final ObjectiveComparatorHelper objectiveComparatorHelper = context.getObjectiveComparatorHelper();
183 final Object[] firstTrajectory = context.getTrajectory().toArray(new Object[0]); 181 final Object[] firstTrajectory = context.getTrajectory().toArray(new Object[0]);
184 TrajectoryWithFitness currentTrajectoryWithFittness = new TrajectoryWithFitness(firstTrajectory, firstFittness); 182 TrajectoryWithFitness currentTrajectoryWithFitness = new TrajectoryWithFitness(firstTrajectory, firstFitness);
185 trajectoiresToExplore.add(currentTrajectoryWithFittness); 183 trajectoiresToExplore.add(currentTrajectoryWithFitness);
186
187 //if(configuration) 184 //if(configuration)
188 visualiseCurrentState(); 185 visualiseCurrentState();
189// for(ViatraQueryMatcher<? extends IPatternMatch> matcher : matchers) { 186// for(ViatraQueryMatcher<? extends IPatternMatch> matcher : matchers) {
@@ -197,22 +194,22 @@ public class BestFirstStrategyForModelGeneration implements IStrategy {
197 194
198 mainLoop: while (!isInterrupted && !configuration.progressMonitor.isCancelled()) { 195 mainLoop: while (!isInterrupted && !configuration.progressMonitor.isCancelled()) {
199 196
200 if (currentTrajectoryWithFittness == null) { 197 if (currentTrajectoryWithFitness == null) {
201 if (trajectoiresToExplore.isEmpty()) { 198 if (trajectoiresToExplore.isEmpty()) {
202 logger.debug("State space is fully traversed."); 199 logger.debug("State space is fully traversed.");
203 return; 200 return;
204 } else { 201 } else {
205 currentTrajectoryWithFittness = selectState(); 202 currentTrajectoryWithFitness = selectState();
206 if (logger.isDebugEnabled()) { 203 if (logger.isDebugEnabled()) {
207 logger.debug("Current trajectory: " + Arrays.toString(context.getTrajectory().toArray())); 204 logger.debug("Current trajectory: " + Arrays.toString(context.getTrajectory().toArray()));
208 logger.debug("New trajectory is chosen: " + currentTrajectoryWithFittness); 205 logger.debug("New trajectory is chosen: " + currentTrajectoryWithFitness);
209 } 206 }
210 context.getDesignSpaceManager().executeTrajectoryWithMinimalBacktrackWithoutStateCoding(currentTrajectoryWithFittness.trajectory); 207 context.getDesignSpaceManager().executeTrajectoryWithMinimalBacktrackWithoutStateCoding(currentTrajectoryWithFitness.trajectory);
211 } 208 }
212 } 209 }
213 210
214// visualiseCurrentState(); 211// visualiseCurrentState();
215// boolean consistencyCheckResult = checkConsistency(currentTrajectoryWithFittness); 212// boolean consistencyCheckResult = checkConsistency(currentTrajectoryWithfitness);
216// if(consistencyCheckResult == true) { 213// if(consistencyCheckResult == true) {
217// continue mainLoop; 214// continue mainLoop;
218// } 215// }
@@ -224,10 +221,11 @@ public class BestFirstStrategyForModelGeneration implements IStrategy {
224 final Object nextActivation = iterator.next(); 221 final Object nextActivation = iterator.next();
225// if (!iterator.hasNext()) { 222// if (!iterator.hasNext()) {
226// logger.debug("Last untraversed activation of the state."); 223// logger.debug("Last untraversed activation of the state.");
227// trajectoiresToExplore.remove(currentTrajectoryWithFittness); 224// trajectoiresToExplore.remove(currentTrajectoryWithfitness);
228// } 225// }
229 logger.debug("Executing new activation: " + nextActivation); 226 logger.debug("Executing new activation: " + nextActivation);
230 context.executeAcitvationId(nextActivation); 227 context.executeAcitvationId(nextActivation);
228 method.getStatistics().incrementDecisionCount();
231 229
232 visualiseCurrentState(); 230 visualiseCurrentState();
233// for(ViatraQueryMatcher<? extends IPatternMatch> matcher : matchers) { 231// for(ViatraQueryMatcher<? extends IPatternMatch> matcher : matchers) {
@@ -238,7 +236,7 @@ public class BestFirstStrategyForModelGeneration implements IStrategy {
238// 236//
239// } 237// }
240 238
241 boolean consistencyCheckResult = checkConsistency(currentTrajectoryWithFittness); 239 boolean consistencyCheckResult = checkConsistency(currentTrajectoryWithFitness);
242 if(consistencyCheckResult == true) { continue mainLoop; } 240 if(consistencyCheckResult == true) { continue mainLoop; }
243 241
244 if (context.isCurrentStateAlreadyTraversed()) { 242 if (context.isCurrentStateAlreadyTraversed()) {
@@ -251,7 +249,7 @@ public class BestFirstStrategyForModelGeneration implements IStrategy {
251 logger.debug("Numeric constraints are not satisifed."); 249 logger.debug("Numeric constraints are not satisifed.");
252 context.backtrack(); 250 context.backtrack();
253 } else { 251 } else {
254 final Fitness nextFitness = calculateFitness(); 252 final Fitness nextFitness = context.calculateFitness();
255 checkForSolution(nextFitness); 253 checkForSolution(nextFitness);
256 if (context.getDepth() > configuration.searchSpaceConstraints.maxDepth) { 254 if (context.getDepth() > configuration.searchSpaceConstraints.maxDepth) {
257 logger.debug("Reached max depth."); 255 logger.debug("Reached max depth.");
@@ -259,31 +257,31 @@ public class BestFirstStrategyForModelGeneration implements IStrategy {
259 continue; 257 continue;
260 } 258 }
261 259
262 TrajectoryWithFitness nextTrajectoryWithFittness = new TrajectoryWithFitness( 260 TrajectoryWithFitness nextTrajectoryWithfitness = new TrajectoryWithFitness(
263 context.getTrajectory().toArray(), nextFitness); 261 context.getTrajectory().toArray(), nextFitness);
264 trajectoiresToExplore.add(nextTrajectoryWithFittness); 262 trajectoiresToExplore.add(nextTrajectoryWithfitness);
265 263
266 int compare = objectiveComparatorHelper.compare(currentTrajectoryWithFittness.fitness, 264 int compare = objectiveComparatorHelper.compare(currentTrajectoryWithFitness.fitness,
267 nextTrajectoryWithFittness.fitness); 265 nextTrajectoryWithfitness.fitness);
268 if (compare < 0) { 266 if (compare < 0) {
269 logger.debug("Better fitness, moving on: " + nextFitness); 267 logger.debug("Better fitness, moving on: " + nextFitness);
270 currentTrajectoryWithFittness = nextTrajectoryWithFittness; 268 currentTrajectoryWithFitness = nextTrajectoryWithfitness;
271 continue mainLoop; 269 continue mainLoop;
272 } else if (compare == 0) { 270 } else if (compare == 0) {
273 logger.debug("Equally good fitness, moving on: " + nextFitness); 271 logger.debug("Equally good fitness, moving on: " + nextFitness);
274 currentTrajectoryWithFittness = nextTrajectoryWithFittness; 272 currentTrajectoryWithFitness = nextTrajectoryWithfitness;
275 continue mainLoop; 273 continue mainLoop;
276 } else { 274 } else {
277 logger.debug("Worse fitness."); 275 logger.debug("Worse fitness.");
278 currentTrajectoryWithFittness = null; 276 currentTrajectoryWithFitness = null;
279 continue mainLoop; 277 continue mainLoop;
280 } 278 }
281 } 279 }
282 } 280 }
283 281
284 logger.debug("State is fully traversed."); 282 logger.debug("State is fully traversed.");
285 trajectoiresToExplore.remove(currentTrajectoryWithFittness); 283 trajectoiresToExplore.remove(currentTrajectoryWithFitness);
286 currentTrajectoryWithFittness = null; 284 currentTrajectoryWithFitness = null;
287 285
288 } 286 }
289 logger.info("Interrupted."); 287 logger.info("Interrupted.");
@@ -308,6 +306,7 @@ public class BestFirstStrategyForModelGeneration implements IStrategy {
308 try { 306 try {
309 activationIds = this.activationSelector.randomizeActivationIDs(context.getUntraversedActivationIds()); 307 activationIds = this.activationSelector.randomizeActivationIDs(context.getUntraversedActivationIds());
310 } catch (NullPointerException e) { 308 } catch (NullPointerException e) {
309// logger.warn("Unexpected state code: " + context.getDesignSpaceManager().getCurrentState());
311 numberOfStatecoderFail++; 310 numberOfStatecoderFail++;
312 activationIds = Collections.emptyList(); 311 activationIds = Collections.emptyList();
313 } 312 }
@@ -315,27 +314,16 @@ public class BestFirstStrategyForModelGeneration implements IStrategy {
315 } 314 }
316 315
317 private void checkForSolution(final Fitness fittness) { 316 private void checkForSolution(final Fitness fittness) {
318 if (fittness.isSatisifiesHardObjectives()) { 317 solutionStore.newSolution(context);
319 if (solutionStoreWithDiversityDescriptor.isDifferent(context)) {
320 if(numericSolver.currentSatisfiable()) {
321 Map<EObject, EObject> trace = solutionStoreWithCopy.newSolution(context);
322 numericSolver.fillSolutionCopy(trace);
323 solutionStoreWithDiversityDescriptor.newSolution(context);
324 solutionStore.newSolution(context);
325 configuration.progressMonitor.workedModelFound(configuration.solutionScope.numberOfRequiredSolution);
326 saveTimes();
327 logger.debug("Found a solution.");
328 }
329 }
330 }
331 } 318 }
319
332 public List<String> times = new LinkedList<String>(); 320 public List<String> times = new LinkedList<String>();
333 private void saveTimes() { 321 private void saveTimes() {
334 long statecoderTime = ((NeighbourhoodBasedPartialInterpretationStateCoder)this.context.getStateCoder()).getStatecoderRuntime()/1000000; 322 long statecoderTime = ((NeighbourhoodBasedPartialInterpretationStateCoder<?, ?>)this.context.getStateCoder()).getStatecoderRuntime()/1000000;
335 long forwardTime = context.getDesignSpaceManager().getForwardTime()/1000000; 323 long forwardTime = context.getDesignSpaceManager().getForwardTime()/1000000;
336 long backtrackingTime = context.getDesignSpaceManager().getBacktrackingTime()/1000000; 324 long backtrackingTime = context.getDesignSpaceManager().getBacktrackingTime()/1000000;
337 long solutionCopy = solutionStoreWithCopy.getSumRuntime()/1000000;
338 long activationSelection = this.activationSelector.getRuntime()/1000000; 325 long activationSelection = this.activationSelector.getRuntime()/1000000;
326 long solutionCopierTime = this.solutionSaver.getTotalCopierRuntime()/1000000;
339 long numericalSolverSumTime = this.numericSolver.getRuntime()/1000000; 327 long numericalSolverSumTime = this.numericSolver.getRuntime()/1000000;
340 long numericalSolverProblemForming = this.numericSolver.getSolverSolvingProblem()/1000000; 328 long numericalSolverProblemForming = this.numericSolver.getSolverSolvingProblem()/1000000;
341 long numericalSolverSolving = this.numericSolver.getSolverSolvingProblem()/1000000; 329 long numericalSolverSolving = this.numericSolver.getSolverSolvingProblem()/1000000;
@@ -347,8 +335,8 @@ public class BestFirstStrategyForModelGeneration implements IStrategy {
347 "|Backtrackingtime:"+backtrackingTime+ 335 "|Backtrackingtime:"+backtrackingTime+
348 "|GlobalConstraintEvaluationTime:"+(globalConstraintEvaluationTime/1000000)+ 336 "|GlobalConstraintEvaluationTime:"+(globalConstraintEvaluationTime/1000000)+
349 "|FitnessCalculationTime:"+(fitnessCalculationTime/1000000)+ 337 "|FitnessCalculationTime:"+(fitnessCalculationTime/1000000)+
350 "|SolutionCopyTime:"+solutionCopy+
351 "|ActivationSelectionTime:"+activationSelection+ 338 "|ActivationSelectionTime:"+activationSelection+
339 "|SolutionCopyTime:"+solutionCopierTime+
352 "|NumericalSolverSumTime:"+numericalSolverSumTime+ 340 "|NumericalSolverSumTime:"+numericalSolverSumTime+
353 "|NumericalSolverProblemFormingTime:"+numericalSolverProblemForming+ 341 "|NumericalSolverProblemFormingTime:"+numericalSolverProblemForming+
354 "|NumericalSolverSolvingTime:"+numericalSolverSolving+ 342 "|NumericalSolverSolvingTime:"+numericalSolverSolving+
@@ -385,13 +373,16 @@ public class BestFirstStrategyForModelGeneration implements IStrategy {
385 } 373 }
386 374
387 public void visualiseCurrentState() { 375 public void visualiseCurrentState() {
388 PartialInterpretationVisualiser partialInterpretatioVisualiser = configuration.debugCongiguration.partialInterpretatioVisualiser; 376 PartialInterpretationVisualiser partialInterpretatioVisualiser = configuration.debugConfiguration.partialInterpretatioVisualiser;
389 if(partialInterpretatioVisualiser != null && this.configuration.documentationLevel == DocumentationLevel.FULL && workspace != null) { 377 if(partialInterpretatioVisualiser != null && this.configuration.documentationLevel == DocumentationLevel.FULL && workspace != null) {
390 PartialInterpretation p = (PartialInterpretation) (context.getModel()); 378 PartialInterpretation p = (PartialInterpretation) (context.getModel());
391 int id = ++numberOfPrintedModel; 379 int id = ++numberOfPrintedModel;
392 if (id % configuration.debugCongiguration.partalInterpretationVisualisationFrequency == 0) { 380 if (id % configuration.debugConfiguration.partalInterpretationVisualisationFrequency == 0) {
393 PartialInterpretationVisualisation visualisation = partialInterpretatioVisualiser.visualiseConcretization(p); 381 PartialInterpretationVisualisation visualisation = partialInterpretatioVisualiser.visualiseConcretization(p);
394 visualisation.writeToFile(workspace, String.format("state%09d.png", id)); 382 logger.debug("Visualizing state: " + id + " (" + context.getDesignSpaceManager().getCurrentState() + ")");
383 String name = String.format("state%09d", id);
384 visualisation.writeToFile(workspace, name + ".png");
385 workspace.writeModel((EObject) context.getModel(), name + ".xmi");
395 } 386 }
396 } 387 }
397 } 388 }
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/DiversityChecker.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/DiversityChecker.xtend
new file mode 100644
index 00000000..fb1b2066
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/DiversityChecker.xtend
@@ -0,0 +1,184 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse
2
3import com.google.common.collect.HashMultiset
4import com.google.common.collect.ImmutableSet
5import com.google.common.collect.Multiset
6import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.neighbourhood.AbstractNodeDescriptor
7import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.neighbourhood.NeighbourhoodWithTraces
8import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.neighbourhood.PartialInterpretation2ImmutableTypeLattice
9import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
10import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.DiversityDescriptor
11import java.util.Collection
12import java.util.HashSet
13import java.util.Map
14import java.util.Set
15import org.eclipse.viatra.dse.base.ThreadContext
16import org.eclipse.xtend.lib.annotations.Accessors
17
18interface DiversityChecker {
19 public static val NO_DIVERSITY_CHECKER = new DiversityChecker {
20 override isActive() {
21 false
22 }
23
24 override getTotalRuntime() {
25 0
26 }
27
28 override getSuccessRate() {
29 1.0
30 }
31
32 override newSolution(ThreadContext threadContext, Object solutionId, Collection<Object> dominatedSolutionIds) {
33 true
34 }
35 }
36
37 def boolean isActive()
38
39 def long getTotalRuntime()
40
41 def double getSuccessRate()
42
43 def boolean newSolution(ThreadContext threadContext, Object solutionId, Collection<Object> dominatedSolutionIds)
44
45 static def of(DiversityDescriptor descriptor) {
46 if (descriptor.ensureDiversity) {
47 new NodewiseDiversityChecker(descriptor)
48 } else {
49 NO_DIVERSITY_CHECKER
50 }
51 }
52}
53
54abstract class AbstractDiversityChecker implements DiversityChecker {
55 val DiversityDescriptor descriptor
56 val PartialInterpretation2ImmutableTypeLattice solutionCoder = new PartialInterpretation2ImmutableTypeLattice
57
58 @Accessors(PUBLIC_GETTER) var long totalRuntime = 0
59 var int allCheckCount = 0
60 var int successfulCheckCount = 0
61
62 protected new(DiversityDescriptor descriptor) {
63 if (!descriptor.ensureDiversity) {
64 throw new IllegalArgumentException(
65 "Diversity description should enforce diversity or NO_DIVERSITY_CHECKER should be used instead.")
66 }
67 this.descriptor = descriptor
68 }
69
70 override isActive() {
71 true
72 }
73
74 override getTotalRuntime() {
75 throw new UnsupportedOperationException("TODO: auto-generated method stub")
76 }
77
78 override getSuccessRate() {
79 (allCheckCount as double) / (successfulCheckCount as double)
80 }
81
82 override newSolution(ThreadContext threadContext, Object solutionId, Collection<Object> dominatedSolutionIds) {
83 val start = System.nanoTime
84 val model = threadContext.model as PartialInterpretation
85 val representation = solutionCoder.createRepresentation(model, descriptor.range, descriptor.parallels,
86 descriptor.maxNumber, descriptor.relevantTypes, descriptor.relevantRelations)
87 val isDifferent = internalNewSolution(representation, solutionId, dominatedSolutionIds)
88 totalRuntime += System.nanoTime - start
89 allCheckCount++
90 if (isDifferent) {
91 successfulCheckCount++
92 }
93 isDifferent
94 }
95
96 protected abstract def boolean internalNewSolution(
97 NeighbourhoodWithTraces<Map<? extends AbstractNodeDescriptor, Integer>, AbstractNodeDescriptor> representation,
98 Object solutionId, Collection<Object> dominatedSolutionIds)
99}
100
101class NodewiseDiversityChecker extends AbstractDiversityChecker {
102 var Multiset<Integer> nodeCodes = HashMultiset.create
103 val Map<Object, Set<Integer>> tracedNodeCodes = newHashMap
104
105 new(DiversityDescriptor descriptor) {
106 super(descriptor)
107 }
108
109 override protected internalNewSolution(
110 NeighbourhoodWithTraces<Map<? extends AbstractNodeDescriptor, Integer>, AbstractNodeDescriptor> representation,
111 Object solutionId, Collection<Object> dominatedSolutionIds) {
112 val nodeCodesInSolution = ImmutableSet.copyOf(representation.modelRepresentation.keySet.map[hashCode])
113 val remainingNodeCodes = if (dominatedSolutionIds.empty) {
114 nodeCodes
115 } else {
116 getRemainingNodeCodes(dominatedSolutionIds)
117 }
118 val hasNewCode = nodeCodesInSolution.exists[!remainingNodeCodes.contains(it)]
119 if (hasNewCode) {
120 nodeCodes = remainingNodeCodes
121 nodeCodes.addAll(nodeCodesInSolution)
122 for (dominatedSolutionId : dominatedSolutionIds) {
123 tracedNodeCodes.remove(dominatedSolutionId)
124 }
125 tracedNodeCodes.put(solutionId, nodeCodesInSolution)
126 }
127 hasNewCode
128 }
129
130 private def getRemainingNodeCodes(Collection<Object> dominatedSolutionIds) {
131 // TODO Optimize multiset operations.
132 val copyOfNodeCodes = HashMultiset.create(nodeCodes)
133 for (dominatedSolutionId : dominatedSolutionIds) {
134 val dominatedModelCode = tracedNodeCodes.get(dominatedSolutionId)
135 if (dominatedModelCode === null) {
136 throw new IllegalArgumentException("Unknown dominated solution: " + dominatedSolutionId)
137 }
138 copyOfNodeCodes.removeAll(dominatedModelCode)
139 }
140 copyOfNodeCodes
141 }
142}
143
144class GraphwiseDiversityChecker extends AbstractDiversityChecker {
145 var Set<Integer> modelCodes = newHashSet
146 val Map<Object, Integer> tracedModelCodes = newHashMap
147
148 new(DiversityDescriptor descriptor) {
149 super(descriptor)
150 }
151
152 override protected internalNewSolution(
153 NeighbourhoodWithTraces<Map<? extends AbstractNodeDescriptor, Integer>, AbstractNodeDescriptor> representation,
154 Object solutionId, Collection<Object> dominatedSolutionIds) {
155 val modelCodeOfSolution = representation.modelRepresentation.hashCode
156 val remainingModelCodes = if (dominatedSolutionIds.empty) {
157 modelCodes
158 } else {
159 getRemainingModelCodes(dominatedSolutionIds)
160 }
161 val isNewCode = !remainingModelCodes.contains(modelCodeOfSolution)
162 if (isNewCode) {
163 modelCodes = remainingModelCodes
164 modelCodes += modelCodeOfSolution
165 for (dominatedSolutionId : dominatedSolutionIds) {
166 tracedModelCodes.remove(dominatedSolutionId)
167 }
168 tracedModelCodes.put(solutionId, modelCodeOfSolution)
169 }
170 isNewCode
171 }
172
173 private def getRemainingModelCodes(Collection<Object> dominatedSolutionIds) {
174 val copyOfModelCodes = new HashSet(modelCodes)
175 for (dominatedSolutionId : dominatedSolutionIds) {
176 val dominatedModelCode = tracedModelCodes.get(dominatedSolutionId)
177 if (dominatedModelCode === null) {
178 throw new IllegalArgumentException("Unknown dominated solution: " + dominatedSolutionId)
179 }
180 copyOfModelCodes -= dominatedModelCode
181 }
182 copyOfModelCodes
183 }
184}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/DseUtils.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/DseUtils.xtend
new file mode 100644
index 00000000..3c2e3319
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/DseUtils.xtend
@@ -0,0 +1,66 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse
2
3import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.IThreeValuedObjective
4import org.eclipse.viatra.dse.base.ThreadContext
5import org.eclipse.viatra.dse.objectives.Comparators
6import org.eclipse.viatra.dse.objectives.Fitness
7import org.eclipse.viatra.dse.objectives.IObjective
8
9final class DseUtils {
10 private new() {
11 throw new IllegalStateException("This is a static utility class and should not be instantiated directly.")
12 }
13
14 static def calculateFitness(ThreadContext it, (IObjective)=>Double getFitness) {
15 val result = new Fitness
16 var boolean satisifiesHardObjectives = true
17 for (objective : objectives) {
18 val fitness = getFitness.apply(objective)
19 result.put(objective.name, fitness)
20 if (objective.isHardObjective() && !objective.satisifiesHardObjective(fitness)) {
21 satisifiesHardObjectives = false
22 }
23 }
24 result.satisifiesHardObjectives = satisifiesHardObjectives
25 result
26 }
27
28 static def caclulateBestPossibleFitness(ThreadContext threadContext) {
29 threadContext.calculateFitness [ objective |
30 if (objective instanceof IThreeValuedObjective) {
31 objective.getBestPossibleFitness(threadContext)
32 } else {
33 switch (objective.comparator) {
34 case Comparators.LOWER_IS_BETTER:
35 Double.NEGATIVE_INFINITY
36 case Comparators.HIGHER_IS_BETTER:
37 Double.POSITIVE_INFINITY
38 case Comparators.DIFFERENCE_TO_ZERO_IS_BETTER:
39 0.0
40 default:
41 throw new IllegalArgumentException("Unknown comparator for non-three-valued objective: " +
42 objective.name)
43 }
44 }
45 ]
46 }
47
48 static def caclulateWorstPossibleFitness(ThreadContext threadContext) {
49 threadContext.calculateFitness [ objective |
50 if (objective instanceof IThreeValuedObjective) {
51 objective.getWorstPossibleFitness(threadContext)
52 } else {
53 switch (objective.comparator) {
54 case Comparators.LOWER_IS_BETTER,
55 case Comparators.DIFFERENCE_TO_ZERO_IS_BETTER:
56 Double.POSITIVE_INFINITY
57 case Comparators.HIGHER_IS_BETTER:
58 Double.NEGATIVE_INFINITY
59 default:
60 throw new IllegalArgumentException("Unknown comparator for non-three-valued objective: " +
61 objective.name)
62 }
63 }
64 ]
65 }
66}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/InconsistentScopeGlobalConstraint.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/InconsistentScopeGlobalConstraint.xtend
new file mode 100644
index 00000000..2e039ca2
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/InconsistentScopeGlobalConstraint.xtend
@@ -0,0 +1,25 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse
2
3import org.eclipse.viatra.dse.objectives.IGlobalConstraint
4import org.eclipse.viatra.dse.base.ThreadContext
5import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
6
7class InconsistentScopeGlobalConstraint implements IGlobalConstraint {
8
9 override init(ThreadContext context) {
10 // Nothing to initialize.
11 }
12
13 override createNew() {
14 this
15 }
16
17 override getName() {
18 class.name
19 }
20
21 override checkGlobalConstraint(ThreadContext context) {
22 val partialModel = context.model as PartialInterpretation
23 partialModel.minNewElements <= partialModel.maxNewElements || partialModel.maxNewElements < 0
24 }
25}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/LoggerSolutionFoundHandler.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/LoggerSolutionFoundHandler.xtend
new file mode 100644
index 00000000..39ef5f9a
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/LoggerSolutionFoundHandler.xtend
@@ -0,0 +1,24 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse
2
3import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration
4import org.apache.log4j.Logger
5import org.eclipse.viatra.dse.api.SolutionTrajectory
6import org.eclipse.viatra.dse.base.ThreadContext
7import org.eclipse.viatra.dse.solutionstore.ISolutionFoundHandler
8import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor
9
10@FinalFieldsConstructor
11class LoggerSolutionFoundHandler implements ISolutionFoundHandler {
12 val ViatraReasonerConfiguration configuration
13
14 val logger = Logger.getLogger(SolutionCopier)
15
16 override solutionFound(ThreadContext context, SolutionTrajectory trajectory) {
17 configuration.progressMonitor.workedModelFound(configuration.solutionScope.numberOfRequiredSolutions)
18 logger.debug("Found a solution.")
19 }
20
21 override solutionTriedToSave(ThreadContext context, SolutionTrajectory trajectory) {
22 // We are not interested in invalid solutions, ignore.
23 }
24}
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 a10530c7..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,34 +1,20 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse 1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse
2 2
3import com.google.common.collect.ImmutableList
4import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
5import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration
6import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.IThreeValuedObjective
3import java.util.Comparator 7import java.util.Comparator
4import java.util.List 8import java.util.List
5import org.eclipse.viatra.dse.base.ThreadContext 9import org.eclipse.viatra.dse.base.ThreadContext
6import org.eclipse.viatra.dse.objectives.Comparators 10import org.eclipse.viatra.dse.objectives.Comparators
7import org.eclipse.viatra.dse.objectives.IObjective 11import org.eclipse.viatra.dse.objectives.IObjective
8import org.eclipse.viatra.dse.objectives.impl.BaseObjective
9import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
10import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration
11 12
12//class ViatraReasonerNumbers { 13class ModelGenerationCompositeObjective implements IThreeValuedObjective {
13// public static val scopePriority = 2 14 val IObjective scopeObjective
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
27class ModelGenerationCompositeObjective implements IObjective{
28 val ScopeObjective scopeObjective
29 val List<UnfinishedMultiplicityObjective> unfinishedMultiplicityObjectives 15 val List<UnfinishedMultiplicityObjective> unfinishedMultiplicityObjectives
30 val UnfinishedWFObjective unfinishedWFObjective 16 val UnfinishedWFObjective unfinishedWFObjective
31 var PartialInterpretation model=null; 17 var PartialInterpretation model = null
32 val boolean punishSize 18 val boolean punishSize
33 val int scopeWeight 19 val int scopeWeight
34 val int conaintmentWeight 20 val int conaintmentWeight
@@ -36,23 +22,20 @@ class ModelGenerationCompositeObjective implements IObjective{
36 val int unfinishedWFWeight 22 val int unfinishedWFWeight
37 23
38 new( 24 new(
39 ScopeObjective scopeObjective, 25 IObjective scopeObjective,
40 List<UnfinishedMultiplicityObjective> unfinishedMultiplicityObjectives, 26 List<UnfinishedMultiplicityObjective> unfinishedMultiplicityObjectives,
41 UnfinishedWFObjective unfinishedWFObjective, 27 UnfinishedWFObjective unfinishedWFObjective,
42 ViatraReasonerConfiguration configuration) 28 ViatraReasonerConfiguration configuration)
43 { 29 {
44 this.scopeObjective = scopeObjective 30 this(
45 this.unfinishedMultiplicityObjectives = unfinishedMultiplicityObjectives 31 scopeObjective, unfinishedMultiplicityObjectives, unfinishedWFObjective, configuration.punishSize,
46 this.unfinishedWFObjective = unfinishedWFObjective 32 configuration.scopeWeight, configuration.conaintmentWeight, configuration.nonContainmentWeight,
47 33 configuration.unfinishedWFWeight
48 this.punishSize = configuration.punishSize 34 )
49 this.scopeWeight = configuration.scopeWeight
50 this.conaintmentWeight = configuration.conaintmentWeight
51 this.nonContainmentWeight = configuration.nonContainmentWeight
52 this.unfinishedWFWeight = configuration.unfinishedWFWeight
53 } 35 }
36
54 new( 37 new(
55 ScopeObjective scopeObjective, 38 IObjective scopeObjective,
56 List<UnfinishedMultiplicityObjective> unfinishedMultiplicityObjectives, 39 List<UnfinishedMultiplicityObjective> unfinishedMultiplicityObjectives,
57 UnfinishedWFObjective unfinishedWFObjective, 40 UnfinishedWFObjective unfinishedWFObjective,
58 boolean punishSize, int scopeWeight, int conaintmentWeight, int nonContainmentWeight, int unfinishedWFWeight) 41 boolean punishSize, int scopeWeight, int conaintmentWeight, int nonContainmentWeight, int unfinishedWFWeight)
@@ -74,18 +57,21 @@ class ModelGenerationCompositeObjective implements IObjective{
74 this.unfinishedMultiplicityObjectives.forEach[it.init(context)] 57 this.unfinishedMultiplicityObjectives.forEach[it.init(context)]
75 this.unfinishedWFObjective.init(context) 58 this.unfinishedWFObjective.init(context)
76 } 59 }
77 60
78 override createNew() { 61 override createNew() {
79 return new ModelGenerationCompositeObjective( 62 return new ModelGenerationCompositeObjective(
80 this.scopeObjective, this.unfinishedMultiplicityObjectives, this.unfinishedWFObjective, 63 scopeObjective.createNew,
81 this.punishSize, this.scopeWeight, this.conaintmentWeight, this.nonContainmentWeight, this.unfinishedWFWeight) 64 ImmutableList.copyOf(unfinishedMultiplicityObjectives.map[createNew as UnfinishedMultiplicityObjective]),
65 unfinishedWFObjective.createNew as UnfinishedWFObjective,
66 punishSize, scopeWeight, conaintmentWeight, nonContainmentWeight, unfinishedWFWeight
67 )
82 } 68 }
83 69
84 override getComparator() { Comparators.LOWER_IS_BETTER } 70 override getComparator() { Comparators.LOWER_IS_BETTER }
71
85 override getFitness(ThreadContext context) { 72 override getFitness(ThreadContext context) {
86 73
87 val scopeFitnes = scopeObjective.getFitness(context) 74 val scopeFitnes = scopeObjective.getFitness(context)
88 //val unfinishedMultiplicitiesFitneses = unfinishedMultiplicityObjectives.map[x|x.getFitness(context)]
89 val unfinishedWFsFitness = unfinishedWFObjective.getFitness(context) 75 val unfinishedWFsFitness = unfinishedWFObjective.getFitness(context)
90 76
91 var containmentMultiplicity = 0.0 77 var containmentMultiplicity = 0.0
@@ -109,24 +95,30 @@ class ModelGenerationCompositeObjective implements IObjective{
109 sum += nonContainmentMultiplicity*nonContainmentWeight 95 sum += nonContainmentMultiplicity*nonContainmentWeight
110 sum += unfinishedWFsFitness*unfinishedWFWeight 96 sum += unfinishedWFsFitness*unfinishedWFWeight
111 sum+=size 97 sum+=size
112
113 //println('''Sum=«sum»|Scope=«scopeFitnes»|ContainmentMultiplicity=«containmentMultiplicity»|NonContainmentMultiplicity=«nonContainmentMultiplicity»|WFs=«unfinishedWFsFitness»''')
114
115 return sum 98 return sum
116 } 99 }
117 100
118 override getLevel() { 2 } 101 override getWorstPossibleFitness(ThreadContext threadContext) {
119 override getName() { "CompositeUnfinishednessObjective"} 102 Double.POSITIVE_INFINITY
103 }
120 104
105 override getBestPossibleFitness(ThreadContext threadContext) {
106 0.0
107 }
108
109 override getLevel() { 2 }
110
111 override getName() { "CompositeUnfinishednessObjective" }
112
121 override isHardObjective() { true } 113 override isHardObjective() { true }
122 override satisifiesHardObjective(Double fitness) { fitness < 0.95 } 114
123 115 override satisifiesHardObjective(Double fitness) { fitness <= 0.001 }
124 116
125 override setComparator(Comparator<Double> comparator) { 117 override setComparator(Comparator<Double> comparator) {
126 throw new UnsupportedOperationException("TODO: auto-generated method stub") 118 throw new UnsupportedOperationException("Model generation objective comparator cannot be set.")
127 } 119 }
120
128 override setLevel(int level) { 121 override setLevel(int level) {
129 throw new UnsupportedOperationException("TODO: auto-generated method stub") 122 throw new UnsupportedOperationException("Model generation objective level cannot be set.")
130 } 123 }
131 124}
132} \ 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/NumericSolver.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/NumericSolver.xtend
index 0b0feb1a..066040a0 100644
--- 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
@@ -21,7 +21,8 @@ import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher
21import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint 21import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint
22 22
23class NumericSolver { 23class NumericSolver {
24 val ThreadContext threadContext; 24 val ModelGenerationMethod method
25 var ThreadContext threadContext
25 val constraint2MustUnitPropagationPrecondition = new HashMap<PConstraint,ViatraQueryMatcher<? extends IPatternMatch>> 26 val constraint2MustUnitPropagationPrecondition = new HashMap<PConstraint,ViatraQueryMatcher<? extends IPatternMatch>>
26 val constraint2CurrentUnitPropagationPrecondition = new HashMap<PConstraint,ViatraQueryMatcher<? extends IPatternMatch>> 27 val constraint2CurrentUnitPropagationPrecondition = new HashMap<PConstraint,ViatraQueryMatcher<? extends IPatternMatch>>
27 NumericTranslator t = new NumericTranslator 28 NumericTranslator t = new NumericTranslator
@@ -35,8 +36,16 @@ class NumericSolver {
35 var int numberOfSolverCalls = 0 36 var int numberOfSolverCalls = 0
36 var int numberOfCachedSolverCalls = 0 37 var int numberOfCachedSolverCalls = 0
37 38
38 new(ThreadContext threadContext, ModelGenerationMethod method, boolean intermediateConsistencyCheck, boolean caching) { 39 new(ModelGenerationMethod method, boolean intermediateConsistencyCheck, boolean caching) {
39 this.threadContext = threadContext 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
40 val engine = threadContext.queryEngine 49 val engine = threadContext.queryEngine
41 for(entry : method.mustUnitPropagationPreconditions.entrySet) { 50 for(entry : method.mustUnitPropagationPreconditions.entrySet) {
42 val constraint = entry.key 51 val constraint = entry.key
@@ -50,8 +59,6 @@ class NumericSolver {
50 val matcher = querySpec.getMatcher(engine); 59 val matcher = querySpec.getMatcher(engine);
51 constraint2CurrentUnitPropagationPrecondition.put(constraint,matcher) 60 constraint2CurrentUnitPropagationPrecondition.put(constraint,matcher)
52 } 61 }
53 this.intermediateConsistencyCheck = intermediateConsistencyCheck
54 this.caching = caching
55 } 62 }
56 63
57 def getRuntime(){runtime} 64 def getRuntime(){runtime}
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 efc2ef36..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
@@ -219,4 +219,4 @@ class PartialModelAsLogicInterpretation implements LogicModelInterpretation{
219 } 219 }
220 builder 220 builder
221 } 221 }
222} \ No newline at end of file 222}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ScopeObjective.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ScopeObjective.xtend
index 69efe0d7..69a734f8 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ScopeObjective.xtend
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ScopeObjective.xtend
@@ -23,9 +23,9 @@ class ScopeObjective implements IObjective{
23 23
24 override getFitness(ThreadContext context) { 24 override getFitness(ThreadContext context) {
25 val interpretation = context.model as PartialInterpretation 25 val interpretation = context.model as PartialInterpretation
26 var res = interpretation.minNewElements.doubleValue 26 var res = interpretation.minNewElementsHeuristic.doubleValue
27 for(scope : interpretation.scopes) { 27 for(scope : interpretation.scopes) {
28 res += scope.minNewElements*2 28 res += scope.minNewElementsHeuristic*2
29 } 29 }
30 return res 30 return res
31 } 31 }
@@ -41,4 +41,4 @@ class ScopeObjective implements IObjective{
41 throw new UnsupportedOperationException("TODO: auto-generated method stub") 41 throw new UnsupportedOperationException("TODO: auto-generated method stub")
42 } 42 }
43 override getLevel() { 2 } 43 override getLevel() { 2 }
44} \ No newline at end of file 44}
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
new file mode 100644
index 00000000..38c8f5a1
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionCopier.xtend
@@ -0,0 +1,86 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse
2
3import com.google.common.collect.ImmutableList
4import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
5import java.util.LinkedHashMap
6import java.util.List
7import java.util.Map
8import org.eclipse.emf.ecore.EObject
9import org.eclipse.emf.ecore.util.EcoreUtil
10import org.eclipse.viatra.dse.base.ThreadContext
11import org.eclipse.xtend.lib.annotations.Accessors
12import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor
13
14@FinalFieldsConstructor
15class CopiedSolution {
16 @Accessors val PartialInterpretation partialInterpretations
17 @Accessors val Map<EObject, EObject> trace
18 @Accessors val long copierRuntime
19 @Accessors var boolean current = true
20}
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 */
28class SolutionCopier {
29 val NumericSolver numericSolver
30 val copiedSolutions = new LinkedHashMap<Object, CopiedSolution>
31
32 long startTime = System.nanoTime
33 @Accessors(PUBLIC_GETTER) long totalCopierRuntime = 0
34
35 new(NumericSolver numericSolver) {
36 this.numericSolver = numericSolver
37 }
38
39 def void copySolution(ThreadContext context, Object solutionId) {
40 val existingCopy = copiedSolutions.get(solutionId)
41 if (existingCopy === null) {
42 val copyStart = System.nanoTime
43 val solution = context.model as PartialInterpretation
44 val copier = new EcoreUtil.Copier
45 val copiedPartialInterpretation = copier.copy(solution) as PartialInterpretation
46 copier.copyReferences
47 totalCopierRuntime += System.nanoTime - copyStart
48 val copierRuntime = System.nanoTime - startTime
49 val copiedSolution = new CopiedSolution(copiedPartialInterpretation, copier, copierRuntime)
50 numericSolver.fillSolutionCopy(copiedSolution.trace)
51 copiedSolutions.put(solutionId, copiedSolution)
52 } else {
53 existingCopy.current = true
54 }
55 }
56
57 def void markAsObsolete(Object solutionId) {
58 val copiedSolution = copiedSolutions.get(solutionId)
59 if (copiedSolution === null) {
60 throw new IllegalStateException("No solution to mark as obsolete for state code: " + solutionId)
61 }
62 copiedSolution.current = false
63 }
64
65 def List<PartialInterpretation> getPartialInterpretations(boolean currentOnly) {
66 getListOfCopiedSolutions(currentOnly).map[partialInterpretations]
67 }
68
69 def List<Map<EObject, EObject>> getTraces(boolean currentOnly) {
70 getListOfCopiedSolutions(currentOnly).map[trace]
71 }
72
73 def List<Long> getAllCopierRuntimes(boolean currentOnly) {
74 getListOfCopiedSolutions(currentOnly).map[copierRuntime]
75 }
76
77 def List<CopiedSolution> getListOfCopiedSolutions(boolean currentOnly) {
78 val values = copiedSolutions.values
79 val filteredSolutions = if (currentOnly) {
80 values.filter[current]
81 } else {
82 values
83 }
84 ImmutableList.copyOf(filteredSolutions)
85 }
86}
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
index 21867a4e..4bd2c349 100644
--- 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
@@ -1,14 +1,12 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse 1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse
2 2
3import java.util.List
4import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation 3import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
5import java.util.LinkedList 4import java.util.LinkedList
6import org.eclipse.emf.ecore.EObject 5import java.util.List
7import java.util.Map 6import java.util.Map
7import org.eclipse.emf.ecore.EObject
8import org.eclipse.emf.ecore.util.EcoreUtil 8import org.eclipse.emf.ecore.util.EcoreUtil
9import org.eclipse.viatra.dse.base.ThreadContext 9import org.eclipse.viatra.dse.base.ThreadContext
10import java.util.TreeMap
11import java.util.SortedMap
12 10
13class SolutionStoreWithCopy { 11class SolutionStoreWithCopy {
14 12
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionStoreWithDiversityDescriptor.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionStoreWithDiversityDescriptor.xtend
deleted file mode 100644
index 1e7f18a8..00000000
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionStoreWithDiversityDescriptor.xtend
+++ /dev/null
@@ -1,120 +0,0 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse
2
3import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.neighbourhood.PartialInterpretation2ImmutableTypeLattice
4import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
5import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.DiversityDescriptor
6import java.util.LinkedList
7import java.util.List
8import org.eclipse.viatra.dse.base.ThreadContext
9import java.util.HashSet
10import java.util.Set
11
12enum DiversityGranularity {
13 Nodewise, Graphwise
14}
15
16class SolutionStoreWithDiversityDescriptor {
17 val DiversityDescriptor descriptor
18 DiversityGranularity granularity
19 val PartialInterpretation2ImmutableTypeLattice solutionCoder = new PartialInterpretation2ImmutableTypeLattice
20 val Set<Integer> solutionCodeList = new HashSet
21
22 var long runtime
23 var int allCheck
24 var int successfulCheck
25
26 new(DiversityDescriptor descriptor) {
27 if(descriptor.ensureDiversity) {
28 this.descriptor = descriptor
29 this.granularity = DiversityGranularity::Nodewise
30 } else {
31 this.descriptor = null
32 this.granularity = DiversityGranularity::Nodewise
33 }
34 }
35
36 def public isActive() {
37 descriptor!==null
38 }
39
40 def getSumRuntime() {
41 return runtime
42 }
43 def getSuccessRate() {
44 return successfulCheck as double / allCheck
45 }
46
47 def isDifferent(ThreadContext context) {
48 if(active) {
49 val start = System.nanoTime
50 val model = context.model as PartialInterpretation
51 var boolean isDifferent
52 if(this.granularity == DiversityGranularity::Graphwise) {
53 val code = solutionCoder.createRepresentation(model,
54 descriptor.range,
55 descriptor.parallels,
56 descriptor.maxNumber,
57 descriptor.relevantTypes,
58 descriptor.relevantRelations).modelRepresentation.hashCode
59
60 isDifferent = !solutionCodeList.contains(code)
61 } else if(this.granularity == DiversityGranularity::Nodewise){
62 val codes = solutionCoder.createRepresentation(model,
63 descriptor.range,
64 descriptor.parallels,
65 descriptor.maxNumber,
66 descriptor.relevantTypes,
67 descriptor.relevantRelations).modelRepresentation.keySet.map[hashCode].toList
68 val differentCodes = codes.filter[!solutionCodeList.contains(it)]
69 //println(differentCodes.size)
70
71 isDifferent = differentCodes.size>=1
72 } else {
73 throw new UnsupportedOperationException('''Unsupported diversity type: «this.granularity»''')
74 }
75
76 runtime += System.nanoTime - start
77 allCheck++
78 if(isDifferent) { successfulCheck++ }
79 return isDifferent
80 } else {
81 allCheck++
82 successfulCheck++
83 return true
84 }
85 }
86
87 def canBeDifferent(ThreadContext context) {
88 return true
89 }
90
91 def newSolution(ThreadContext context) {
92 if(active) {
93 val start = System.nanoTime
94 val model = context.model as PartialInterpretation
95 if(this.granularity == DiversityGranularity::Graphwise) {
96 val code = solutionCoder.createRepresentation(model,
97 descriptor.range,
98 descriptor.parallels,
99 descriptor.maxNumber,
100 descriptor.relevantTypes,
101 descriptor.relevantRelations).modelRepresentation.hashCode
102
103 solutionCodeList += code.hashCode
104 } else if(this.granularity == DiversityGranularity::Nodewise){
105 val codes = solutionCoder.createRepresentation(model,
106 descriptor.range,
107 descriptor.parallels,
108 descriptor.maxNumber,
109 descriptor.relevantTypes,
110 descriptor.relevantRelations).modelRepresentation.keySet.map[hashCode].toList
111
112 solutionCodeList += codes.map[it.hashCode]
113 } else {
114 throw new UnsupportedOperationException('''Unsupported diversity type: «this.granularity»''')
115 }
116
117 runtime += System.nanoTime - start
118 }
119 }
120} \ 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/SurelyViolatedObjectiveGlobalConstraint.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SurelyViolatedObjectiveGlobalConstraint.xtend
new file mode 100644
index 00000000..8ed3e912
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SurelyViolatedObjectiveGlobalConstraint.xtend
@@ -0,0 +1,27 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse
2
3import org.eclipse.viatra.dse.base.ThreadContext
4import org.eclipse.viatra.dse.objectives.IGlobalConstraint
5import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor
6
7@FinalFieldsConstructor
8class SurelyViolatedObjectiveGlobalConstraint implements IGlobalConstraint {
9 val ViatraReasonerSolutionSaver solutionSaver
10
11 override init(ThreadContext context) {
12 // Nothing to initialize.
13 }
14
15 override createNew() {
16 this
17 }
18
19 override getName() {
20 class.name
21 }
22
23 override checkGlobalConstraint(ThreadContext context) {
24 val bestFitness = DseUtils.caclulateBestPossibleFitness(context)
25 bestFitness.satisifiesHardObjectives && solutionSaver.fitnessMayBeSaved(bestFitness)
26 }
27}
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 2b0807d6..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
@@ -1,15 +1,15 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse 1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse
2 2
3import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.MultiplicityGoalConstraintCalculator 3import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.MultiplicityGoalConstraintCalculator
4import java.util.Comparator 4import java.util.Comparator
5import org.eclipse.viatra.dse.base.ThreadContext 5import org.eclipse.viatra.dse.base.ThreadContext
6import org.eclipse.viatra.dse.objectives.IObjective
7import org.eclipse.viatra.dse.objectives.Comparators 6import org.eclipse.viatra.dse.objectives.Comparators
7import org.eclipse.viatra.dse.objectives.IObjective
8 8
9class UnfinishedMultiplicityObjective implements IObjective { 9class UnfinishedMultiplicityObjective implements IObjective {
10 val MultiplicityGoalConstraintCalculator unfinishedMultiplicity; 10 val MultiplicityGoalConstraintCalculator unfinishedMultiplicity
11 11
12 public new(MultiplicityGoalConstraintCalculator unfinishedMultiplicity) { 12 new(MultiplicityGoalConstraintCalculator unfinishedMultiplicity) {
13 this.unfinishedMultiplicity = unfinishedMultiplicity 13 this.unfinishedMultiplicity = unfinishedMultiplicity
14 } 14 }
15 15
@@ -29,12 +29,13 @@ class UnfinishedMultiplicityObjective implements IObjective {
29 override satisifiesHardObjective(Double fitness) { return fitness <=0.01 } 29 override satisifiesHardObjective(Double fitness) { return fitness <=0.01 }
30 30
31 override setComparator(Comparator<Double> comparator) { 31 override setComparator(Comparator<Double> comparator) {
32 throw new UnsupportedOperationException("TODO: auto-generated method stub") 32 throw new UnsupportedOperationException
33 } 33 }
34 override setLevel(int level) { 34 override setLevel(int level) {
35 throw new UnsupportedOperationException("TODO: auto-generated method stub") 35 throw new UnsupportedOperationException
36 } 36 }
37
37 def isContainment() { 38 def isContainment() {
38 return this.unfinishedMultiplicity.containment 39 return this.unfinishedMultiplicity.containment
39 } 40 }
40} \ No newline at end of file 41}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/UnfinishedWFObjective.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/UnfinishedWFObjective.xtend
index e0111cf6..1b61ffa5 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/UnfinishedWFObjective.xtend
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/UnfinishedWFObjective.xtend
@@ -1,56 +1,64 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse 1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse
2 2
3import org.eclipse.viatra.dse.objectives.IObjective 3import java.util.ArrayList
4import org.eclipse.viatra.query.runtime.api.IPatternMatch
5import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher
6import org.eclipse.viatra.query.runtime.api.IQuerySpecification
7import java.util.Collection 4import java.util.Collection
8import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine 5import java.util.Comparator
9import org.eclipse.viatra.query.runtime.emf.EMFScope
10import org.eclipse.viatra.dse.base.ThreadContext
11import java.util.List 6import java.util.List
7import org.eclipse.viatra.dse.base.ThreadContext
12import org.eclipse.viatra.dse.objectives.Comparators 8import org.eclipse.viatra.dse.objectives.Comparators
13import java.util.ArrayList 9import org.eclipse.viatra.dse.objectives.IObjective
14import java.util.Comparator 10import org.eclipse.viatra.query.runtime.api.IPatternMatch
11import org.eclipse.viatra.query.runtime.api.IQuerySpecification
12import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher
15 13
16class UnfinishedWFObjective implements IObjective { 14class UnfinishedWFObjective implements IObjective {
17 Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedWFs 15 Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedWFs
18 val List<ViatraQueryMatcher<?>> matchers 16 val List<ViatraQueryMatcher<?>> matchers
19 17
20 public new(Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedWFs) { 18 new(
19 Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedWFs) {
21 this.unfinishedWFs = unfinishedWFs 20 this.unfinishedWFs = unfinishedWFs
22 matchers = new ArrayList(unfinishedWFs.size) 21 matchers = new ArrayList(unfinishedWFs.size)
23 } 22 }
23
24 override getName() '''unfinishedWFs''' 24 override getName() '''unfinishedWFs'''
25
25 override createNew() { 26 override createNew() {
26 return new UnfinishedWFObjective(unfinishedWFs) 27 return new UnfinishedWFObjective(unfinishedWFs)
27 } 28 }
29
28 override init(ThreadContext context) { 30 override init(ThreadContext context) {
29 val engine = context.queryEngine//ViatraQueryEngine.on(new EMFScope(context.model)) 31 val engine = context.queryEngine // ViatraQueryEngine.on(new EMFScope(context.model))
30 for(unfinishedWF : unfinishedWFs) { 32 for (unfinishedWF : unfinishedWFs) {
31 matchers += unfinishedWF.getMatcher(engine) 33 matchers += unfinishedWF.getMatcher(engine)
32 } 34 }
33 } 35 }
34 36
35 override getComparator() { Comparators.LOWER_IS_BETTER } 37 override getComparator() { Comparators.LOWER_IS_BETTER }
38
36 override getFitness(ThreadContext context) { 39 override getFitness(ThreadContext context) {
37 var sumOfMatches = 0 40 var sumOfMatches = 0
38 for(matcher : matchers) { 41 for (matcher : matchers) {
39 val number = matcher.countMatches 42 val number = matcher.countMatches
40 //println('''«matcher.patternName» = «number»''') 43// if (number > 0) {
41 sumOfMatches+=number 44// println('''«matcher.patternName» = «number»''')
45// }
46 sumOfMatches += number
42 } 47 }
43 return sumOfMatches.doubleValue 48 return sumOfMatches.doubleValue
44 } 49 }
45 50
46 override getLevel() { 2 } 51 override getLevel() { 2 }
52
47 override isHardObjective() { true } 53 override isHardObjective() { true }
48 override satisifiesHardObjective(Double fitness) { return fitness <=0.01 } 54
49 55 override satisifiesHardObjective(Double fitness) { return fitness <= 0.01 }
56
50 override setComparator(Comparator<Double> comparator) { 57 override setComparator(Comparator<Double> comparator) {
51 throw new UnsupportedOperationException("TODO: auto-generated method stub") 58 throw new UnsupportedOperationException()
52 } 59 }
60
53 override setLevel(int level) { 61 override setLevel(int level) {
54 throw new UnsupportedOperationException("TODO: auto-generated method stub") 62 throw new UnsupportedOperationException()
55 } 63 }
56} \ No newline at end of file 64}
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
new file mode 100644
index 00000000..d879d4cc
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend
@@ -0,0 +1,150 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse
2
3import java.util.HashMap
4import java.util.Map
5import org.eclipse.viatra.dse.api.DSEException
6import org.eclipse.viatra.dse.api.Solution
7import org.eclipse.viatra.dse.api.SolutionTrajectory
8import org.eclipse.viatra.dse.base.ThreadContext
9import org.eclipse.viatra.dse.objectives.Fitness
10import org.eclipse.viatra.dse.objectives.IObjective
11import org.eclipse.viatra.dse.objectives.ObjectiveComparatorHelper
12import org.eclipse.viatra.dse.solutionstore.SolutionStore.ISolutionSaver
13import org.eclipse.xtend.lib.annotations.Accessors
14
15/**
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}.
20 */
21class ViatraReasonerSolutionSaver implements ISolutionSaver {
22 @Accessors val SolutionCopier solutionCopier
23 @Accessors val DiversityChecker diversityChecker
24 val boolean hasExtremalObjectives
25 val int numberOfRequiredSolutions
26 val ObjectiveComparatorHelper comparatorHelper
27 val Map<SolutionTrajectory, Fitness> trajectories = new HashMap
28
29 @Accessors(PUBLIC_SETTER) var Map<Object, Solution> solutionsCollection
30
31 new(IObjective[][] leveledExtremalObjectives, int numberOfRequiredSolutions, DiversityChecker diversityChecker, NumericSolver numericSolver) {
32 this.diversityChecker = diversityChecker
33 comparatorHelper = new ObjectiveComparatorHelper(leveledExtremalObjectives)
34 hasExtremalObjectives = leveledExtremalObjectives.exists[!empty]
35 this.numberOfRequiredSolutions = numberOfRequiredSolutions
36 this.solutionCopier = new SolutionCopier(numericSolver)
37 }
38
39 override saveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) {
40 if (hasExtremalObjectives) {
41 saveBestSolutionOnly(context, id, solutionTrajectory)
42 } else {
43 saveAnyDiverseSolution(context, id, solutionTrajectory)
44 }
45 }
46
47 private def saveBestSolutionOnly(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) {
48 val fitness = context.lastFitness
49 if (!shouldSaveSolution(fitness, context)) {
50 return false
51 }
52 val dominatedTrajectories = newArrayList
53 for (entry : trajectories.entrySet) {
54 val isLastFitnessBetter = comparatorHelper.compare(fitness, entry.value)
55 if (isLastFitnessBetter < 0) {
56 // Found a trajectory that dominates the current one, no need to save
57 return false
58 }
59 if (isLastFitnessBetter > 0) {
60 dominatedTrajectories += entry.key
61 }
62 }
63 if (dominatedTrajectories.size == 0 && !needsMoreSolutionsWithSameFitness) {
64 return false
65 }
66 if (!diversityChecker.newSolution(context, id, dominatedTrajectories.map[solution.stateCode])) {
67 return false
68 }
69 // We must save the new trajectory before removing dominated trajectories
70 // to avoid removing the current solution when it is reachable only via dominated trajectories.
71 val solutionSaved = basicSaveSolution(context, id, solutionTrajectory, fitness)
72 for (dominatedTrajectory : dominatedTrajectories) {
73 trajectories -= dominatedTrajectory
74 val dominatedSolution = dominatedTrajectory.solution
75 if (!dominatedSolution.trajectories.remove(dominatedTrajectory)) {
76 throw new DSEException(
77 "Dominated solution is not reachable from dominated trajectory. This should never happen!")
78 }
79 if (dominatedSolution.trajectories.empty) {
80 val dominatedSolutionId = dominatedSolution.stateCode
81 solutionCopier.markAsObsolete(dominatedSolutionId)
82 solutionsCollection -= dominatedSolutionId
83 }
84 }
85 solutionSaved
86 }
87
88 private def saveAnyDiverseSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) {
89 val fitness = context.lastFitness
90 if (!shouldSaveSolution(fitness, context)) {
91 return false
92 }
93 if (!diversityChecker.newSolution(context, id, emptyList)) {
94 return false
95 }
96 basicSaveSolution(context, id, solutionTrajectory, fitness)
97 }
98
99 private def shouldSaveSolution(Fitness fitness, ThreadContext context) {
100 return fitness.satisifiesHardObjectives
101 }
102
103 private def basicSaveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory,
104 Fitness fitness) {
105 var boolean solutionSaved = false
106 var dseSolution = solutionsCollection.get(id)
107 if (dseSolution === null) {
108 solutionCopier.copySolution(context, id)
109 dseSolution = new Solution(id, solutionTrajectory)
110 solutionsCollection.put(id, dseSolution)
111 solutionSaved = true
112 } else {
113 solutionSaved = dseSolution.trajectories.add(solutionTrajectory)
114 }
115 if (solutionSaved) {
116 solutionTrajectory.solution = dseSolution
117 trajectories.put(solutionTrajectory, fitness)
118 }
119 solutionSaved
120 }
121
122 def fitnessMayBeSaved(Fitness fitness) {
123 if (!hasExtremalObjectives) {
124 return true
125 }
126 var boolean mayDominate
127 for (existingFitness : trajectories.values) {
128 val isNewFitnessBetter = comparatorHelper.compare(fitness, existingFitness)
129 if (isNewFitnessBetter < 0) {
130 return false
131 }
132 if (isNewFitnessBetter > 0) {
133 mayDominate = true
134 }
135 }
136 mayDominate || needsMoreSolutionsWithSameFitness
137 }
138
139 private def boolean needsMoreSolutionsWithSameFitness() {
140 if (solutionsCollection === null) {
141 // The solutions collection will only be initialized upon saving the first solution.
142 return true
143 }
144 solutionsCollection.size < numberOfRequiredSolutions
145 }
146
147 def getTotalCopierRuntime() {
148 solutionCopier.totalCopierRuntime
149 }
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 5a528a9e..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
@@ -1,5 +1,6 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse 1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse
2 2
3import com.google.common.collect.ImmutableList
3import java.util.ArrayList 4import java.util.ArrayList
4import java.util.Collection 5import java.util.Collection
5import org.eclipse.viatra.dse.objectives.Comparators 6import org.eclipse.viatra.dse.objectives.Comparators
@@ -12,25 +13,33 @@ import org.eclipse.viatra.query.runtime.api.IQuerySpecification
12import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher 13import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher
13 14
14class WF2ObjectiveConverter { 15class WF2ObjectiveConverter {
15 16 static val INVALIDATED_WFS_NAME = "invalidatedWFs"
17
16 def createCompletenessObjective( 18 def createCompletenessObjective(
17 Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedWF) 19 Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedWF) {
18 { 20 new UnfinishedWFObjective(unfinishedWF)
19 val res = new ConstraintsObjective('''unfinishedWFs''', 21 }
20 unfinishedWF.map[ 22
21 new QueryConstraint(it.fullyQualifiedName,it,2.0) 23 def createInvalidationObjective(
22 ].toList 24 Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> invalidatedByWF) {
25 createConstraintObjective(INVALIDATED_WFS_NAME, invalidatedByWF)
26 }
27
28 def IGlobalConstraint createInvalidationGlobalConstraint(
29 Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> invalidatedByWF) {
30 new ModelQueriesGlobalConstraint(INVALIDATED_WFS_NAME, new ArrayList(invalidatedByWF))
31 }
32
33 private def createConstraintObjective(String name,
34 Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> queries) {
35 val res = new ConstraintsObjective(
36 name,
37 ImmutableList.copyOf(queries.map [
38 new QueryConstraint(it.fullyQualifiedName, it, 1.0)
39 ])
23 ) 40 )
24 res.withComparator(Comparators.LOWER_IS_BETTER) 41 res.withComparator(Comparators.LOWER_IS_BETTER)
25 res.level = 2 42 res.level = 2
26 return res 43 res
27 }
28
29 def IGlobalConstraint createInvalidationObjective(
30 Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> invalidatedByWF)
31 {
32 return new ModelQueriesGlobalConstraint('''invalidatedWFs''',
33 new ArrayList(invalidatedByWF)
34 )
35 } 44 }
36} \ No newline at end of file 45}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/AbstractThreeValuedObjective.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/AbstractThreeValuedObjective.xtend
new file mode 100644
index 00000000..cd911ab5
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/AbstractThreeValuedObjective.xtend
@@ -0,0 +1,35 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization
2
3import org.eclipse.viatra.dse.base.ThreadContext
4
5abstract class AbstractThreeValuedObjective extends DirectionalThresholdObjective implements IThreeValuedObjective {
6 protected new(String name, ObjectiveKind kind, ObjectiveThreshold threshold, int level) {
7 super(name, kind, threshold, level)
8 }
9
10 abstract def double getLowestPossibleFitness(ThreadContext threadContext)
11
12 abstract def double getHighestPossibleFitness(ThreadContext threadContext)
13
14 override getWorstPossibleFitness(ThreadContext threadContext) {
15 switch (kind) {
16 case LOWER_IS_BETTER:
17 getHighestPossibleFitness(threadContext)
18 case HIGHER_IS_BETTER:
19 getLowestPossibleFitness(threadContext)
20 default:
21 throw new IllegalStateException("Unknown three valued objective kind: " + kind)
22 }
23 }
24
25 override getBestPossibleFitness(ThreadContext threadContext) {
26 switch (kind) {
27 case LOWER_IS_BETTER:
28 getLowestPossibleFitness(threadContext)
29 case HIGHER_IS_BETTER:
30 getHighestPossibleFitness(threadContext)
31 default:
32 throw new IllegalStateException("Unknown three valued objective kind: " + kind)
33 }
34 }
35}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/CompositeDirectionalThresholdObjective.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/CompositeDirectionalThresholdObjective.xtend
new file mode 100644
index 00000000..0aa442f5
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/CompositeDirectionalThresholdObjective.xtend
@@ -0,0 +1,62 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization
2
3import com.google.common.collect.ImmutableList
4import java.util.Collection
5import org.eclipse.viatra.dse.base.ThreadContext
6
7class CompositeDirectionalThresholdObjective extends DirectionalThresholdObjective {
8 val Collection<DirectionalThresholdObjective> objectives
9
10 new(String name, Collection<DirectionalThresholdObjective> objectives) {
11 this(name, objectives, getKind(objectives), getThreshold(objectives), getLevel(objectives))
12 }
13
14 new(String name, DirectionalThresholdObjective... objectives) {
15 this(name, objectives as Collection<DirectionalThresholdObjective>)
16 }
17
18 protected new(String name, Iterable<DirectionalThresholdObjective> objectives, ObjectiveKind kind,
19 ObjectiveThreshold threshold, int level) {
20 super(name, kind, threshold, level)
21 this.objectives = ImmutableList.copyOf(objectives)
22 }
23
24 override createNew() {
25 new CompositeDirectionalThresholdObjective(name, objectives.map[createNew as DirectionalThresholdObjective],
26 kind, threshold, level)
27 }
28
29 override init(ThreadContext context) {
30 for (objective : objectives) {
31 objective.init(context)
32 }
33 }
34
35 override protected getRawFitness(ThreadContext context) {
36 var double fitness = 0
37 for (objective : objectives) {
38 fitness += objective.getFitness(context)
39 }
40 fitness
41 }
42
43 private static def getKind(Collection<DirectionalThresholdObjective> objectives) {
44 val kinds = objectives.map[kind].toSet
45 if (kinds.size != 1) {
46 throw new IllegalArgumentException("Passed objectives must have the same kind")
47 }
48 kinds.head
49 }
50
51 private static def getThreshold(Collection<DirectionalThresholdObjective> objectives) {
52 objectives.map[threshold].reduce[a, b|a.merge(b)]
53 }
54
55 private static def int getLevel(Collection<DirectionalThresholdObjective> objectives) {
56 val levels = objectives.map[level].toSet
57 if (levels.size != 1) {
58 throw new IllegalArgumentException("Passed objectives must have the same level")
59 }
60 levels.head
61 }
62}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/DirectionalThresholdObjective.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/DirectionalThresholdObjective.xtend
new file mode 100644
index 00000000..376e3d1a
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/DirectionalThresholdObjective.xtend
@@ -0,0 +1,164 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization
2
3import java.util.Comparator
4import org.eclipse.viatra.dse.base.ThreadContext
5import org.eclipse.viatra.dse.objectives.IObjective
6import org.eclipse.xtend.lib.annotations.Accessors
7import org.eclipse.xtend.lib.annotations.Data
8import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor
9
10abstract class ObjectiveThreshold {
11 public static val NO_THRESHOLD = new ObjectiveThreshold {
12 override isHard() {
13 false
14 }
15
16 override satisfiesThreshold(double cost, Comparator<Double> comparator) {
17 true
18 }
19
20 override protected postProcessSatisfactoryCost(double cost, ObjectiveKind kind) {
21 cost
22 }
23
24 override ObjectiveThreshold merge(ObjectiveThreshold other) {
25 if (other == NO_THRESHOLD) {
26 NO_THRESHOLD
27 } else {
28 throw new IllegalArgumentException("Merged thresholds must have the same type")
29 }
30 }
31 }
32
33 private new() {
34 }
35
36 def boolean isHard() {
37 true
38 }
39
40 def boolean satisfiesThreshold(double cost, ObjectiveKind kind) {
41 satisfiesThreshold(cost, kind.comparator)
42 }
43
44 def boolean satisfiesThreshold(double cost, Comparator<Double> comparator)
45
46 def double postProcessCost(double cost, ObjectiveKind kind) {
47 if (satisfiesThreshold(cost, kind)) {
48 postProcessSatisfactoryCost(cost, kind)
49 } else {
50 cost
51 }
52 }
53
54 protected def double postProcessSatisfactoryCost(double cost, ObjectiveKind kind)
55
56 def ObjectiveThreshold merge(ObjectiveThreshold other)
57
58 @Data
59 static class Exclusive extends ObjectiveThreshold {
60 static val EPSILON = 0.1
61
62 val double threshold
63 val boolean clampToThreshold
64
65 @FinalFieldsConstructor
66 new() {
67 }
68
69 new(double threshold) {
70 this(threshold, true)
71 }
72
73 override satisfiesThreshold(double cost, Comparator<Double> comparator) {
74 comparator.compare(threshold, cost) < 0
75 }
76
77 override protected postProcessSatisfactoryCost(double cost, ObjectiveKind kind) {
78 if (clampToThreshold) {
79 threshold + Math.signum(kind.satisfiedValue) * EPSILON
80 } else {
81 cost
82 }
83 }
84
85 override ObjectiveThreshold merge(ObjectiveThreshold other) {
86 if (other instanceof Exclusive) {
87 new Exclusive(threshold + other.threshold)
88 } else {
89 throw new IllegalArgumentException("Merged thresholds must have the same type")
90 }
91 }
92 }
93
94 @Data
95 static class Inclusive extends ObjectiveThreshold {
96 val double threshold
97 val boolean clampToThreshold
98
99 @FinalFieldsConstructor
100 new() {
101 }
102
103 new(double threshold) {
104 this(threshold, true)
105 }
106
107 override satisfiesThreshold(double cost, Comparator<Double> comparator) {
108 comparator.compare(threshold, cost) <= 0
109 }
110
111 override protected postProcessSatisfactoryCost(double cost, ObjectiveKind kind) {
112 if (clampToThreshold) {
113 threshold
114 } else {
115 cost
116 }
117 }
118
119 override ObjectiveThreshold merge(ObjectiveThreshold other) {
120 if (other instanceof Inclusive) {
121 new Inclusive(threshold + other.threshold)
122 } else {
123 throw new IllegalArgumentException("Merged thresholds must have the same type")
124 }
125 }
126 }
127}
128
129abstract class DirectionalThresholdObjective implements IObjective {
130 @Accessors val String name
131 @Accessors ObjectiveKind kind
132 @Accessors ObjectiveThreshold threshold
133 @Accessors int level
134
135 protected new(String name, ObjectiveKind kind, ObjectiveThreshold threshold, int level) {
136 this.name = name
137 this.kind = kind
138 this.threshold = threshold
139 this.level = level
140 }
141
142 override isHardObjective() {
143 threshold.hard
144 }
145
146 override satisifiesHardObjective(Double fitness) {
147 threshold.satisfiesThreshold(fitness, comparator)
148 }
149
150 override getComparator() {
151 kind.comparator
152 }
153
154 override setComparator(Comparator<Double> comparator) {
155 kind = ObjectiveKind.fromComparator(comparator)
156 }
157
158 override getFitness(ThreadContext context) {
159 val fitness = getRawFitness(context)
160 threshold.postProcessCost(fitness, kind)
161 }
162
163 protected def double getRawFitness(ThreadContext context)
164}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/IThreeValuedObjective.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/IThreeValuedObjective.xtend
new file mode 100644
index 00000000..4a870a3e
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/IThreeValuedObjective.xtend
@@ -0,0 +1,10 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization
2
3import org.eclipse.viatra.dse.base.ThreadContext
4import org.eclipse.viatra.dse.objectives.IObjective
5
6interface IThreeValuedObjective extends IObjective {
7 def Double getWorstPossibleFitness(ThreadContext threadContext)
8
9 def Double getBestPossibleFitness(ThreadContext threadContext)
10}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/MatchCostObjective.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/MatchCostObjective.xtend
new file mode 100644
index 00000000..a0c6a2c1
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/MatchCostObjective.xtend
@@ -0,0 +1,52 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization
2
3import com.google.common.collect.ImmutableList
4import java.util.Collection
5import org.eclipse.viatra.dse.base.ThreadContext
6import org.eclipse.viatra.query.runtime.api.IPatternMatch
7import org.eclipse.viatra.query.runtime.api.IQuerySpecification
8import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher
9import org.eclipse.xtend.lib.annotations.Data
10
11@Data
12class MatchCostElement {
13 val IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> querySpecification
14 val double weight
15}
16
17class MatchCostObjective extends DirectionalThresholdObjective {
18 val Collection<MatchCostElement> costElements
19 Collection<CostElementMatcher> matchers
20
21 new(String name, Collection<MatchCostElement> costElements, ObjectiveKind kind, ObjectiveThreshold threshold,
22 int level) {
23 super(name, kind, threshold, level)
24 this.costElements = costElements
25 }
26
27 override createNew() {
28 new MatchCostObjective(name, costElements, kind, threshold, level)
29 }
30
31 override init(ThreadContext context) {
32 val queryEngine = context.queryEngine
33 matchers = ImmutableList.copyOf(costElements.map [
34 val matcher = querySpecification.getMatcher(queryEngine)
35 new CostElementMatcher(matcher, weight)
36 ])
37 }
38
39 override protected getRawFitness(ThreadContext context) {
40 var double cost = 0
41 for (it : matchers) {
42 cost += weight * matcher.countMatches
43 }
44 cost
45 }
46
47 @Data
48 private static class CostElementMatcher {
49 val ViatraQueryMatcher<? extends IPatternMatch> matcher
50 val double weight
51 }
52}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/ObjectiveKind.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/ObjectiveKind.java
new file mode 100644
index 00000000..cbbaaafd
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/ObjectiveKind.java
@@ -0,0 +1,60 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization;
2
3import java.util.Comparator;
4
5import org.eclipse.viatra.dse.objectives.Comparators;
6
7public enum ObjectiveKind {
8 LOWER_IS_BETTER {
9
10 @Override
11 public Comparator<Double> getComparator() {
12 return Comparators.LOWER_IS_BETTER;
13 }
14
15 @Override
16 public double getInvalidValue() {
17 return Double.POSITIVE_INFINITY;
18 }
19
20 @Override
21 public double getSatisfiedValue() {
22 return Double.NEGATIVE_INFINITY;
23 }
24
25 },
26 HIGHER_IS_BETTER {
27
28 @Override
29 public Comparator<Double> getComparator() {
30 return Comparators.HIGHER_IS_BETTER;
31 }
32
33 @Override
34 public double getInvalidValue() {
35 return Double.NEGATIVE_INFINITY;
36 }
37
38 @Override
39 public double getSatisfiedValue() {
40 return Double.POSITIVE_INFINITY;
41 }
42
43 };
44
45 public abstract Comparator<Double> getComparator();
46
47 public abstract double getInvalidValue();
48
49 public abstract double getSatisfiedValue();
50
51 public static ObjectiveKind fromComparator(Comparator<Double> comparator) {
52 if (Comparators.LOWER_IS_BETTER.equals(comparator)) {
53 return ObjectiveKind.LOWER_IS_BETTER;
54 } else if (Comparators.HIGHER_IS_BETTER.equals(comparator)) {
55 return ObjectiveKind.HIGHER_IS_BETTER;
56 } else {
57 throw new IllegalStateException("Only LOWER_IS_BETTER and HIGHER_IS_BETTER comparators are supported.");
58 }
59 }
60}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/QueryBasedObjective.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/QueryBasedObjective.xtend
new file mode 100644
index 00000000..d355f5be
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/QueryBasedObjective.xtend
@@ -0,0 +1,48 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization
2
3import org.eclipse.viatra.dse.base.ThreadContext
4import org.eclipse.viatra.query.runtime.api.IPatternMatch
5import org.eclipse.viatra.query.runtime.api.IQuerySpecification
6import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher
7
8class QueryBasedObjective extends DirectionalThresholdObjective {
9 val IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> querySpecification
10 ViatraQueryMatcher<? extends IPatternMatch> matcher
11
12 new(IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> querySpecification,
13 ObjectiveKind kind, ObjectiveThreshold threshold, int level) {
14 super(querySpecification.simpleName + " objective", kind, threshold, level)
15 if (querySpecification.parameters.size != 1) {
16 throw new IllegalArgumentException("Objective query must have a single parameter")
17 }
18 this.querySpecification = querySpecification
19 }
20
21 override createNew() {
22 new QueryBasedObjective(querySpecification, kind, threshold, level)
23 }
24
25 override init(ThreadContext context) {
26 matcher = querySpecification.getMatcher(context.queryEngine)
27 }
28
29 override protected getRawFitness(ThreadContext context) {
30 val iterator = matcher.allMatches.iterator
31 if (!iterator.hasNext) {
32 return invalidValue
33 }
34 val value = iterator.next.get(0)
35 if (iterator.hasNext) {
36 throw new IllegalStateException("Multiple matches for objective query")
37 }
38 if (value instanceof Number) {
39 value.doubleValue
40 } else {
41 throw new IllegalStateException("Objective value is not an instance of Number")
42 }
43 }
44
45 private def getInvalidValue() {
46 kind.invalidValue
47 }
48}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/ThreeValuedCostObjective.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/ThreeValuedCostObjective.xtend
new file mode 100644
index 00000000..0a6fd55b
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/ThreeValuedCostObjective.xtend
@@ -0,0 +1,85 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization
2
3import com.google.common.collect.ImmutableList
4import java.util.Collection
5import org.eclipse.viatra.dse.base.ThreadContext
6import org.eclipse.viatra.query.runtime.api.IPatternMatch
7import org.eclipse.viatra.query.runtime.api.IQuerySpecification
8import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher
9import org.eclipse.xtend.lib.annotations.Data
10
11@Data
12class ThreeValuedCostElement {
13 val IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> currentMatchQuery
14 val IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> mayMatchQuery
15 val IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> mustMatchQuery
16 val int weight
17}
18
19class ThreeValuedCostObjective extends AbstractThreeValuedObjective {
20 val Collection<ThreeValuedCostElement> costElements
21 Collection<CostElementMatchers> matchers
22
23 new(String name, Collection<ThreeValuedCostElement> costElements, ObjectiveKind kind, ObjectiveThreshold threshold,
24 int level) {
25 super(name, kind, threshold, level)
26 this.costElements = costElements
27 }
28
29 override createNew() {
30 new ThreeValuedCostObjective(name, costElements, kind, threshold, level)
31 }
32
33 override init(ThreadContext context) {
34 val queryEngine = context.queryEngine
35 matchers = ImmutableList.copyOf(costElements.map [ element |
36 new CostElementMatchers(
37 queryEngine.getMatcher(element.currentMatchQuery),
38 queryEngine.getMatcher(element.mayMatchQuery),
39 queryEngine.getMatcher(element.mustMatchQuery),
40 element.weight
41 )
42 ])
43 }
44
45 override getRawFitness(ThreadContext context) {
46 var int cost = 0
47 for (matcher : matchers) {
48 cost += matcher.weight * matcher.currentMatcher.countMatches
49 }
50 cost as double
51 }
52
53 override getLowestPossibleFitness(ThreadContext threadContext) {
54 var int cost = 0
55 for (matcher : matchers) {
56 if (matcher.weight >= 0) {
57 cost += matcher.weight * matcher.mustMatcher.countMatches
58 } else if (matcher.mayMatcher.countMatches > 0) {
59 // TODO Count may matches.
60 return Double.NEGATIVE_INFINITY
61 }
62 }
63 cost as double
64 }
65
66 override getHighestPossibleFitness(ThreadContext threadContext) {
67 var int cost = 0
68 for (matcher : matchers) {
69 if (matcher.weight <= 0) {
70 cost += matcher.weight * matcher.mustMatcher.countMatches
71 } else if (matcher.mayMatcher.countMatches > 0) {
72 return Double.POSITIVE_INFINITY
73 }
74 }
75 cost as double
76 }
77
78 @Data
79 private static class CostElementMatchers {
80 val ViatraQueryMatcher<? extends IPatternMatch> currentMatcher
81 val ViatraQueryMatcher<? extends IPatternMatch> mayMatcher
82 val ViatraQueryMatcher<? extends IPatternMatch> mustMatcher
83 val int weight
84 }
85}