From a620f07468780778bd55dcffc30245def37ece69 Mon Sep 17 00:00:00 2001 From: Kristóf Marussy Date: Thu, 6 Aug 2020 16:07:16 +0200 Subject: MoDeS3 unit propagation WIP --- .../xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbin | Bin 0 -> 14631 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbin (limited to 'Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbin') diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbin b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbin new file mode 100644 index 00000000..4f542a67 Binary files /dev/null and b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbin differ -- cgit v1.2.3-70-g09d2 From 4fe7fce97aedbd516109ef81afc33e00112b7b68 Mon Sep 17 00:00:00 2001 From: Kristóf Marussy Date: Fri, 28 Aug 2020 18:58:37 +0200 Subject: Must unit propagation --- .../.ApplicationConfigurationIdeModule.xtendbin | Bin 1700 -> 1700 bytes .../ide/.ApplicationConfigurationIdeSetup.xtendbin | Bin 2525 -> 2525 bytes .../.SolverSemanticHighlightCalculator.xtendbin | Bin 5333 -> 5333 bytes .../.SolverSemanticTextAttributeProvider.xtendbin | Bin 4902 -> 4902 bytes .../validation/.SolverLanguageValidator.xtendbin | Bin 1716 -> 1716 bytes ....SolverLanguageTokenDefInjectingParser.xtendbin | Bin 2741 -> 2741 bytes ...nguageSyntheticTokenSyntacticSequencer.xtendbin | Bin 2757 -> 2757 bytes Domains/ca.mcgill.rtgmrt.example.modes3/.gitignore | 1 + .../META-INF/MANIFEST.MF | 5 +- .../ecore-gen/modes3/Modes3Factory.java | 9 + .../ecore-gen/modes3/Modes3ModelRoot.java | 4 +- .../ecore-gen/modes3/Modes3Package.java | 76 + .../ecore-gen/modes3/SimpleSegment.java | 17 + .../ecore-gen/modes3/impl/Modes3FactoryImpl.java | 11 + .../ecore-gen/modes3/impl/Modes3ModelRootImpl.java | 10 +- .../ecore-gen/modes3/impl/Modes3PackageImpl.java | 24 +- .../ecore-gen/modes3/impl/SimpleSegmentImpl.java | 37 + .../modes3/util/Modes3AdapterFactory.java | 18 + .../ecore-gen/modes3/util/Modes3Switch.java | 22 + .../model/modes3.aird_deactivated | 1531 -------------------- .../model/modes3.ecore | 3 +- .../model/modes3.genmodel | 1 + .../output/solution.partialinterpretation | 1068 -------------- .../output/solution1.gml | 1191 --------------- .../output/solution1.partialinterpretation | 1037 ------------- .../output/solution1.png | Bin 105065 -> 0 bytes Domains/ca.mcgill.rtgmrt.example.modes3/plugin.xml | 8 +- .../src/modes3/queries/Modes3Queries.vql | 54 +- .../src/modes3/run/Modes3ModelGenerator.xtend | 30 +- .../src/modes3/run/Modes3TypeScopeHint.xtend | 79 + .../run/Modes3UnitPropagationGenerator.xtend | 470 ++++-- .../vql-gen/modes3/queries/.gitignore | 7 + .../modes3/queries/ExtraInputOfTurnout.java | 730 ---------- .../vql-gen/modes3/queries/InputsOfTurnout.java | 570 ++++++++ .../vql-gen/modes3/queries/Modes3Queries.java | 72 +- .../modes3/queries/NoExtraInputOfTurnout.java | 560 ------- .../modes3/queries/TooFewInputsOfTurnout.java | 559 +++++++ .../queries/TooManyExtraInputsOfTurnout.java | 570 -------- .../modes3/queries/TooManyInputsOfSegment.java | 64 +- .../modes3/queries/TooManyInputsOfTurnout.java | 600 ++++++++ .../vql-gen/modes3/queries/Turnout.java | 543 ------- .../vql-gen/modes3/queries/TurnoutInSegments.java | 564 ------- .../modes3/run/.Modes3ModelGenerator.xtendbin | Bin 14631 -> 15038 bytes .../modes3/run/.Modes3TypeScopeHint.xtendbin | Bin 0 -> 7179 bytes .../run/.Modes3UnitPropagationGenerator.xtendbin | Bin 9899 -> 11735 bytes .../xtend-gen/modes3/run/.gitignore | 1 + .../xtend-gen/modes3/run/Modes3ModelGenerator.java | 56 +- .../xtend-gen/modes3/run/Modes3TypeScopeHint.java | 133 ++ .../modes3/run/Modes3UnitPropagationGenerator.java | 1133 +++++++++++---- .../plugin.xml | 68 - .../ModelGenerationMethodProvider.xtend | 14 +- .../cardinality/LinearTypeConstraintHint.xtend | 4 +- .../logic2viatra/cardinality/ScopePropagator.xtend | 14 +- .../logic2viatra/patterns/PatternGenerator.xtend | 4 +- .../logic2viatra/patterns/PatternProvider.xtend | 11 +- .../patterns/RelationDeclarationIndexer.xtend | 2 +- .../patterns/RelationRefinementGenerator.xtend | 137 +- .../rules/RefinementRuleProvider.xtend | 338 +++-- .../viatrasolver/reasoner/ViatraReasoner.xtend | 4 + .../dse/BestFirstStrategyForModelGeneration.java | 4 +- .../mit/inf/dslreasoner/run/FileSystemHint.xtend | 4 +- .../bme/mit/inf/dslreasoner/run/SGraphHint.xtend | 4 +- .../mit/inf/dslreasoner/run/SatelliteHint.xtend | 4 +- .../hu/bme/mit/inf/dslreasoner/run/SimpleRun.xtend | 6 +- 64 files changed, 3907 insertions(+), 8579 deletions(-) create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/SimpleSegment.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/impl/SimpleSegmentImpl.java delete mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/model/modes3.aird_deactivated delete mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/output/solution.partialinterpretation delete mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/output/solution1.gml delete mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/output/solution1.partialinterpretation delete mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/output/solution1.png create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/Modes3TypeScopeHint.xtend delete mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/ExtraInputOfTurnout.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/InputsOfTurnout.java delete mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/NoExtraInputOfTurnout.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooFewInputsOfTurnout.java delete mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooManyExtraInputsOfTurnout.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooManyInputsOfTurnout.java delete mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/Turnout.java delete mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TurnoutInSegments.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3TypeScopeHint.xtendbin create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/Modes3TypeScopeHint.java (limited to 'Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbin') diff --git a/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeModule.xtendbin b/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeModule.xtendbin index 1e457bb2..e697e27d 100644 Binary files a/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeModule.xtendbin and b/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeModule.xtendbin differ diff --git a/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeSetup.xtendbin b/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeSetup.xtendbin index 6ad24fc0..ddbe1979 100644 Binary files a/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeSetup.xtendbin and b/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeSetup.xtendbin differ diff --git a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticHighlightCalculator.xtendbin b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticHighlightCalculator.xtendbin index 18c9aee3..e1e21292 100644 Binary files a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticHighlightCalculator.xtendbin and b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticHighlightCalculator.xtendbin differ diff --git a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticTextAttributeProvider.xtendbin b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticTextAttributeProvider.xtendbin index 0ebd4493..b967ea7c 100644 Binary files a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticTextAttributeProvider.xtendbin and b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticTextAttributeProvider.xtendbin differ diff --git a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.SolverLanguageValidator.xtendbin b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.SolverLanguageValidator.xtendbin index bb484ba1..2c271c98 100644 Binary files a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.SolverLanguageValidator.xtendbin and b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.SolverLanguageValidator.xtendbin differ diff --git a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.SolverLanguageTokenDefInjectingParser.xtendbin b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.SolverLanguageTokenDefInjectingParser.xtendbin index 61448536..40f87b4c 100644 Binary files a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.SolverLanguageTokenDefInjectingParser.xtendbin and b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.SolverLanguageTokenDefInjectingParser.xtendbin differ diff --git a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.SolverLanguageSyntheticTokenSyntacticSequencer.xtendbin b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.SolverLanguageSyntheticTokenSyntacticSequencer.xtendbin index 9af9309d..d0715440 100644 Binary files a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.SolverLanguageSyntheticTokenSyntacticSequencer.xtendbin and b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.SolverLanguageSyntheticTokenSyntacticSequencer.xtendbin differ diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/.gitignore b/Domains/ca.mcgill.rtgmrt.example.modes3/.gitignore index ae3c1726..6cef8ea6 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/.gitignore +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/.gitignore @@ -1 +1,2 @@ /bin/ +output/ diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/META-INF/MANIFEST.MF b/Domains/ca.mcgill.rtgmrt.example.modes3/META-INF/MANIFEST.MF index 53e4a39c..96bd2113 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/META-INF/MANIFEST.MF +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/META-INF/MANIFEST.MF @@ -3,6 +3,7 @@ Bundle-ManifestVersion: 2 Bundle-Name: %pluginName Bundle-SymbolicName: ca.mcgill.rtgmrt.example.modes3;singleton:=true Bundle-Version: 0.1.0.qualifier +Bundle-ClassPath: . Bundle-Vendor: %providerName Bundle-Localization: plugin Export-Package: modes3, @@ -28,7 +29,7 @@ Require-Bundle: org.eclipse.viatra.query.runtime, org.eclipse.emf.ecore.xmi;bundle-version="2.16.0", hu.bme.mit.inf.dslreasoner.visualisation;bundle-version="1.0.0", org.eclipse.viatra.query.patternlanguage.emf;bundle-version="2.4.0" -Bundle-RequiredExecutionEnvironment: J2SE-1.5 -Bundle-ActivationPolicy: lazy Import-Package: org.apache.log4j Automatic-Module-Name: ca.mcgill.rtgmrt.example.modes3 +Bundle-ActivationPolicy: lazy +Bundle-RequiredExecutionEnvironment: J2SE-1.5 diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/Modes3Factory.java b/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/Modes3Factory.java index 73188db1..10ce47a1 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/Modes3Factory.java +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/Modes3Factory.java @@ -57,6 +57,15 @@ public interface Modes3Factory extends EFactory { */ Train createTrain(); + /** + * Returns a new object of class 'Simple Segment'. + * + * + * @return a new object of class 'Simple Segment'. + * @generated + */ + SimpleSegment createSimpleSegment(); + /** * Returns the package supported by this factory. * diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/Modes3ModelRoot.java b/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/Modes3ModelRoot.java index 4f925b7a..d46ee305 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/Modes3ModelRoot.java +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/Modes3ModelRoot.java @@ -62,7 +62,7 @@ public interface Modes3ModelRoot extends EObject { /** * Returns the value of the 'Segments' containment reference list. - * The list contents are of type {@link modes3.Segment}. + * The list contents are of type {@link modes3.SimpleSegment}. * * * @return the value of the 'Segments' containment reference list. @@ -70,7 +70,7 @@ public interface Modes3ModelRoot extends EObject { * @model containment="true" * @generated */ - EList getSegments(); + EList getSegments(); /** * Returns the value of the 'Turnouts' containment reference list. diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/Modes3Package.java b/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/Modes3Package.java index 4760af9d..a19c1955 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/Modes3Package.java +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/Modes3Package.java @@ -304,6 +304,62 @@ public interface Modes3Package extends EPackage { int TRAIN_OPERATION_COUNT = 0; + /** + * The meta object id for the '{@link modes3.impl.SimpleSegmentImpl Simple Segment}' class. + * + * + * @see modes3.impl.SimpleSegmentImpl + * @see modes3.impl.Modes3PackageImpl#getSimpleSegment() + * @generated + */ + int SIMPLE_SEGMENT = 4; + + /** + * The feature id for the 'Connected To' reference list. + * + * + * @generated + * @ordered + */ + int SIMPLE_SEGMENT__CONNECTED_TO = SEGMENT__CONNECTED_TO; + + /** + * The feature id for the 'Occupied By' reference. + * + * + * @generated + * @ordered + */ + int SIMPLE_SEGMENT__OCCUPIED_BY = SEGMENT__OCCUPIED_BY; + + /** + * The feature id for the 'Id' attribute. + * + * + * @generated + * @ordered + */ + int SIMPLE_SEGMENT__ID = SEGMENT__ID; + + /** + * The number of structural features of the 'Simple Segment' class. + * + * + * @generated + * @ordered + */ + int SIMPLE_SEGMENT_FEATURE_COUNT = SEGMENT_FEATURE_COUNT + 0; + + /** + * The number of operations of the 'Simple Segment' class. + * + * + * @generated + * @ordered + */ + int SIMPLE_SEGMENT_OPERATION_COUNT = SEGMENT_OPERATION_COUNT + 0; + + /** * Returns the meta object for class '{@link modes3.Segment Segment}'. * @@ -476,6 +532,16 @@ public interface Modes3Package extends EPackage { */ EAttribute getTrain_Speed(); + /** + * Returns the meta object for class '{@link modes3.SimpleSegment Simple Segment}'. + * + * + * @return the meta object for class 'Simple Segment'. + * @see modes3.SimpleSegment + * @generated + */ + EClass getSimpleSegment(); + /** * Returns the factory that creates the instances of the model. * @@ -635,6 +701,16 @@ public interface Modes3Package extends EPackage { */ EAttribute TRAIN__SPEED = eINSTANCE.getTrain_Speed(); + /** + * The meta object literal for the '{@link modes3.impl.SimpleSegmentImpl Simple Segment}' class. + * + * + * @see modes3.impl.SimpleSegmentImpl + * @see modes3.impl.Modes3PackageImpl#getSimpleSegment() + * @generated + */ + EClass SIMPLE_SEGMENT = eINSTANCE.getSimpleSegment(); + } } //Modes3Package diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/SimpleSegment.java b/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/SimpleSegment.java new file mode 100644 index 00000000..da77510f --- /dev/null +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/SimpleSegment.java @@ -0,0 +1,17 @@ +/** + */ +package modes3; + + +/** + * + * A representation of the model object 'Simple Segment'. + * + * + * + * @see modes3.Modes3Package#getSimpleSegment() + * @model + * @generated + */ +public interface SimpleSegment extends Segment { +} // SimpleSegment diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/impl/Modes3FactoryImpl.java b/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/impl/Modes3FactoryImpl.java index 6ec86cb6..60947533 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/impl/Modes3FactoryImpl.java +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/impl/Modes3FactoryImpl.java @@ -60,6 +60,7 @@ public class Modes3FactoryImpl extends EFactoryImpl implements Modes3Factory { case Modes3Package.MODES3_MODEL_ROOT: return createModes3ModelRoot(); case Modes3Package.TURNOUT: return createTurnout(); case Modes3Package.TRAIN: return createTrain(); + case Modes3Package.SIMPLE_SEGMENT: return createSimpleSegment(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } @@ -105,6 +106,16 @@ public class Modes3FactoryImpl extends EFactoryImpl implements Modes3Factory { return train; } + /** + * + * + * @generated + */ + public SimpleSegment createSimpleSegment() { + SimpleSegmentImpl simpleSegment = new SimpleSegmentImpl(); + return simpleSegment; + } + /** * * diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/impl/Modes3ModelRootImpl.java b/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/impl/Modes3ModelRootImpl.java index d1ee25ff..ccab1f29 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/impl/Modes3ModelRootImpl.java +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/impl/Modes3ModelRootImpl.java @@ -6,7 +6,7 @@ import java.util.Collection; import modes3.Modes3ModelRoot; import modes3.Modes3Package; -import modes3.Segment; +import modes3.SimpleSegment; import modes3.Train; import modes3.Turnout; @@ -79,7 +79,7 @@ public class Modes3ModelRootImpl extends MinimalEObjectImpl.Container implements * @generated * @ordered */ - protected EList segments; + protected EList segments; /** * The cached value of the '{@link #getTurnouts() Turnouts}' containment reference list. @@ -148,9 +148,9 @@ public class Modes3ModelRootImpl extends MinimalEObjectImpl.Container implements * * @generated */ - public EList getSegments() { + public EList getSegments() { if (segments == null) { - segments = new EObjectContainmentEList(Segment.class, this, Modes3Package.MODES3_MODEL_ROOT__SEGMENTS); + segments = new EObjectContainmentEList(SimpleSegment.class, this, Modes3Package.MODES3_MODEL_ROOT__SEGMENTS); } return segments; } @@ -223,7 +223,7 @@ public class Modes3ModelRootImpl extends MinimalEObjectImpl.Container implements return; case Modes3Package.MODES3_MODEL_ROOT__SEGMENTS: getSegments().clear(); - getSegments().addAll((Collection)newValue); + getSegments().addAll((Collection)newValue); return; case Modes3Package.MODES3_MODEL_ROOT__TURNOUTS: getTurnouts().clear(); diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/impl/Modes3PackageImpl.java b/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/impl/Modes3PackageImpl.java index 2b9e828c..557da4c1 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/impl/Modes3PackageImpl.java +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/impl/Modes3PackageImpl.java @@ -6,6 +6,7 @@ import modes3.Modes3Factory; import modes3.Modes3ModelRoot; import modes3.Modes3Package; import modes3.Segment; +import modes3.SimpleSegment; import modes3.Train; import modes3.Turnout; @@ -51,6 +52,13 @@ public class Modes3PackageImpl extends EPackageImpl implements Modes3Package { */ private EClass trainEClass = null; + /** + * + * + * @generated + */ + private EClass simpleSegmentEClass = null; + /** * Creates an instance of the model Package, registered with * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package @@ -256,6 +264,15 @@ public class Modes3PackageImpl extends EPackageImpl implements Modes3Package { return (EAttribute)trainEClass.getEStructuralFeatures().get(2); } + /** + * + * + * @generated + */ + public EClass getSimpleSegment() { + return simpleSegmentEClass; + } + /** * * @@ -303,6 +320,8 @@ public class Modes3PackageImpl extends EPackageImpl implements Modes3Package { createEReference(trainEClass, TRAIN__LOCATION); createEAttribute(trainEClass, TRAIN__ID); createEAttribute(trainEClass, TRAIN__SPEED); + + simpleSegmentEClass = createEClass(SIMPLE_SEGMENT); } /** @@ -334,6 +353,7 @@ public class Modes3PackageImpl extends EPackageImpl implements Modes3Package { // Add supertypes to classes turnoutEClass.getESuperTypes().add(this.getSegment()); + simpleSegmentEClass.getESuperTypes().add(this.getSegment()); // Initialize classes, features, and operations; add parameters initEClass(segmentEClass, Segment.class, "Segment", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); @@ -344,7 +364,7 @@ public class Modes3PackageImpl extends EPackageImpl implements Modes3Package { initEClass(modes3ModelRootEClass, Modes3ModelRoot.class, "Modes3ModelRoot", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getModes3ModelRoot_Id(), ecorePackage.getEInt(), "id", null, 0, 1, Modes3ModelRoot.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getModes3ModelRoot_Trains(), this.getTrain(), null, "trains", null, 0, -1, Modes3ModelRoot.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); - initEReference(getModes3ModelRoot_Segments(), this.getSegment(), null, "segments", null, 0, -1, Modes3ModelRoot.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); + initEReference(getModes3ModelRoot_Segments(), this.getSimpleSegment(), null, "segments", null, 0, -1, Modes3ModelRoot.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getModes3ModelRoot_Turnouts(), this.getTurnout(), null, "turnouts", null, 0, -1, Modes3ModelRoot.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(turnoutEClass, Turnout.class, "Turnout", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); @@ -356,6 +376,8 @@ public class Modes3PackageImpl extends EPackageImpl implements Modes3Package { initEAttribute(getTrain_Id(), ecorePackage.getEInt(), "id", null, 0, 1, Train.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getTrain_Speed(), ecorePackage.getEDouble(), "speed", null, 0, 1, Train.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); + initEClass(simpleSegmentEClass, SimpleSegment.class, "SimpleSegment", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); + // Create resource createResource(eNS_URI); } diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/impl/SimpleSegmentImpl.java b/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/impl/SimpleSegmentImpl.java new file mode 100644 index 00000000..e3fd6c34 --- /dev/null +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/impl/SimpleSegmentImpl.java @@ -0,0 +1,37 @@ +/** + */ +package modes3.impl; + +import modes3.Modes3Package; +import modes3.SimpleSegment; + +import org.eclipse.emf.ecore.EClass; + +/** + * + * An implementation of the model object 'Simple Segment'. + * + * + * @generated + */ +public class SimpleSegmentImpl extends SegmentImpl implements SimpleSegment { + /** + * + * + * @generated + */ + protected SimpleSegmentImpl() { + super(); + } + + /** + * + * + * @generated + */ + @Override + protected EClass eStaticClass() { + return Modes3Package.Literals.SIMPLE_SEGMENT; + } + +} //SimpleSegmentImpl diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/util/Modes3AdapterFactory.java b/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/util/Modes3AdapterFactory.java index 86568e9d..9c5c8d2d 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/util/Modes3AdapterFactory.java +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/util/Modes3AdapterFactory.java @@ -84,6 +84,10 @@ public class Modes3AdapterFactory extends AdapterFactoryImpl { return createTrainAdapter(); } @Override + public Adapter caseSimpleSegment(SimpleSegment object) { + return createSimpleSegmentAdapter(); + } + @Override public Adapter defaultCase(EObject object) { return createEObjectAdapter(); } @@ -159,6 +163,20 @@ public class Modes3AdapterFactory extends AdapterFactoryImpl { return null; } + /** + * Creates a new adapter for an object of class '{@link modes3.SimpleSegment Simple Segment}'. + * + * This default implementation returns null so that we can easily ignore cases; + * it's useful to ignore a case when inheritance will catch all the cases anyway. + * + * @return the new adapter. + * @see modes3.SimpleSegment + * @generated + */ + public Adapter createSimpleSegmentAdapter() { + return null; + } + /** * Creates a new adapter for the default case. * diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/util/Modes3Switch.java b/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/util/Modes3Switch.java index 5dab272b..0c28861a 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/util/Modes3Switch.java +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/util/Modes3Switch.java @@ -91,6 +91,13 @@ public class Modes3Switch extends Switch { if (result == null) result = defaultCase(theEObject); return result; } + case Modes3Package.SIMPLE_SEGMENT: { + SimpleSegment simpleSegment = (SimpleSegment)theEObject; + T result = caseSimpleSegment(simpleSegment); + if (result == null) result = caseSegment(simpleSegment); + if (result == null) result = defaultCase(theEObject); + return result; + } default: return defaultCase(theEObject); } } @@ -155,6 +162,21 @@ public class Modes3Switch extends Switch { return null; } + /** + * Returns the result of interpreting the object as an instance of 'Simple Segment'. + * + * This implementation returns null; + * returning a non-null result will terminate the switch. + * + * @param object the target of the switch. + * @return the result of interpreting the object as an instance of 'Simple Segment'. + * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) + * @generated + */ + public T caseSimpleSegment(SimpleSegment object) { + return null; + } + /** * Returns the result of interpreting the object as an instance of 'EObject'. * diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/model/modes3.aird_deactivated b/Domains/ca.mcgill.rtgmrt.example.modes3/model/modes3.aird_deactivated deleted file mode 100644 index f5400732..00000000 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/model/modes3.aird_deactivated +++ /dev/null @@ -1,1531 +0,0 @@ - - - - http://www.eclipse.org/emf/2002/Ecore - modes3.ecore - modes3.genmodel - ../src/modes3/queries/Modes3Queries.vql - java:/Objects/org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch - java:/Objects/java.lang.Object - java:/Objects/jdk.internal.HotSpotIntrinsicCandidate - java:/Objects/java.lang.annotation.Target - java:/Objects/java.lang.annotation.ElementType - java:/Objects/java.lang.Enum - java:/Objects/java.lang.Comparable - java:/Primitives - java:/Objects/java.lang.CloneNotSupportedException - java:/Objects/java.lang.Exception - java:/Objects/java.lang.Throwable - java:/Objects/java.io.Serializable - java:/Objects/java.lang.Deprecated - java:/Objects/java.lang.annotation.Retention - java:/Objects/java.lang.annotation.RetentionPolicy - java:/Objects/java.lang.String - java:/Objects/java.lang.CharSequence - java:/Objects/java.util.stream.IntStream - java:/Objects/java.util.stream.BaseStream - java:/Objects/java.lang.AutoCloseable - java:/Objects/java.lang.Class - java:/Objects/java.lang.reflect.GenericDeclaration - java:/Objects/java.lang.reflect.AnnotatedElement - java:/Objects/java.lang.annotation.Annotation - java:/Objects/java.lang.InterruptedException - java:/Objects/java.lang.StackTraceElement - java:/Objects/java.lang.Module - java:/Objects/java.lang.WeakPairMap - java:/Objects/java.lang.ref.ReferenceQueue - java:/Objects/java.lang.ref.Reference - java:/Objects/java.lang.Thread - java:/Objects/java.lang.Runnable - java:/Objects/java.lang.FunctionalInterface - java:/Objects/java.lang.annotation.Documented - java:/Objects/java.io.ObjectInputStream - java:/Objects/java.io.InputStream - java:/Objects/java.io.Closeable - java:/Objects/java.io.IOException - java:/Objects/java.util.Comparator - java:/Objects/java.util.function.Function - java:/Objects/java.lang.ClassNotFoundException - java:/Objects/java.lang.ReflectiveOperationException - java:/Objects/java.lang.StringBuffer - java:/Objects/java.lang.AbstractStringBuilder - java:/Objects/java.lang.Appendable - java:/Objects/java.io.ObjectStreamException - java:/Objects/java.io.PrintStream - java:/Objects/java.io.FilterOutputStream - java:/Objects/java.io.OutputStream - java:/Objects/java.io.Flushable - java:/Objects/java.io.ObjectInput - java:/Objects/java.io.DataInput - java:/Objects/java.io.ObjectStreamConstants - java:/Objects/java.io.SerializablePermission - java:/Objects/java.security.BasicPermission - java:/Objects/java.security.Permission - java:/Objects/java.security.Guard - java:/Objects/java.lang.SecurityException - java:/Objects/java.lang.RuntimeException - java:/Objects/java.lang.StringBuilder - java:/Objects/java.io.ObjectOutputStream - java:/Objects/java.io.ObjectOutput - java:/Objects/java.io.DataOutput - java:/Objects/java.io.DataInputStream - java:/Objects/java.io.FilterInputStream - java:/Objects/java.util.concurrent.ConcurrentMap - java:/Objects/java.util.Map - java:/Objects/java.util.function.BiFunction - java:/Objects/java.io.PrintWriter - java:/Objects/java.io.Writer - java:/Objects/java.io.ObjectStreamClass - java:/Objects/java.io.InvalidClassException - java:/Objects/java.util.Set - java:/Objects/java.util.Collection - java:/Objects/java.lang.Iterable - java:/Objects/java.util.function.Consumer - java:/Objects/java.util.List - java:/Objects/java.util.Iterator - java:/Objects/java.lang.Boolean - java:/Objects/java.lang.StackFrameInfo - java:/Objects/java.lang.StackWalker - java:/Objects/java.lang.invoke.MethodType - java:/Objects/java.lang.ref.WeakReference - java:/Objects/java.lang.ThreadGroup - java:/Objects/java.lang.Void - java:/Objects/java.io.ObjectInputFilter - java:/Objects/java.lang.IllegalArgumentException - java:/Objects/java.io.UnsupportedEncodingException - java:/Objects/java.lang.reflect.Type - java:/Objects/java.lang.System - java:/Objects/java.util.function.Supplier - java:/Objects/java.lang.ClassLoader - java:/Objects/java.util.Deque - java:/Objects/java.util.Queue - java:/Objects/java.util.stream.Stream - java:/Objects/java.util.function.Predicate - java:/Objects/java.lang.module.ModuleDescriptor - java:/Objects/java.util.Optional - java:/Objects/java.io.ObjectInputValidation - java:/Objects/java.io.InvalidObjectException - java:/Objects/sun.reflect.annotation.AnnotationType - java:/Objects/java.lang.reflect.Method - java:/Objects/java.lang.reflect.Executable - java:/Objects/java.lang.reflect.AccessibleObject - java:/Objects/jdk.internal.reflect.CallerSensitive - java:/Objects/java.lang.ModuleLayer - java:/Objects/java.lang.module.Configuration - java:/Objects/java.lang.module.Resolver - java:/Objects/java.lang.module.ModuleFinder - java:/Objects/java.lang.module.ModuleReference - java:/Objects/java.net.URI - java:/Objects/java.net.URISyntaxException - java:/Objects/java.lang.ref.SoftReference - java:/Objects/jdk.internal.vm.annotation.ForceInline - java:/Objects/java.lang.module.ResolvedModule - java:/Objects/java.security.AccessControlContext - java:/Objects/java.security.ProtectionDomain - java:/Objects/sun.security.util.Debug - java:/Objects/java.math.BigInteger - java:/Objects/java.lang.Number - java:/Objects/java.io.StreamCorruptedException - java:/Objects/jdk.internal.misc.Unsafe - java:/Objects/java.lang.InstantiationException - java:/Objects/java.lang.reflect.Constructor - java:/Objects/jdk.internal.reflect.ConstructorAccessor - java:/Objects/java.lang.reflect.InvocationTargetException - java:/Objects/java.lang.reflect.Field - java:/Objects/java.lang.reflect.Member - java:/Objects/java.io.Externalizable - java:/Objects/java.io.NotActiveException - java:/Objects/java.lang.SecurityManager - java:/Objects/java.net.InetAddress - java:/Objects/java.net.UnknownHostException - java:/Objects/java.lang.reflect.AnnotatedType - java:/Objects/java.io.SerialCallbackContext - java:/Objects/java.security.PermissionCollection - java:/Objects/java.util.Enumeration - java:/Objects/java.util.stream.Collector - java:/Objects/java.util.function.BiConsumer - java:/Objects/java.util.concurrent.ConcurrentHashMap - java:/Objects/java.util.AbstractMap - java:/Objects/java.util.stream.DoubleStream - java:/Objects/java.lang.Double - java:/Objects/java.lang.NumberFormatException - java:/Objects/jdk.internal.reflect.ConstantPool - java:/Objects/sun.nio.ch.Interruptible - java:/Objects/java.util.stream.LongStream - java:/Objects/java.lang.Long - java:/Objects/java.lang.ThreadLocal - java:/Objects/java.util.concurrent.atomic.AtomicInteger - java:/Objects/java.util.function.IntBinaryOperator - java:/Objects/jdk.internal.vm.annotation.Contended - java:/Objects/java.security.DomainCombiner - java:/Objects/java.util.function.UnaryOperator - java:/Objects/java.security.AccessControlException - java:/Objects/java.lang.NoSuchMethodException - java:/Objects/java.lang.NoSuchFieldException - java:/Objects/sun.reflect.generics.factory.GenericsFactory - java:/Objects/java.lang.reflect.TypeVariable - java:/Objects/java.util.function.ToDoubleFunction - java:/Objects/jdk.internal.misc.JavaSecurityAccess - java:/Objects/java.security.PrivilegedAction - java:/Objects/java.util.function.ToIntFunction - java:/Objects/java.security.CodeSource - java:/Objects/java.net.URL - java:/Objects/java.net.URLStreamHandlerFactory - java:/Objects/java.net.URLStreamHandler - java:/Objects/java.net.URLConnection - java:/Objects/java.net.UnknownServiceException - java:/Objects/sun.reflect.generics.repository.ClassRepository - java:/Objects/sun.reflect.generics.repository.GenericDeclRepository - java:/Objects/sun.reflect.generics.repository.AbstractRepository - java:/Objects/sun.reflect.generics.visitor.Reifier - java:/Objects/sun.reflect.generics.visitor.TypeTreeVisitor - java:/Objects/sun.reflect.generics.tree.ArrayTypeSignature - java:/Objects/sun.reflect.generics.tree.FieldTypeSignature - java:/Objects/sun.reflect.generics.tree.BaseType - java:/Objects/sun.reflect.generics.tree.TypeSignature - java:/Objects/sun.reflect.generics.tree.ReturnType - java:/Objects/sun.reflect.generics.tree.TypeTree - java:/Objects/sun.reflect.generics.tree.Tree - java:/Objects/java.util.function.ToLongFunction - java:/Objects/java.security.Principal - java:/Objects/javax.security.auth.Subject - java:/Objects/javax.security.auth.AuthPermission - java:/Objects/java.security.cert.Certificate - java:/Objects/java.security.cert.CertificateEncodingException - java:/Objects/java.security.cert.CertificateException - java:/Objects/java.security.GeneralSecurityException - java:/Objects/java.nio.charset.Charset - java:/Objects/java.nio.charset.spi.CharsetProvider - java:/Objects/java.lang.SafeVarargs - java:/Objects/java.security.CodeSigner - java:/Objects/java.security.cert.CertPath - java:/Objects/java.util.function.BinaryOperator - java:/Objects/java.security.cert.CertificateFactory - java:/Objects/java.security.cert.CertificateFactorySpi - java:/Objects/java.security.cert.CRLException - java:/Objects/java.util.Locale - java:/Objects/java.lang.Cloneable - java:/Objects/java.util.function.IntFunction - java:/Objects/java.net.SocketPermission - java:/Objects/java.net.MalformedURLException - java:/Objects/java.lang.PublicMethods - java:/Objects/jdk.internal.reflect.ReflectionFactory - java:/Objects/java.lang.invoke.MethodHandle - java:/Objects/java.lang.invoke.LambdaForm - java:/Objects/sun.invoke.util.Wrapper - java:/Objects/java.lang.ClassCastException - java:/Objects/java.lang.Package - java:/Objects/java.lang.NamedPackage - java:/Objects/java.util.Spliterator - java:/Objects/java.util.function.DoubleConsumer - java:/Objects/java.net.Proxy - java:/Objects/java.net.SocketAddress - java:/Objects/java.lang.Integer - java:/Objects/java.net.spi.URLStreamHandlerProvider - java:/Objects/java.util.function.IntConsumer - java:/Objects/java.util.Hashtable - java:/Objects/java.util.Dictionary - java:/Objects/java.util.function.LongConsumer - java:/Objects/java.io.ObjectStreamField - java:/Objects/java.util.Random - java:/Objects/java.util.concurrent.atomic.AtomicLong - java:/Objects/java.util.function.LongBinaryOperator - java:/Objects/java.net.UrlDeserializedState - java:/Objects/java.util.function.LongUnaryOperator - java:/Objects/java.io.FileDescriptor - java:/Objects/jdk.internal.ref.PhantomCleanable - java:/Objects/java.lang.ref.PhantomReference - java:/Objects/java.io.DataOutputStream - java:/Objects/java.util.ListIterator - java:/Objects/java.io.SyncFailedException - java:/Objects/java.lang.IllegalAccessException - java:/Objects/java.lang.ClassValue - java:/Objects/java.util.WeakHashMap - java:/Objects/java.util.AbstractSet - java:/Objects/java.util.AbstractCollection - java:/Objects/jdk.internal.reflect.FieldAccessor - java:/Objects/sun.reflect.generics.repository.FieldRepository - java:/Objects/jdk.internal.reflect.MethodAccessor - java:/Objects/jdk.internal.reflect.LangReflectAccess - java:/Objects/java.util.function.DoublePredicate - java:/Objects/java.lang.ref.Cleaner - java:/Objects/java.util.concurrent.ThreadFactory - java:/Objects/java.io.OptionalDataException - java:/Objects/java.util.OptionalDouble - java:/Objects/java.util.function.DoubleSupplier - java:/Objects/jdk.internal.ref.CleanerImpl - java:/Objects/jdk.internal.ref.SoftCleanable - java:/Objects/sun.reflect.generics.repository.ConstructorRepository - java:/Objects/sun.reflect.generics.tree.MethodTypeSignature - java:/Objects/sun.reflect.generics.tree.Signature - java:/Objects/sun.reflect.generics.tree.FormalTypeParameter - java:/Objects/sun.reflect.generics.tree.TypeArgument - java:/Objects/sun.reflect.generics.tree.BooleanSignature - java:/Objects/sun.reflect.generics.tree.BottomSignature - java:/Objects/sun.reflect.generics.tree.ByteSignature - java:/Objects/sun.reflect.generics.tree.CharSignature - java:/Objects/sun.reflect.generics.tree.ClassTypeSignature - java:/Objects/sun.reflect.generics.tree.SimpleClassTypeSignature - java:/Objects/sun.reflect.generics.tree.DoubleSignature - java:/Objects/sun.reflect.generics.tree.FloatSignature - java:/Objects/sun.reflect.generics.tree.IntSignature - java:/Objects/sun.reflect.generics.tree.LongSignature - java:/Objects/sun.reflect.generics.tree.ShortSignature - java:/Objects/sun.reflect.generics.tree.TypeVariableSignature - java:/Objects/sun.reflect.generics.tree.VoidDescriptor - java:/Objects/sun.reflect.generics.tree.Wildcard - java:/Objects/sun.reflect.generics.visitor.Visitor - java:/Objects/sun.reflect.generics.tree.ClassSignature - java:/Objects/sun.reflect.generics.repository.MethodRepository - java:/Objects/jdk.internal.ref.WeakCleanable - java:/Objects/java.lang.invoke.BoundMethodHandle - java:/Objects/java.lang.invoke.ClassSpecializer - java:/Objects/jdk.internal.org.objectweb.asm.MethodVisitor - java:/Objects/jdk.internal.org.objectweb.asm.AnnotationVisitor - java:/Objects/java.lang.invoke.MemberName - java:/Objects/java.lang.invoke.ResolvedMethodName - java:/Objects/java.lang.invoke.MethodHandleImpl - java:/Objects/java.lang.invoke.DelegatingMethodHandle - java:/Objects/java.lang.reflect.Parameter - java:/Objects/java.lang.invoke.MethodTypeForm - java:/Objects/jdk.internal.vm.annotation.Stable - java:/Objects/java.util.function.IntUnaryOperator - java:/Objects/java.util.function.IntPredicate - java:/Objects/java.util.function.ObjIntConsumer - java:/Objects/java.util.OptionalInt - java:/Objects/java.util.function.IntSupplier - java:/Objects/java.util.PrimitiveIterator - java:/Objects/java.util.function.IntToDoubleFunction - java:/Objects/java.util.function.IntToLongFunction - java:/Objects/java.util.IntSummaryStatistics - java:/Objects/java.lang.TypeNotPresentException - java:/Objects/java.lang.UnsupportedOperationException - java:/Objects/java.io.FileNotFoundException - java:/Objects/java.util.function.ObjDoubleConsumer - java:/Objects/java.util.function.DoubleFunction - java:/Objects/java.util.function.DoubleUnaryOperator - java:/Objects/java.util.function.DoubleToIntFunction - java:/Objects/java.util.function.DoubleToLongFunction - java:/Objects/java.util.function.DoubleBinaryOperator - java:/Objects/java.util.DoubleSummaryStatistics - java:/Objects/java.lang.invoke.Invokers - java:/Objects/java.lang.invoke.VarHandle - java:/Objects/java.lang.invoke.VarForm - java:/Objects/java.lang.invoke.LambdaFormEditor - java:/Objects/java.lang.invoke.LambdaFormBuffer - java:/Objects/java.util.ArrayList - java:/Objects/java.util.AbstractList - java:/Objects/java.util.RandomAccess - java:/Objects/java.lang.IndexOutOfBoundsException - java:/Objects/java.util.function.LongPredicate - java:/Objects/java.util.function.ObjLongConsumer - java:/Objects/java.util.OptionalLong - java:/Objects/java.util.function.LongSupplier - java:/Objects/java.util.function.LongFunction - java:/Objects/java.util.function.LongToDoubleFunction - java:/Objects/java.util.function.LongToIntFunction - java:/Objects/java.util.LongSummaryStatistics - java:/Objects/java.util.concurrent.CountedCompleter - java:/Objects/java.util.concurrent.ForkJoinTask - java:/Objects/java.util.concurrent.Future - java:/Objects/java.util.concurrent.ExecutionException - java:/Objects/java.io.File - java:/Objects/java.security.SecureRandom - java:/Objects/java.util.regex.Pattern - java:/Objects/java.util.regex.Matcher - java:/Objects/java.util.regex.MatchResult - java:/Objects/java.util.function.ToDoubleBiFunction - java:/Objects/java.lang.invoke.CallSite - java:/Objects/java.lang.invoke.WrongMethodTypeException - java:/Objects/java.io.OutputStreamWriter - java:/Objects/java.nio.charset.CharsetEncoder - java:/Objects/java.nio.CharBuffer - java:/Objects/java.nio.Buffer - java:/Objects/java.util.function.ToIntBiFunction - java:/Objects/jdk.internal.vm.annotation.DontInline - java:/Objects/java.lang.ArrayIndexOutOfBoundsException - java:/Objects/java.lang.ClassFormatError - java:/Objects/java.lang.LinkageError - java:/Objects/java.lang.Error - java:/Objects/java.nio.ByteBuffer - java:/Objects/java.nio.DoubleBuffer - java:/Objects/java.nio.ByteOrder - java:/Objects/java.util.function.ToLongBiFunction - java:/Objects/java.lang.invoke.MethodHandleNatives - java:/Objects/java.lang.NoSuchMethodError - java:/Objects/java.lang.IncompatibleClassChangeError - java:/Objects/java.lang.AssertionStatusDirectives - java:/Objects/java.util.concurrent.atomic.AtomicReference - java:/Objects/java.util.concurrent.locks.ReentrantLock - java:/Objects/java.util.concurrent.locks.Lock - java:/Objects/java.util.concurrent.locks.Condition - java:/Objects/java.util.concurrent.TimeUnit - java:/Objects/java.time.Duration - java:/Objects/java.time.temporal.TemporalAmount - java:/Objects/java.time.temporal.Temporal - java:/Objects/java.time.temporal.TemporalAccessor - java:/Objects/java.time.temporal.TemporalField - java:/Objects/java.time.temporal.TemporalUnit - java:/Objects/java.util.concurrent.RunnableFuture - java:/Objects/jdk.internal.perf.PerfCounter - java:/Objects/java.nio.LongBuffer - java:/Objects/java.net.ContentHandler - java:/Objects/java.util.concurrent.Callable - java:/Objects/jdk.internal.misc.JavaLangInvokeAccess - java:/Objects/java.util.HashMap - java:/Objects/java.util.LinkedHashMap - java:/Objects/jdk.internal.perf.Perf - java:/Objects/java.util.concurrent.TimeoutException - java:/Objects/java.util.Vector - java:/Objects/java.nio.FloatBuffer - java:/Objects/java.net.FileNameMap - java:/Objects/java.util.concurrent.ForkJoinPool - java:/Objects/java.util.concurrent.AbstractExecutorService - java:/Objects/java.util.concurrent.ExecutorService - java:/Objects/java.util.concurrent.Executor - java:/Objects/java.time.temporal.ChronoUnit - java:/Objects/java.nio.IntBuffer - java:/Objects/java.net.ContentHandlerFactory - java:/Objects/java.math.BigDecimal - java:/Objects/java.math.MathContext - java:/Objects/java.math.RoundingMode - java:/Objects/java.nio.ShortBuffer - java:/Objects/sun.net.www.MessageHeader - java:/Objects/java.util.regex.PatternSyntaxException - java:/Objects/java.security.Timestamp - java:/Objects/java.util.Date - java:/Objects/java.time.Instant - java:/Objects/java.time.temporal.TemporalAdjuster - java:/Objects/java.lang.Readable - java:/Objects/java.util.regex.IntHashSet - java:/Objects/java.time.temporal.TemporalQuery - java:/Objects/jdk.internal.org.objectweb.asm.Attribute - java:/Objects/jdk.internal.org.objectweb.asm.ClassReader - java:/Objects/jdk.internal.org.objectweb.asm.ClassVisitor - java:/Objects/jdk.internal.org.objectweb.asm.FieldVisitor - java:/Objects/jdk.internal.org.objectweb.asm.TypePath - java:/Objects/java.time.temporal.ValueRange - java:/Objects/jdk.internal.org.objectweb.asm.Handle - java:/Objects/java.time.format.ResolverStyle - java:/Objects/jdk.internal.org.objectweb.asm.Label - java:/Objects/jdk.internal.org.objectweb.asm.MethodWriter - java:/Objects/jdk.internal.org.objectweb.asm.ClassWriter - java:/Objects/jdk.internal.org.objectweb.asm.Item - java:/Objects/sun.util.locale.InternalLocaleBuilder - java:/Objects/sun.util.locale.LocaleSyntaxException - java:/Objects/sun.util.calendar.BaseCalendar - java:/Objects/sun.util.calendar.AbstractCalendar - java:/Objects/sun.util.calendar.CalendarSystem - java:/Objects/sun.util.calendar.CalendarDate - java:/Objects/java.util.TimeZone - java:/Objects/java.time.ZoneId - java:/Objects/java.time.format.TextStyle - java:/Objects/jdk.internal.org.objectweb.asm.ByteVector - java:/Objects/sun.util.locale.LocaleObjectCache - java:/Objects/sun.util.locale.BaseLocale - java:/Objects/sun.util.locale.LocaleExtensions - java:/Objects/java.lang.Character - java:/Objects/jdk.internal.org.objectweb.asm.Context - java:/Objects/sun.util.locale.provider.LocaleServiceProviderPool - java:/Objects/java.util.spi.LocaleServiceProvider - java:/Objects/java.math.MutableBigInteger - java:/Objects/java.util.spi.LocaleNameProvider - java:/Objects/java.util.concurrent.ForkJoinWorkerThread - java:/Objects/java.util.ResourceBundle - java:/Objects/java.util.ServiceLoader - java:/Objects/jdk.internal.module.ServicesCatalog - java:/Objects/jdk.internal.loader.ClassLoaderValue - java:/Objects/jdk.internal.loader.AbstractClassLoaderValue - java:/Objects/java.lang.IllegalStateException - java:/Objects/java.util.Formatter - java:/Objects/java.util.Calendar - java:/Objects/java.text.DateFormatSymbols - java:/Objects/java.lang.RuntimePermission - java:/Objects/jdk.internal.org.objectweb.asm.ModuleVisitor - java:/Objects/sun.util.locale.provider.LocaleResources - java:/Objects/sun.util.locale.provider.ResourceBundleBasedAdapter - java:/Objects/sun.util.resources.LocaleData - java:/Objects/java.util.spi.ResourceBundleProvider - java:/Objects/jdk.internal.vm.annotation.ReservedStackAccess - java:/Objects/jdk.internal.org.objectweb.asm.AnnotationWriter - java:/Objects/jdk.internal.org.objectweb.asm.FieldWriter - java:/Objects/jdk.internal.org.objectweb.asm.ModuleWriter - java:/Objects/java.util.MissingResourceException - java:/Objects/java.io.BufferedWriter - java:/Objects/sun.util.locale.LanguageTag - java:/Objects/sun.util.locale.ParseStatus - java:/Objects/sun.util.locale.StringTokenIterator - java:/Objects/sun.util.locale.Extension - java:/Objects/java.util.SortedMap - java:/Objects/jdk.internal.org.objectweb.asm.Frame - java:/Objects/jdk.internal.org.objectweb.asm.Type - java:/Objects/sun.util.locale.provider.LocaleProviderAdapter - java:/Objects/sun.util.locale.provider.FallbackLocaleProviderAdapter - java:/Objects/sun.util.locale.provider.JRELocaleProviderAdapter - java:/Objects/java.text.spi.BreakIteratorProvider - java:/Objects/java.text.BreakIterator - java:/Objects/java.text.CharacterIterator - java:/Objects/sun.util.calendar.Era - java:/Objects/java.util.concurrent.locks.AbstractQueuedSynchronizer - java:/Objects/java.util.concurrent.locks.AbstractOwnableSynchronizer - java:/Objects/java.io.FilenameFilter - java:/Objects/jdk.internal.org.objectweb.asm.Handler - java:/Objects/sun.util.calendar.Gregorian - java:/Objects/java.time.ZoneOffset - java:/Objects/java.time.zone.ZoneRules - java:/Objects/java.time.zone.ZoneOffsetTransition - java:/Objects/java.time.LocalDateTime - java:/Objects/java.time.chrono.ChronoLocalDateTime - java:/Objects/java.time.chrono.ChronoZonedDateTime - java:/Objects/java.time.format.DateTimeFormatter - java:/Objects/java.text.Format - java:/Objects/java.text.AttributedCharacterIterator - java:/Objects/java.time.zone.ZoneOffsetTransitionRule - java:/Objects/java.time.Month - java:/Objects/jdk.internal.org.objectweb.asm.Edge - java:/Objects/java.time.DayOfWeek - java:/Objects/sun.invoke.empty.Empty - java:/Objects/java.time.LocalTime - java:/Objects/java.time.LocalDate - java:/Objects/java.time.chrono.ChronoLocalDate - java:/Objects/java.time.chrono.Chronology - java:/Objects/java.time.chrono.Era - java:/Objects/java.lang.InternalError - java:/Objects/java.lang.VirtualMachineError - java:/Objects/java.io.FileFilter - java:/Objects/java.lang.reflect.ParameterizedType - java:/Objects/java.time.OffsetTime - java:/Objects/java.time.OffsetDateTime - java:/Objects/java.time.ZonedDateTime - java:/Objects/java.time.Clock - java:/Objects/java.lang.reflect.WildcardType - java:/Objects/java.time.Period - java:/Objects/java.time.chrono.ChronoPeriod - java:/Objects/java.net.NetworkInterface - java:/Objects/java.net.SocketException - java:/Objects/java.util.spi.ResourceBundleControlProvider - java:/Objects/java.time.chrono.IsoChronology - java:/Objects/java.time.chrono.AbstractChronology - java:/Objects/java.time.temporal.ChronoField - java:/Objects/java.net.InetAddressImpl - java:/Objects/java.time.chrono.IsoEra - java:/Objects/java.util.NavigableSet - java:/Objects/java.util.SortedSet - java:/Objects/java.net.InterfaceAddress - java:/Objects/java.net.Inet4Address - java:/Objects/java.security.PublicKey - java:/Objects/java.security.Key - java:/Objects/java.text.FieldPosition - java:/Objects/java.text.ParseException - java:/Objects/java.util.ServiceConfigurationError - java:/Objects/java.nio.file.Path - java:/Objects/java.nio.file.Watchable - java:/Objects/java.nio.file.WatchService - java:/Objects/java.nio.file.WatchKey - java:/Objects/java.nio.file.WatchEvent - java:/Objects/java.text.ParsePosition - java:/Objects/java.time.format.DateTimeFormatterBuilder - java:/Objects/java.time.format.DateTimePrintContext - java:/Objects/java.time.format.DecimalStyle - java:/Objects/java.time.format.DateTimeParseException - java:/Objects/java.time.DateTimeException - java:/Objects/java.io.FileSystem - java:/Objects/java.time.format.FormatStyle - java:/Objects/java.security.NoSuchAlgorithmException - java:/Objects/java.security.SecureRandomSpi - java:/Objects/java.security.SecureRandomParameters - java:/Objects/java.time.format.DateTimeParseContext - java:/Objects/java.time.format.Parsed - java:/Objects/java.io.BufferedReader - java:/Objects/java.io.Reader - java:/Objects/java.time.format.SignStyle - java:/Objects/java.security.InvalidKeyException - java:/Objects/java.security.KeyException - java:/Objects/java.security.Provider - java:/Objects/java.util.Properties - java:/Objects/java.util.InvalidPropertiesFormatException - java:/Objects/java.io.NotSerializableException - java:/Objects/jdk.internal.misc.JavaLangAccess - java:/Objects/java.nio.charset.CharacterCodingException - java:/Objects/java.security.NoSuchProviderException - java:/Objects/java.lang.LayerInstantiationException - java:/Objects/java.security.MessageDigest - java:/Objects/java.security.MessageDigestSpi - java:/Objects/java.security.DigestException - java:/Objects/java.time.format.DateTimeTextProvider - java:/Objects/sun.security.util.MessageDigestSpi2 - java:/Objects/javax.crypto.SecretKey - java:/Objects/javax.security.auth.Destroyable - java:/Objects/javax.security.auth.DestroyFailedException - java:/Objects/jdk.internal.module.ModuleTarget - java:/Objects/java.nio.file.FileSystem - java:/Objects/java.nio.file.FileStore - java:/Objects/java.nio.file.attribute.FileStoreAttributeView - java:/Objects/java.nio.file.attribute.AttributeView - java:/Objects/java.nio.file.LinkOption - java:/Objects/java.nio.file.OpenOption - java:/Objects/java.nio.file.PathMatcher - java:/Objects/java.security.SignatureException - java:/Objects/java.nio.file.attribute.UserPrincipalLookupService - java:/Objects/java.nio.file.attribute.GroupPrincipal - java:/Objects/java.nio.file.attribute.UserPrincipal - java:/Objects/java.nio.file.spi.FileSystemProvider - java:/Objects/java.nio.file.AccessMode - java:/Objects/java.nio.charset.CharsetDecoder - java:/Objects/java.nio.charset.CoderResult - java:/Objects/java.nio.file.attribute.FileAttributeView - java:/Objects/java.util.LinkedList - java:/Objects/java.util.AbstractSequentialList - java:/Objects/sun.util.resources.Bundles - java:/Objects/jdk.internal.misc.JavaUtilResourceBundleAccess - java:/Objects/java.util.EnumSet - java:/Objects/java.security.cert.CRL - java:/Objects/java.security.PrivilegedExceptionAction - java:/Objects/java.security.PrivilegedActionException - java:/Objects/java.lang.module.ModuleReader - java:/Objects/java.nio.file.CopyOption - java:/Objects/java.nio.file.attribute.FileAttribute - java:/Objects/java.nio.channels.AsynchronousFileChannel - java:/Objects/java.nio.channels.AsynchronousChannel - java:/Objects/java.nio.channels.Channel - java:/Objects/java.nio.channels.SeekableByteChannel - java:/Objects/java.nio.channels.ByteChannel - java:/Objects/java.nio.channels.ReadableByteChannel - java:/Objects/java.nio.file.DirectoryStream - java:/Objects/sun.util.resources.OpenListResourceBundle - java:/Objects/java.nio.channels.FileChannel - java:/Objects/java.nio.channels.spi.AbstractInterruptibleChannel - java:/Objects/java.nio.channels.InterruptibleChannel - java:/Objects/java.nio.file.attribute.BasicFileAttributes - java:/Objects/java.nio.file.attribute.FileTime - java:/Objects/java.nio.channels.FileLock - java:/Objects/java.nio.channels.WritableByteChannel - java:/Objects/java.nio.channels.CompletionHandler - java:/Objects/java.nio.channels.GatheringByteChannel - java:/Objects/java.nio.channels.ScatteringByteChannel - java:/Objects/java.nio.MappedByteBuffer - java:/Objects/sun.util.resources.TimeZoneNamesBundle - java:/Objects/java.nio.channels.AsynchronousCloseException - java:/Objects/java.nio.channels.ClosedChannelException - java:/Objects/sun.nio.cs.StreamEncoder - java:/Objects/sun.util.resources.ParallelListResourceBundle - java:/Objects/java.util.concurrent.atomic.AtomicMarkableReference - java:/Objects/java.nio.charset.CodingErrorAction - java:/Objects/java.util.spi.CalendarDataProvider - java:/Objects/java.io.Console - java:/Objects/java.util.spi.CalendarNameProvider - java:/Objects/java.io.FileOutputStream - java:/Objects/jdk.internal.misc.JavaIOFileDescriptorAccess - java:/Objects/sun.util.spi.CalendarProvider - java:/Objects/java.text.spi.CollatorProvider - java:/Objects/java.text.Collator - java:/Objects/java.text.CollationKey - java:/Objects/java.util.spi.CurrencyNameProvider - java:/Objects/java.text.spi.DateFormatProvider - java:/Objects/java.text.DateFormat - java:/Objects/java.text.NumberFormat - java:/Objects/java.util.Currency - java:/Objects/java.util.HashSet - java:/Objects/java.text.spi.DateFormatSymbolsProvider - java:/Objects/java.text.spi.DecimalFormatSymbolsProvider - java:/Objects/java.text.DecimalFormatSymbols - java:/Objects/sun.text.spi.JavaTimeDateTimePatternProvider - java:/Objects/java.text.spi.NumberFormatProvider - java:/Objects/java.util.spi.TimeZoneNameProvider - java:/Objects/org.eclipse.viatra.query.runtime.api.IPatternMatch - java:/Objects/org.eclipse.viatra.query.runtime.api.IQuerySpecification - java:/Objects/org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQueryHeader - java:/Objects/org.eclipse.viatra.query.runtime.matchers.psystem.annotations.PAnnotation - java:/Objects/org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter - java:/Objects/org.eclipse.viatra.query.runtime.matchers.context.IInputKey - java:/Objects/org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection - java:/Objects/org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility - java:/Objects/org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery - java:/Objects/org.eclipse.viatra.query.runtime.matchers.psystem.PTraceable - java:/Objects/org.eclipse.viatra.query.runtime.matchers.psystem.queries.PDisjunction - java:/Objects/org.eclipse.viatra.query.runtime.matchers.psystem.PBody - java:/Objects/org.eclipse.viatra.query.runtime.matchers.psystem.PVariable - java:/Objects/org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint - java:/Objects/org.eclipse.viatra.query.runtime.matchers.context.IQueryMetaContext - java:/Objects/org.eclipse.viatra.query.runtime.matchers.context.InputKeyImplication - java:/Objects/org.eclipse.viatra.query.runtime.matchers.context.IPosetComparator - java:/Objects/org.eclipse.viatra.query.runtime.matchers.tuple.Tuple - java:/Objects/org.eclipse.viatra.query.runtime.matchers.tuple.AbstractTuple - java:/Objects/org.eclipse.viatra.query.runtime.matchers.tuple.ITuple - java:/Objects/org.eclipse.viatra.query.runtime.matchers.psystem.TypeJudgement - java:/Objects/org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter - java:/Objects/org.eclipse.viatra.query.runtime.matchers.psystem.VariableDeferredPConstraint - java:/Objects/org.eclipse.viatra.query.runtime.matchers.psystem.DeferredPConstraint - java:/Objects/org.eclipse.viatra.query.runtime.matchers.psystem.BasePConstraint - java:/Objects/org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint - java:/Objects/org.eclipse.viatra.query.runtime.matchers.backend.QueryHintOption - java:/Objects/org.eclipse.viatra.query.runtime.matchers.backend.IQueryBackendFactory - java:/Objects/org.eclipse.viatra.query.runtime.matchers.backend.IMatcherCapability - java:/Objects/org.eclipse.viatra.query.runtime.matchers.context.IQueryBackendContext - java:/Objects/org.eclipse.viatra.query.runtime.matchers.backend.IQueryBackendHintProvider - java:/Objects/org.eclipse.viatra.query.runtime.matchers.psystem.queries.PProblem - java:/Objects/org.eclipse.viatra.query.runtime.matchers.planning.QueryProcessingException - java:/Objects/org.eclipse.viatra.query.runtime.matchers.ViatraQueryRuntimeException - java:/Objects/org.eclipse.viatra.query.runtime.matchers.planning.SubPlan - java:/Objects/org.eclipse.viatra.query.runtime.matchers.planning.operations.POperation - java:/Objects/org.eclipse.viatra.query.runtime.matchers.backend.IQueryBackend - java:/Objects/org.eclipse.viatra.query.runtime.matchers.backend.IQueryResultProvider - java:/Objects/org.eclipse.viatra.query.runtime.matchers.backend.IUpdateable - java:/Objects/org.eclipse.viatra.query.runtime.matchers.tuple.TupleMask - java:/Objects/org.eclipse.viatra.query.runtime.matchers.tuple.IModifiableTuple - java:/Objects/org.eclipse.viatra.query.runtime.matchers.util.Accuracy - java:/Objects/org.apache.log4j.Logger - java:/Objects/org.apache.log4j.Category - java:/Objects/org.apache.log4j.spi.AppenderAttachable - java:/Objects/org.apache.log4j.Appender - java:/Objects/org.apache.log4j.spi.Filter - java:/Objects/org.apache.log4j.spi.OptionHandler - java:/Objects/org.apache.log4j.spi.LoggingEvent - java:/Objects/org.apache.log4j.Priority - java:/Objects/org.apache.log4j.Level - java:/Objects/org.apache.log4j.spi.ThrowableInformation - java:/Objects/org.apache.log4j.spi.LocationInfo - java:/Objects/java.io.StringWriter - java:/Objects/org.apache.log4j.spi.LoggerRepository - java:/Objects/org.apache.log4j.spi.HierarchyEventListener - java:/Objects/org.apache.log4j.helpers.AppenderAttachableImpl - java:/Objects/org.apache.log4j.spi.ErrorHandler - java:/Objects/org.apache.log4j.spi.LoggerFactory - java:/Objects/org.apache.log4j.Layout - java:/Objects/org.eclipse.viatra.query.runtime.matchers.psystem.analysis.QueryAnalyzer - java:/Objects/org.eclipse.viatra.query.runtime.matchers.context.IQueryCacheContext - java:/Objects/org.eclipse.viatra.query.runtime.matchers.context.IQueryResultProviderAccess - java:/Objects/org.eclipse.viatra.query.runtime.matchers.context.IQueryRuntimeContext - java:/Objects/org.eclipse.viatra.query.runtime.matchers.context.IQueryRuntimeContextListener - java:/Objects/org.eclipse.viatra.query.runtime.matchers.context.IndexingService - java:/Objects/org.eclipse.viatra.query.runtime.api.ViatraQueryEngine - java:/Objects/org.eclipse.viatra.query.runtime.api.scope.IBaseIndex - java:/Objects/org.eclipse.viatra.query.runtime.api.scope.ViatraBaseIndexChangeListener - java:/Objects/org.eclipse.viatra.query.runtime.api.scope.IIndexingErrorListener - java:/Objects/org.eclipse.viatra.query.runtime.api.scope.IInstanceObserver - java:/Objects/org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher - java:/Objects/org.eclipse.viatra.query.runtime.api.scope.QueryScope - java:/Objects/org.eclipse.viatra.query.runtime.internal.apiimpl.EngineContextFactory - java:/Objects/org.eclipse.viatra.query.runtime.api.scope.IEngineContext - java:/Objects/org.eclipse.viatra.query.runtime.api.ViatraQueryEngineOptions - java:/Objects/org.eclipse.viatra.query.runtime.api.impl.BaseMatcher - java:/Objects/org.eclipse.viatra.query.runtime.internal.apiimpl.QueryResultWrapper - java:/Objects/org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification - java:/Objects/org.eclipse.viatra.query.runtime.api.impl.BaseQuerySpecification - java:/Objects/java.lang.ExceptionInInitializerError - java:/Objects/org.eclipse.viatra.query.runtime.exception.ViatraQueryException - java:/Objects/org.eclipse.viatra.query.runtime.matchers.psystem.queries.QueryInitializationException - java:/Objects/org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedPatternGroup - java:/Objects/org.eclipse.viatra.query.runtime.api.impl.BaseQueryGroup - java:/Objects/org.eclipse.viatra.query.runtime.api.IQueryGroup - java:/Objects/org.eclipse.viatra.query.runtime.api.AdvancedViatraQueryEngine - java:/Objects/org.eclipse.viatra.query.runtime.api.ViatraQueryEngineLifecycleListener - java:/Objects/org.eclipse.viatra.query.runtime.api.IMatchUpdateListener - java:/Objects/org.eclipse.viatra.query.runtime.api.ViatraQueryModelUpdateListener - java:/Objects/java.lang.Override - java:/Objects/org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery - java:/Objects/org.eclipse.viatra.query.runtime.matchers.psystem.queries.BasePQuery - java:/Objects/org.eclipse.emf.ecore.EClassifier - java:/Objects/org.eclipse.emf.ecore.ENamedElement - java:/Objects/org.eclipse.emf.ecore.EModelElement - java:/Objects/org.eclipse.emf.ecore.EObject - java:/Objects/org.eclipse.emf.common.notify.Notifier - java:/Objects/org.eclipse.emf.common.util.EList - java:/Objects/org.eclipse.emf.common.notify.Adapter - java:/Objects/org.eclipse.emf.common.notify.Notification - java:/Objects/org.eclipse.emf.common.util.TreeIterator - java:/Objects/org.eclipse.emf.ecore.EClass - java:/Objects/org.eclipse.emf.ecore.EAttribute - java:/Objects/org.eclipse.emf.ecore.EStructuralFeature - java:/Objects/org.eclipse.emf.ecore.ETypedElement - java:/Objects/org.eclipse.emf.ecore.EGenericType - java:/Objects/org.eclipse.emf.ecore.ETypeParameter - java:/Objects/org.eclipse.emf.ecore.EAnnotation - java:/Objects/org.eclipse.emf.common.util.EMap - java:/Objects/org.eclipse.emf.ecore.EReference - java:/Objects/org.eclipse.emf.ecore.InternalEObject - java:/Objects/org.eclipse.emf.common.notify.NotificationChain - java:/Objects/org.eclipse.emf.ecore.resource.Resource - java:/Objects/org.eclipse.emf.common.util.URI - java:/Objects/org.eclipse.emf.common.util.Pool - java:/Objects/org.eclipse.emf.common.util.WeakInterningHashSet - java:/Objects/org.eclipse.emf.common.util.InterningSet - java:/Objects/java.util.concurrent.locks.ReentrantReadWriteLock - java:/Objects/java.util.concurrent.locks.ReadWriteLock - java:/Objects/java.lang.IllegalMonitorStateException - java:/Objects/org.eclipse.emf.common.util.SegmentSequence - java:/Objects/org.eclipse.emf.common.util.CommonUtil - java:/Objects/org.eclipse.emf.ecore.resource.ResourceSet - java:/Objects/org.eclipse.emf.common.notify.AdapterFactory - java:/Objects/org.eclipse.emf.ecore.EPackage - java:/Objects/org.eclipse.emf.ecore.EFactory - java:/Objects/org.eclipse.emf.ecore.EDataType - java:/Objects/org.eclipse.emf.common.CommonPlugin - java:/Objects/org.eclipse.emf.common.EMFPlugin - java:/Objects/org.eclipse.emf.common.util.DelegatingResourceLocator - java:/Objects/org.eclipse.emf.common.util.ResourceLocator - java:/Objects/org.eclipse.emf.common.util.Logger - java:/Objects/org.eclipse.core.runtime.Plugin - java:/Objects/org.osgi.framework.BundleActivator - java:/Objects/org.osgi.framework.BundleContext - java:/Objects/org.osgi.framework.BundleReference - java:/Objects/org.osgi.framework.Bundle - java:/Objects/org.osgi.framework.ServiceReference - java:/Objects/java.security.cert.X509Certificate - java:/Objects/java.security.cert.X509Extension - java:/Objects/java.security.cert.CertificateExpiredException - java:/Objects/java.security.cert.CertificateNotYetValidException - java:/Objects/java.security.cert.CertificateParsingException - java:/Objects/javax.security.auth.x500.X500Principal - java:/Objects/sun.security.x509.X500Name - java:/Objects/sun.security.x509.GeneralNameInterface - java:/Objects/sun.security.util.DerOutputStream - java:/Objects/java.io.ByteArrayOutputStream - java:/Objects/sun.security.util.DerEncoder - java:/Objects/sun.security.util.DerValue - java:/Objects/sun.security.util.DerInputBuffer - java:/Objects/java.io.ByteArrayInputStream - java:/Objects/sun.security.util.BitArray - java:/Objects/sun.security.util.DerInputStream - java:/Objects/sun.security.util.ObjectIdentifier - java:/Objects/sun.security.util.ByteArrayLexOrder - java:/Objects/sun.security.util.ByteArrayTagOrder - java:/Objects/sun.security.x509.RDN - java:/Objects/sun.security.x509.AVA - java:/Objects/java.lang.Byte - java:/Objects/org.osgi.framework.Version - java:/Objects/org.osgi.framework.BundleException - java:/Objects/org.osgi.framework.BundleListener - java:/Objects/java.util.EventListener - java:/Objects/org.osgi.framework.BundleEvent - java:/Objects/java.util.EventObject - java:/Objects/org.osgi.framework.FrameworkListener - java:/Objects/org.osgi.framework.FrameworkEvent - java:/Objects/org.osgi.framework.ServiceListener - java:/Objects/org.osgi.framework.ServiceEvent - java:/Objects/org.osgi.framework.InvalidSyntaxException - java:/Objects/org.osgi.framework.Filter - java:/Objects/org.osgi.framework.ServiceObjects - java:/Objects/org.osgi.framework.ServiceRegistration - java:/Objects/org.osgi.framework.ServiceFactory - java:/Objects/org.eclipse.core.runtime.IPath - java:/Objects/org.eclipse.osgi.service.debug.DebugOptions - java:/Objects/org.eclipse.osgi.service.debug.DebugTrace - java:/Objects/org.eclipse.core.runtime.ILog - java:/Objects/org.eclipse.core.runtime.ILogListener - java:/Objects/org.eclipse.core.runtime.IStatus - java:/Objects/org.eclipse.core.runtime.Preferences - java:/Objects/org.eclipse.core.runtime.CoreException - java:/Objects/org.eclipse.core.runtime.ListenerList - java:/Objects/org.osgi.util.tracker.ServiceTracker - java:/Objects/org.osgi.util.tracker.ServiceTrackerCustomizer - java:/Objects/org.osgi.framework.AllServiceListener - java:/Objects/org.osgi.util.tracker.AbstractTracked - java:/Objects/org.eclipse.emf.ecore.EOperation - java:/Objects/org.eclipse.emf.ecore.EParameter - java:/Objects/org.eclipse.emf.ecore.util.FeatureMap - java:/Objects/org.eclipse.emf.ecore.util.InternalEList - java:/Objects/org.eclipse.emf.ecore.util.EContentsEList - java:/Objects/org.eclipse.emf.ecore.util.AbstractSequentialInternalEList - java:/Objects/org.eclipse.emf.ecore.resource.URIConverter - java:/Objects/java.io.InputStreamReader - java:/Objects/sun.nio.cs.StreamDecoder - java:/Objects/java.io.FileInputStream - java:/Objects/org.eclipse.emf.ecore.resource.ContentHandler - java:/Objects/org.eclipse.emf.ecore.resource.URIHandler - java:/Objects/org.eclipse.emf.ecore.EEnumLiteral - java:/Objects/org.eclipse.emf.common.util.Enumerator - java:/Objects/org.eclipse.emf.ecore.EEnum - java:/Objects/modes3.Segment - java:/Objects/modes3.Train - java:/Objects/java.lang.SuppressWarnings - java:/Objects/modes3.Turnout - ../src/modes3/run/Modes3ModelGenerator.xtend - java:/Objects/org.eclipse.xtend.lib.annotations.FinalFieldsConstructor - java:/Objects/org.eclipse.xtend.lib.macro.Active - java:/Objects/com.google.common.annotations.Beta - java:/Objects/com.google.common.annotations.GwtCompatible - java:/Objects/org.eclipse.xtend.lib.annotations.FinalFieldsConstructorProcessor - java:/Objects/org.eclipse.xtend.lib.macro.TransformationParticipant - java:/Objects/org.eclipse.xtext.xbase.lib.Extension - java:/Objects/org.eclipse.xtend.lib.macro.TransformationContext - java:/Objects/org.eclipse.xtend.lib.macro.services.Tracability - java:/Objects/org.eclipse.xtend.lib.macro.declaration.Element - java:/Objects/org.eclipse.xtend.lib.macro.services.ProblemSupport - java:/Objects/org.eclipse.xtend.lib.macro.services.Problem - java:/Objects/org.eclipse.xtext.xbase.lib.Procedures - java:/Objects/org.eclipse.xtend.lib.macro.services.TypeReferenceProvider - java:/Objects/org.eclipse.xtend.lib.macro.declaration.TypeReference - java:/Objects/org.eclipse.xtend.lib.macro.declaration.ResolvedMethod - java:/Objects/org.eclipse.xtend.lib.macro.declaration.ResolvedExecutable - java:/Objects/org.eclipse.xtend.lib.macro.declaration.ExecutableDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.TypeParameterDeclarator - java:/Objects/org.eclipse.xtend.lib.macro.declaration.MemberDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.Declaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.AnnotationTarget - java:/Objects/org.eclipse.xtend.lib.macro.declaration.NamedElement - java:/Objects/org.eclipse.xtend.lib.macro.declaration.CompilationUnit - java:/Objects/org.eclipse.xtend.lib.macro.file.Path - java:/Objects/com.google.common.collect.ImmutableList - java:/Objects/com.google.common.collect.ImmutableCollection - java:/Objects/com.google.common.collect.UnmodifiableIterator - java:/Objects/com.google.common.annotations.VisibleForTesting - java:/Objects/com.google.common.collect.UnmodifiableListIterator - java:/Objects/com.google.common.base.Splitter - java:/Objects/com.google.common.base.AbstractIterator - java:/Objects/com.google.common.base.CharMatcher - java:/Objects/com.google.common.base.Predicate - java:/Objects/com.google.common.annotations.GwtIncompatible - java:/Objects/java.util.BitSet - java:/Objects/com.google.common.base.CommonPattern - java:/Objects/com.google.common.base.CommonMatcher - java:/Objects/org.eclipse.xtend.lib.macro.declaration.TypeDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.Type - java:/Objects/org.eclipse.xtend.lib.macro.declaration.AnnotationReference - java:/Objects/org.eclipse.xtend.lib.macro.declaration.AnnotationTypeDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.AnnotationTypeElementDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.expression.Expression - java:/Objects/org.eclipse.xtend.lib.macro.declaration.Modifier - java:/Objects/org.eclipse.xtend.lib.macro.declaration.Visibility - java:/Objects/org.eclipse.xtend.lib.macro.declaration.EnumerationValueDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.EnumerationTypeDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.ConstructorDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.ParameterDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.FieldDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.MethodDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.TypeParameterDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.ClassDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.InterfaceDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.ResolvedConstructor - java:/Objects/org.eclipse.xtend.lib.macro.declaration.ResolvedParameter - java:/Objects/org.eclipse.xtend.lib.macro.declaration.ResolvedTypeParameter - java:/Objects/org.eclipse.xtend.lib.macro.services.TypeLookup - java:/Objects/org.eclipse.xtend.lib.macro.services.GlobalTypeLookup - java:/Objects/org.eclipse.xtend.lib.macro.declaration.MutableAnnotationTypeDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.MutableTypeDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.MutableMemberDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.MutableDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.MutableAnnotationTarget - java:/Objects/org.eclipse.xtend.lib.macro.declaration.MutableNamedElement - java:/Objects/org.eclipse.xtend.lib.macro.declaration.MutableElement - java:/Objects/org.eclipse.xtend.lib.macro.declaration.MutableConstructorDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.MutableExecutableDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.MutableTypeParameterDeclarator - java:/Objects/org.eclipse.xtend.lib.macro.declaration.MutableTypeParameterDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.MutableFieldDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.CompilationStrategy - java:/Objects/org.eclipse.xtend2.lib.StringConcatenationClient - java:/Objects/org.eclipse.xtend.lib.macro.declaration.MutableMethodDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.MutableParameterDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.MutableClassDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.MutableEnumerationTypeDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.MutableEnumerationValueDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.MutableInterfaceDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.declaration.MutableAnnotationTypeElementDeclaration - java:/Objects/org.eclipse.xtend.lib.macro.file.FileSystemSupport - java:/Objects/org.eclipse.xtend.lib.macro.file.FileLocations - java:/Objects/org.eclipse.xtend.lib.macro.services.AnnotationReferenceProvider - java:/Objects/org.eclipse.xtend.lib.macro.services.AnnotationReferenceBuildContext - java:/Objects/org.eclipse.xtend.lib.macro.services.Associator - java:/Objects/org.eclipse.xtend.lib.annotations.Data - java:/Objects/org.eclipse.xtend.lib.annotations.DataProcessor - java:/Objects/org.eclipse.xtend.lib.macro.AbstractClassProcessor - java:/Objects/org.eclipse.xtend.lib.macro.RegisterGlobalsParticipant - java:/Objects/org.eclipse.xtend.lib.macro.RegisterGlobalsContext - java:/Objects/org.eclipse.xtend.lib.macro.services.UpstreamTypeLookup - java:/Objects/org.eclipse.xtend.lib.macro.services.SourceTypeLookup - java:/Objects/org.eclipse.xtend.lib.macro.CodeGenerationParticipant - java:/Objects/org.eclipse.xtend.lib.macro.CodeGenerationContext - java:/Objects/org.eclipse.xtend.lib.macro.file.MutableFileSystemSupport - java:/Objects/org.eclipse.xtend.lib.macro.ValidationParticipant - java:/Objects/org.eclipse.xtend.lib.macro.ValidationContext - java:/Objects/org.eclipse.xtend.lib.annotations.Accessors - java:/Objects/org.eclipse.xtend.lib.annotations.AccessorsProcessor - java:/Objects/org.eclipse.xtend.lib.annotations.AccessorType - java:/Objects/org.eclipse.xtext.xbase.lib.ArrayLiterals - java:/Objects/org.eclipse.xtext.xbase.lib.Pure - java:/Objects/org.eclipse.xtext.xbase.lib.Inline - java:/Objects/org.eclipse.xtext.xbase.lib.CollectionLiterals - java:/Objects/org.eclipse.xtext.xbase.lib.Pair - java:/Objects/java.util.LinkedHashSet - java:/Objects/java.util.TreeMap - java:/Objects/java.util.NavigableMap - java:/Objects/java.util.TreeSet - java:/Objects/org.eclipse.xtext.xbase.lib.InputOutput - java:/Objects/org.eclipse.xtext.xbase.lib.ArrayExtensions - java:/Objects/org.eclipse.xtext.xbase.lib.BigDecimalExtensions - java:/Objects/org.eclipse.xtext.xbase.lib.BigIntegerExtensions - java:/Objects/org.eclipse.xtext.xbase.lib.BooleanExtensions - java:/Objects/com.google.common.primitives.Booleans - java:/Objects/org.eclipse.xtext.xbase.lib.ByteExtensions - java:/Objects/java.lang.Math - java:/Objects/org.eclipse.xtext.xbase.lib.CharacterExtensions - java:/Objects/org.eclipse.xtext.xbase.lib.CollectionExtensions - java:/Objects/com.google.common.collect.Iterables - java:/Objects/com.google.common.collect.FluentIterable - java:/Objects/com.google.common.base.Function - java:/Objects/com.google.common.base.Optional - java:/Objects/com.google.common.base.Supplier - java:/Objects/com.google.common.collect.ImmutableListMultimap - java:/Objects/com.google.common.collect.ImmutableMultimap - java:/Objects/com.google.common.collect.BaseImmutableMultimap - java:/Objects/com.google.common.collect.AbstractMultimap - java:/Objects/com.google.common.collect.Multimap - java:/Objects/com.google.common.collect.Multiset - java:/Objects/com.google.common.collect.Multimaps - java:/Objects/com.google.common.collect.Maps - java:/Objects/com.google.common.collect.ImmutableMap - java:/Objects/com.google.common.collect.ImmutableSet - java:/Objects/com.google.common.collect.ImmutableSetMultimap - java:/Objects/com.google.common.collect.SetMultimap - java:/Objects/com.google.common.collect.Serialization - java:/Objects/com.google.common.collect.ImmutableMultiset - java:/Objects/com.google.common.collect.ImmutableMultisetGwtSerializationDependencies - java:/Objects/com.google.common.collect.IndexedImmutableSet - java:/Objects/com.google.common.collect.AbstractListMultimap - java:/Objects/com.google.common.collect.AbstractMapBasedMultimap - java:/Objects/com.google.common.collect.AbstractSetMultimap - java:/Objects/com.google.common.collect.AbstractSortedSetMultimap - java:/Objects/com.google.common.collect.SortedSetMultimap - java:/Objects/com.google.common.collect.AbstractMultiset - java:/Objects/com.google.common.collect.Multisets - java:/Objects/com.google.common.collect.Sets - java:/Objects/com.google.common.collect.ForwardingCollection - java:/Objects/com.google.common.collect.ForwardingObject - java:/Objects/com.google.common.collect.CartesianList - java:/Objects/com.google.common.collect.ForwardingNavigableSet - java:/Objects/com.google.common.collect.ForwardingSortedSet - java:/Objects/com.google.common.collect.ForwardingSet - java:/Objects/com.google.common.collect.Ordering - java:/Objects/com.google.common.collect.Collections2 - java:/Objects/com.google.common.collect.AbstractIterator - java:/Objects/java.util.concurrent.CopyOnWriteArraySet - java:/Objects/java.util.concurrent.CopyOnWriteArrayList - java:/Objects/com.google.common.collect.Range - java:/Objects/com.google.common.collect.RangeGwtSerializationDependencies - java:/Objects/com.google.common.collect.Cut - java:/Objects/com.google.common.collect.DiscreteDomain - java:/Objects/com.google.common.collect.BoundType - java:/Objects/java.util.EnumMap - java:/Objects/com.google.common.collect.ListMultimap - java:/Objects/com.google.common.collect.ForwardingMultimap - java:/Objects/com.google.common.collect.FilteredMultimap - java:/Objects/com.google.common.collect.FilteredSetMultimap - java:/Objects/com.google.common.base.Converter - java:/Objects/com.google.common.collect.BiMap - java:/Objects/com.google.common.collect.ForwardingMap - java:/Objects/com.google.common.collect.AbstractNavigableMap - java:/Objects/com.google.common.collect.MapDifference - java:/Objects/com.google.common.collect.SortedMapDifference - java:/Objects/com.google.common.collect.ForwardingSortedMap - java:/Objects/com.google.common.base.Equivalence - java:/Objects/java.util.function.BiPredicate - java:/Objects/java.util.IdentityHashMap - java:/Objects/com.google.common.collect.ForwardingMultiset - java:/Objects/com.google.common.collect.SortedMultiset - java:/Objects/com.google.common.collect.SortedMultisetBridge - java:/Objects/com.google.common.collect.SortedIterable - java:/Objects/com.google.common.base.Joiner - java:/Objects/com.google.common.collect.ImmutableSortedSet - java:/Objects/com.google.common.collect.ImmutableSortedSetFauxverideShim - java:/Objects/com.google.common.collect.RegularImmutableSortedSet - java:/Objects/com.google.common.collect.ImmutableSortedMap - java:/Objects/com.google.common.collect.ImmutableSortedMapFauxverideShim - java:/Objects/java.util.Collections - java:/Objects/java.util.AbstractQueue - java:/Objects/org.eclipse.xtext.xbase.lib.ComparableExtensions - java:/Objects/org.eclipse.xtext.xbase.lib.DoubleExtensions - java:/Objects/org.eclipse.xtext.xbase.lib.FloatExtensions - java:/Objects/java.lang.Float - java:/Objects/org.eclipse.xtext.xbase.lib.FunctionExtensions - java:/Objects/org.eclipse.xtext.xbase.lib.Functions - java:/Objects/org.eclipse.xtext.xbase.lib.IntegerExtensions - java:/Objects/org.eclipse.xtext.xbase.lib.ExclusiveRange - java:/Objects/org.eclipse.xtext.xbase.lib.IntegerRange - java:/Objects/org.eclipse.xtext.xbase.lib.IterableExtensions - java:/Objects/org.eclipse.xtext.xbase.lib.IteratorExtensions - java:/Objects/com.google.common.collect.Iterators - java:/Objects/com.google.common.collect.AbstractIndexedListIterator - java:/Objects/com.google.common.collect.PeekingIterator - java:/Objects/org.eclipse.xtext.xbase.lib.ListExtensions - java:/Objects/org.eclipse.xtext.xbase.lib.LongExtensions - java:/Objects/org.eclipse.xtext.xbase.lib.MapExtensions - java:/Objects/org.eclipse.xtext.xbase.lib.internal.UnmodifiableMergingMapView - java:/Objects/org.eclipse.xtext.xbase.lib.ObjectExtensions - java:/Objects/com.google.common.base.Objects - java:/Objects/com.google.common.base.ExtraObjectsMethodsForWeb - java:/Objects/org.eclipse.xtext.xbase.lib.ProcedureExtensions - java:/Objects/org.eclipse.xtext.xbase.lib.ShortExtensions - java:/Objects/java.lang.Short - java:/Objects/org.eclipse.xtext.xbase.lib.StringExtensions - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bold - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - KEEP_LOCATION - KEEP_SIZE - KEEP_RATIO - - backgroundColor - foregroundColor - - - - - - - - - - - - - - - - KEEP_LOCATION - KEEP_SIZE - KEEP_RATIO - - labelColor - backgroundColor - foregroundColor - - - - - - - - - - - - - - - - KEEP_LOCATION - KEEP_SIZE - KEEP_RATIO - - backgroundColor - foregroundColor - - - - - - - - KEEP_LOCATION - KEEP_SIZE - KEEP_RATIO - - backgroundColor - foregroundColor - - - - - - - - - - - - - - - - - - - - - - - - - - bold - - - - - - - - - - - bold - - - - - - - - - - - - labelSize - - - labelSize - - - - - - - - - - - - - - - - - - - - - labelSize - - - labelSize - - - - - - - - - - labelSize - - - labelSize - - - - - - - - - - labelSize - - - labelSize - - - - - - - - - - - italic - - - - - - - - - - - - - - diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/model/modes3.ecore b/Domains/ca.mcgill.rtgmrt.example.modes3/model/modes3.ecore index aa50b778..f7cb28be 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/model/modes3.ecore +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/model/modes3.ecore @@ -13,7 +13,7 @@ + eType="#//SimpleSegment" containment="true"/> @@ -29,4 +29,5 @@ + diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/model/modes3.genmodel b/Domains/ca.mcgill.rtgmrt.example.modes3/model/modes3.genmodel index 1a6c7a84..1cd4ac41 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/model/modes3.genmodel +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/model/modes3.genmodel @@ -26,5 +26,6 @@ + diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/output/solution.partialinterpretation b/Domains/ca.mcgill.rtgmrt.example.modes3/output/solution.partialinterpretation deleted file mode 100644 index bbf46091..00000000 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/output/solution.partialinterpretation +++ /dev/null @@ -1,1068 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/output/solution1.gml b/Domains/ca.mcgill.rtgmrt.example.modes3/output/solution1.gml deleted file mode 100644 index 66b57d1a..00000000 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/output/solution1.gml +++ /dev/null @@ -1,1191 +0,0 @@ -graph -[ - node - [ - id 0 - graphics - [ - w 269.5 - h 54 - type "rectangle" - fill "#FFFFFF" - fill2 "#FFFFFF" - outline "#000000" - ] - LabelGraphics - [ - text "o 1" - outline "#000000" - fill "#FFFFFF" - fontSize 16 - fontName "Monospace" - autoSizePolicy "node_width" - anchor "t" - borderDistance 0.0 - ] - LabelGraphics - [ - text " - Modes3ModelRoot class DefinedPart - Modes3ModelRoot class - " - fontSize 14 - fontName "Consolas" - alignment "left" - anchor "tl" - borderDistance 6 - ] - ] - - node - [ - id 1 - graphics - [ - w 41.800000000000004 - h 26 - type "rectangle" - fill "#FFFFFF" - fill2 "#FFFFFF" - outline "#000000" - ] - LabelGraphics - [ - text "true" - outline "#000000" - fill "#FFFFFF" - fontSize 16 - fontName "Monospace" - autoSizePolicy "node_width" - anchor "t" - borderDistance 0.0 - ] - LabelGraphics - [ - text " - " - fontSize 14 - fontName "Consolas" - alignment "left" - anchor "tl" - borderDistance 6 - ] - ] - - node - [ - id 2 - graphics - [ - w 50.6 - h 26 - type "rectangle" - fill "#FFFFFF" - fill2 "#FFFFFF" - outline "#000000" - ] - LabelGraphics - [ - text "false" - outline "#000000" - fill "#FFFFFF" - fontSize 16 - fontName "Monospace" - autoSizePolicy "node_width" - anchor "t" - borderDistance 0.0 - ] - LabelGraphics - [ - text " - " - fontSize 14 - fontName "Consolas" - alignment "left" - anchor "tl" - borderDistance 6 - ] - ] - - node - [ - id 3 - graphics - [ - w 115.50000000000001 - h 54 - type "rectangle" - fill "#FFFFFF" - fill2 "#FFFFFF" - outline "#000000" - ] - LabelGraphics - [ - text "null" - outline "#000000" - fill "#FFFFFF" - fontSize 16 - fontName "Monospace" - autoSizePolicy "node_width" - anchor "t" - borderDistance 0.0 - ] - LabelGraphics - [ - text " - Segment class - Turnout class - " - fontSize 14 - fontName "Consolas" - alignment "left" - anchor "tl" - borderDistance 6 - ] - ] - - node - [ - id 4 - graphics - [ - w 100.10000000000001 - h 40 - type "rectangle" - fill "#FFFFFF" - fill2 "#FFFFFF" - outline "#000000" - ] - LabelGraphics - [ - text "null" - outline "#000000" - fill "#FFFFFF" - fontSize 16 - fontName "Monospace" - autoSizePolicy "node_width" - anchor "t" - borderDistance 0.0 - ] - LabelGraphics - [ - text " - Train class - " - fontSize 14 - fontName "Consolas" - alignment "left" - anchor "tl" - borderDistance 6 - ] - ] - - node - [ - id 5 - graphics - [ - w 115.50000000000001 - h 40 - type "rectangle" - fill "#FFFFFF" - fill2 "#FFFFFF" - outline "#000000" - ] - LabelGraphics - [ - text "null" - outline "#000000" - fill "#FFFFFF" - fontSize 16 - fontName "Monospace" - autoSizePolicy "node_width" - anchor "t" - borderDistance 0.0 - ] - LabelGraphics - [ - text " - Segment class - " - fontSize 14 - fontName "Consolas" - alignment "left" - anchor "tl" - borderDistance 6 - ] - ] - - node - [ - id 6 - graphics - [ - w 100.10000000000001 - h 40 - type "rectangle" - fill "#FFFFFF" - fill2 "#FFFFFF" - outline "#000000" - ] - LabelGraphics - [ - text "null" - outline "#000000" - fill "#FFFFFF" - fontSize 16 - fontName "Monospace" - autoSizePolicy "node_width" - anchor "t" - borderDistance 0.0 - ] - LabelGraphics - [ - text " - Train class - " - fontSize 14 - fontName "Consolas" - alignment "left" - anchor "tl" - borderDistance 6 - ] - ] - - node - [ - id 7 - graphics - [ - w 115.50000000000001 - h 40 - type "rectangle" - fill "#FFFFFF" - fill2 "#FFFFFF" - outline "#000000" - ] - LabelGraphics - [ - text "null" - outline "#000000" - fill "#FFFFFF" - fontSize 16 - fontName "Monospace" - autoSizePolicy "node_width" - anchor "t" - borderDistance 0.0 - ] - LabelGraphics - [ - text " - Segment class - " - fontSize 14 - fontName "Consolas" - alignment "left" - anchor "tl" - borderDistance 6 - ] - ] - - node - [ - id 8 - graphics - [ - w 100.10000000000001 - h 40 - type "rectangle" - fill "#FFFFFF" - fill2 "#FFFFFF" - outline "#000000" - ] - LabelGraphics - [ - text "null" - outline "#000000" - fill "#FFFFFF" - fontSize 16 - fontName "Monospace" - autoSizePolicy "node_width" - anchor "t" - borderDistance 0.0 - ] - LabelGraphics - [ - text " - Train class - " - fontSize 14 - fontName "Consolas" - alignment "left" - anchor "tl" - borderDistance 6 - ] - ] - - node - [ - id 9 - graphics - [ - w 115.50000000000001 - h 40 - type "rectangle" - fill "#FFFFFF" - fill2 "#FFFFFF" - outline "#000000" - ] - LabelGraphics - [ - text "null" - outline "#000000" - fill "#FFFFFF" - fontSize 16 - fontName "Monospace" - autoSizePolicy "node_width" - anchor "t" - borderDistance 0.0 - ] - LabelGraphics - [ - text " - Segment class - " - fontSize 14 - fontName "Consolas" - alignment "left" - anchor "tl" - borderDistance 6 - ] - ] - - node - [ - id 10 - graphics - [ - w 100.10000000000001 - h 40 - type "rectangle" - fill "#FFFFFF" - fill2 "#FFFFFF" - outline "#000000" - ] - LabelGraphics - [ - text "null" - outline "#000000" - fill "#FFFFFF" - fontSize 16 - fontName "Monospace" - autoSizePolicy "node_width" - anchor "t" - borderDistance 0.0 - ] - LabelGraphics - [ - text " - Train class - " - fontSize 14 - fontName "Consolas" - alignment "left" - anchor "tl" - borderDistance 6 - ] - ] - - node - [ - id 11 - graphics - [ - w 115.50000000000001 - h 40 - type "rectangle" - fill "#FFFFFF" - fill2 "#FFFFFF" - outline "#000000" - ] - LabelGraphics - [ - text "null" - outline "#000000" - fill "#FFFFFF" - fontSize 16 - fontName "Monospace" - autoSizePolicy "node_width" - anchor "t" - borderDistance 0.0 - ] - LabelGraphics - [ - text " - Segment class - " - fontSize 14 - fontName "Consolas" - alignment "left" - anchor "tl" - borderDistance 6 - ] - ] - - node - [ - id 12 - graphics - [ - w 100.10000000000001 - h 40 - type "rectangle" - fill "#FFFFFF" - fill2 "#FFFFFF" - outline "#000000" - ] - LabelGraphics - [ - text "null" - outline "#000000" - fill "#FFFFFF" - fontSize 16 - fontName "Monospace" - autoSizePolicy "node_width" - anchor "t" - borderDistance 0.0 - ] - LabelGraphics - [ - text " - Train class - " - fontSize 14 - fontName "Consolas" - alignment "left" - anchor "tl" - borderDistance 6 - ] - ] - - node - [ - id 13 - graphics - [ - w 15.400000000000002 - h 26 - type "rectangle" - fill "#FFFFFF" - fill2 "#FFFFFF" - outline "#000000" - ] - LabelGraphics - [ - text "?" - outline "#000000" - fill "#FFFFFF" - fontSize 16 - fontName "Monospace" - autoSizePolicy "node_width" - anchor "t" - borderDistance 0.0 - ] - LabelGraphics - [ - text " - " - fontSize 14 - fontName "Consolas" - alignment "left" - anchor "tl" - borderDistance 6 - ] - ] - - node - [ - id 14 - graphics - [ - w 15.400000000000002 - h 26 - type "rectangle" - fill "#FFFFFF" - fill2 "#FFFFFF" - outline "#000000" - ] - LabelGraphics - [ - text "?" - outline "#000000" - fill "#FFFFFF" - fontSize 16 - fontName "Monospace" - autoSizePolicy "node_width" - anchor "t" - borderDistance 0.0 - ] - LabelGraphics - [ - text " - " - fontSize 14 - fontName "Consolas" - alignment "left" - anchor "tl" - borderDistance 6 - ] - ] - - node - [ - id 15 - graphics - [ - w 15.400000000000002 - h 26 - type "rectangle" - fill "#FFFFFF" - fill2 "#FFFFFF" - outline "#000000" - ] - LabelGraphics - [ - text "?" - outline "#000000" - fill "#FFFFFF" - fontSize 16 - fontName "Monospace" - autoSizePolicy "node_width" - anchor "t" - borderDistance 0.0 - ] - LabelGraphics - [ - text " - " - fontSize 14 - fontName "Consolas" - alignment "left" - anchor "tl" - borderDistance 6 - ] - ] - - node - [ - id 16 - graphics - [ - w 103.4 - h 26 - type "rectangle" - fill "#FFFFFF" - fill2 "#FFFFFF" - outline "#000000" - ] - LabelGraphics - [ - text "New Objects" - outline "#000000" - fill "#FFFFFF" - fontSize 16 - fontName "Monospace" - autoSizePolicy "node_width" - anchor "t" - borderDistance 0.0 - ] - LabelGraphics - [ - text " - " - fontSize 14 - fontName "Consolas" - alignment "left" - anchor "tl" - borderDistance 6 - ] - ] - edge - [ - source 5 - target 3 - graphics - [ - fill "#000000" - targetArrow "standard" - ] - LabelGraphics - [ - text "connectedTo reference Segment" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 3 - target 5 - graphics - [ - fill "#000000" - targetArrow "standard" - ] - LabelGraphics - [ - text "connectedTo reference Segment" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 7 - target 3 - graphics - [ - fill "#000000" - targetArrow "standard" - ] - LabelGraphics - [ - text "connectedTo reference Segment" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 3 - target 7 - graphics - [ - fill "#000000" - targetArrow "standard" - ] - LabelGraphics - [ - text "connectedTo reference Segment" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 7 - target 9 - graphics - [ - fill "#000000" - targetArrow "standard" - ] - LabelGraphics - [ - text "connectedTo reference Segment" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 9 - target 7 - graphics - [ - fill "#000000" - targetArrow "standard" - ] - LabelGraphics - [ - text "connectedTo reference Segment" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 11 - target 5 - graphics - [ - fill "#000000" - targetArrow "standard" - ] - LabelGraphics - [ - text "connectedTo reference Segment" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 5 - target 11 - graphics - [ - fill "#000000" - targetArrow "standard" - ] - LabelGraphics - [ - text "connectedTo reference Segment" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 5 - target 6 - graphics - [ - fill "#000000" - targetArrow "standard" - ] - LabelGraphics - [ - text "occupiedBy reference Segment" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 3 - target 4 - graphics - [ - fill "#000000" - targetArrow "standard" - ] - LabelGraphics - [ - text "occupiedBy reference Segment" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 7 - target 8 - graphics - [ - fill "#000000" - targetArrow "standard" - ] - LabelGraphics - [ - text "occupiedBy reference Segment" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 9 - target 10 - graphics - [ - fill "#000000" - targetArrow "standard" - ] - LabelGraphics - [ - text "occupiedBy reference Segment" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 11 - target 12 - graphics - [ - fill "#000000" - targetArrow "standard" - ] - LabelGraphics - [ - text "occupiedBy reference Segment" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 0 - target 4 - graphics - [ - fill "#000000" - width 3 - targetArrow "standard" - ] - LabelGraphics - [ - text "trains reference Modes3ModelRoot" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 0 - target 6 - graphics - [ - fill "#000000" - width 3 - targetArrow "standard" - ] - LabelGraphics - [ - text "trains reference Modes3ModelRoot" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 0 - target 8 - graphics - [ - fill "#000000" - width 3 - targetArrow "standard" - ] - LabelGraphics - [ - text "trains reference Modes3ModelRoot" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 0 - target 10 - graphics - [ - fill "#000000" - width 3 - targetArrow "standard" - ] - LabelGraphics - [ - text "trains reference Modes3ModelRoot" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 0 - target 12 - graphics - [ - fill "#000000" - width 3 - targetArrow "standard" - ] - LabelGraphics - [ - text "trains reference Modes3ModelRoot" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 0 - target 5 - graphics - [ - fill "#000000" - width 3 - targetArrow "standard" - ] - LabelGraphics - [ - text "segments reference Modes3ModelRoot" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 0 - target 7 - graphics - [ - fill "#000000" - width 3 - targetArrow "standard" - ] - LabelGraphics - [ - text "segments reference Modes3ModelRoot" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 0 - target 9 - graphics - [ - fill "#000000" - width 3 - targetArrow "standard" - ] - LabelGraphics - [ - text "segments reference Modes3ModelRoot" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 0 - target 11 - graphics - [ - fill "#000000" - width 3 - targetArrow "standard" - ] - LabelGraphics - [ - text "segments reference Modes3ModelRoot" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 0 - target 3 - graphics - [ - fill "#000000" - width 3 - targetArrow "standard" - ] - LabelGraphics - [ - text "turnouts reference Modes3ModelRoot" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 3 - target 9 - graphics - [ - fill "#000000" - targetArrow "standard" - ] - LabelGraphics - [ - text "straight reference Turnout" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 3 - target 5 - graphics - [ - fill "#000000" - targetArrow "standard" - ] - LabelGraphics - [ - text "divergent reference Turnout" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 6 - target 5 - graphics - [ - fill "#000000" - targetArrow "standard" - ] - LabelGraphics - [ - text "location reference Train" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 4 - target 3 - graphics - [ - fill "#000000" - targetArrow "standard" - ] - LabelGraphics - [ - text "location reference Train" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 8 - target 7 - graphics - [ - fill "#000000" - targetArrow "standard" - ] - LabelGraphics - [ - text "location reference Train" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 10 - target 9 - graphics - [ - fill "#000000" - targetArrow "standard" - ] - LabelGraphics - [ - text "location reference Train" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] - edge - [ - source 12 - target 11 - graphics - [ - fill "#000000" - targetArrow "standard" - ] - LabelGraphics - [ - text "location reference Train" - fontSize 14 - fontName "Consolas" - configuration "AutoFlippingLabel" - model "six_pos" - position "thead" - ] - ] -] - diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/output/solution1.partialinterpretation b/Domains/ca.mcgill.rtgmrt.example.modes3/output/solution1.partialinterpretation deleted file mode 100644 index 8b50e17f..00000000 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/output/solution1.partialinterpretation +++ /dev/null @@ -1,1037 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/output/solution1.png b/Domains/ca.mcgill.rtgmrt.example.modes3/output/solution1.png deleted file mode 100644 index b6fa6e4e..00000000 Binary files a/Domains/ca.mcgill.rtgmrt.example.modes3/output/solution1.png and /dev/null differ diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/plugin.xml b/Domains/ca.mcgill.rtgmrt.example.modes3/plugin.xml index 7341e19c..a105a729 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/plugin.xml +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/plugin.xml @@ -6,21 +6,19 @@ - - - - - + + + diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql index 982e6cec..b8841928 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql @@ -2,11 +2,6 @@ package modes3.queries import "http://www.ece.mcgill.ca/wcet/modes3" -@Constraint(message = "turnoutInSegments", severity = "error", key = { T }) -pattern turnoutInSegments(T : Turnout) { - Modes3ModelRoot.segments(_, T); -} - pattern connectedTo(S1 : Segment, S2 : Segment) { Segment.connectedTo(S1, S2); } @@ -39,10 +34,6 @@ pattern turnoutOutputsAreSame(T : Turnout) { Turnout.divergent(T, S); } -pattern turnout(T : Turnout) { - Turnout(T); -} - pattern output(S1 : Segment, S2 : Segment) { Segment.connectedTo(S1, S2); } or { @@ -56,8 +47,7 @@ pattern output(S1 : Segment, S2 : Segment) { //} @Constraint(message = "tooManyInputsOfSegment", severity = "error", key = { S }) -pattern tooManyInputsOfSegment(S : Segment) { - neg find turnout(S); +pattern tooManyInputsOfSegment(S : SimpleSegment) { find output(I1, S); find output(I2, S); find output(I3, S); @@ -74,30 +64,38 @@ pattern turnoutConnectedToBothOutputs(T : Turnout) { Segment.connectedTo(T, Divergent); } -pattern extraInputOfTurnout(T : Turnout, S : Segment) { - Turnout.straight(T, Straight); - Turnout.divergent(T, Divergent); - find output(S, T); - S != Straight; - S != Divergent; +pattern adjacent(S1 : Segment, S2 : Segment) { + find output(S1, S2); +} or { + find turnoutOutput(S2, S1); } -@Constraint(message = "noExtraInputOfTurnout", severity = "error", key = { T }) -pattern noExtraInputOfTurnout(T : Turnout) { - neg find extraInputOfTurnout(T, _); +@Constraint(message = "turnoutConnectedToBothOutputs", severity = "error", key = { T }) +pattern tooManyInputsOfTurnout(T : Turnout) { + find adjacent(I1, T); + find adjacent(I2, T); + find adjacent(I3, T); + find adjacent(I4, T); + I1 != I2; + I1 != I3; + I1 != I4; + I2 != I3; + I2 != I4; + I3 != I4; } -@Constraint(message = "tooManyExtraInputsOfTurnout", severity = "error", key = { T }) -pattern tooManyExtraInputsOfTurnout(T : Turnout) { - find extraInputOfTurnout(T, I1); - find extraInputOfTurnout(T, I2); +pattern inputsOfTurnout(T : Turnout) { + find adjacent(I1, T); + find adjacent(I2, T); + find adjacent(I3, T); I1 != I2; + I1 != I3; + I2 != I3; } -pattern adjacent(S1 : Segment, S2 : Segment) { - find output(S1, S2); -} or { - find turnoutOutput(S2, S1); +@Constraint(message = "tooFewInputsOfTurnout", severity = "error", key = { T }) +pattern tooFewInputsOfTurnout(T : Turnout) { + neg find inputsOfTurnout(T); } pattern reachable(S1 : Segment, S2 : Segment) { diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/Modes3ModelGenerator.xtend b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/Modes3ModelGenerator.xtend index 71d1798f..fac7c496 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/Modes3ModelGenerator.xtend +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/Modes3ModelGenerator.xtend @@ -8,6 +8,7 @@ import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2LogicConfiguration import hu.bme.mit.inf.dslreasoner.ecore2logic.EcoreMetamodelDescriptor import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.Ecore2logicannotationsFactory import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.Ecore2logicannotationsPackage +import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicProblemBuilder import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.LogiclanguagePackage import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeDefinition @@ -22,6 +23,7 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Polyhedr import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedralScopePropagatorSolver import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic.InstanceModel2Logic +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.BinaryElementRelationLink import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialComplexTypeInterpretation import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationPackage @@ -44,8 +46,6 @@ import org.eclipse.viatra.query.runtime.api.ViatraQueryEngineOptions import org.eclipse.viatra.query.runtime.localsearch.matcher.integration.LocalSearchEMFBackendFactory import org.eclipse.viatra.query.runtime.rete.matcher.ReteBackendFactory import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor -import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RelationDefinition -import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.BinaryElementRelationLink @FinalFieldsConstructor class Modes3ModelGenerator { @@ -92,22 +92,32 @@ class Modes3ModelGenerator { minNewElements = modelSize maxNewElements = modelSize minNewElementsByType => [ - put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.turnout), 1) +// put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.turnout), 5) ] maxNewElementsByType => [ put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.train), 5) + put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.turnout), 5) ] ] - solutionScope.numberOfRequiredSolutions = 1 + solutionScope => [ + numberOfRequiredSolutions = 1 + ] + scopeWeight = 5 nameNewElements = false typeInferenceMethod = TypeInferenceMethod.PreliminaryAnalysis - stateCoderStrategy = StateCoderStrategy::Neighbourhood + stateCoderStrategy = StateCoderStrategy.PairwiseNeighbourhood scopePropagatorStrategy = new ScopePropagatorStrategy.Polyhedral( PolyhedralScopePropagatorConstraints.Relational, PolyhedralScopePropagatorSolver.Clp) -// unitPropagationPatternGenerators += new Modes3UnitPropagationGenerator(ecore2Logic, metamodelLogic.trace) - debugConfiguration.partialInterpretatioVisualiser = null + hints += new Modes3TypeScopeHint(ecore2Logic, metamodelLogic.trace) + unitPropagationPatternGenerators += new Modes3UnitPropagationGenerator(ecore2Logic, metamodelLogic.trace) + debugConfiguration => [ + partialInterpretatioVisualiser = new GraphvizVisualiser +// partalInterpretationVisualisationFrequency = 50 + ] + documentationLevel = DocumentationLevel.NORMAL ] val workspace = new FileSystemWorkspace("output/", "") + workspace.writeModel(logic.output, "problem.logicproblem") val solution = solver.solve(logic.output, config, workspace) if (solution instanceof ModelResult) { println("Saving generated solutions") @@ -122,7 +132,6 @@ class Modes3ModelGenerator { workspace.writeText('''solution«representationNumber».gml''', gml) if (representation.newElements.size < 160) { if (representation instanceof PartialInterpretation) { - representation.problem.types.forEach[println(name)] val rootType = (representation.problem.types.findFirst [ name == "Modes3ModelRoot class DefinedPart" ] as TypeDefinition) @@ -198,10 +207,7 @@ class Modes3ModelGenerator { PartialinterpretationPackage.eINSTANCE.class Ecore2logicannotationsPackage.eINSTANCE.class Viatra2LogicAnnotationsPackage.eINSTANCE.class - Resource.Factory.Registry.INSTANCE.extensionToFactoryMap.put("ecore", new XMIResourceFactoryImpl) - Resource.Factory.Registry.INSTANCE.extensionToFactoryMap.put("logicproblem", new XMIResourceFactoryImpl) - Resource.Factory.Registry.INSTANCE.extensionToFactoryMap.put("partialinterpretation", - new XMIResourceFactoryImpl) + Resource.Factory.Registry.INSTANCE.extensionToFactoryMap.put("*", new XMIResourceFactoryImpl) } def static void main(String[] args) { diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/Modes3TypeScopeHint.xtend b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/Modes3TypeScopeHint.xtend new file mode 100644 index 00000000..94e5eb08 --- /dev/null +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/Modes3TypeScopeHint.xtend @@ -0,0 +1,79 @@ +package modes3.run + +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeExpressionBuilderFactory +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternGenerator +import java.util.Map +import modes3.Modes3Package +import modes3.queries.Adjacent +import org.eclipse.viatra.query.runtime.api.IPatternMatch +import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation + +class Modes3TypeScopeHint implements LinearTypeConstraintHint { + static val TURNOUT_NEIGHBOR_COUNT = "turnoutNeighborCount" + + val Type segmentType + val Type turnoutType + + new(extension Ecore2Logic ecore2Logic, Ecore2Logic_Trace ecore2LogicTrace) { + extension val Modes3Package = Modes3Package.eINSTANCE + segmentType = ecore2LogicTrace.TypeofEClass(segment) + turnoutType = ecore2LogicTrace.TypeofEClass(turnout) + } + + override getAdditionalPatterns(extension PatternGenerator patternGenerator, Map fqnToPQuery) { + ''' + pattern «TURNOUT_NEIGHBOR_COUNT»_helper(problem: LogicProblem, interpretation: PartialInterpretation, source: DefinedElement, target: DefinedElement) { + find interpretation(problem, interpretation); + find mustExist(problem, interpretation, source); + find mustExist(problem, interpretation, target); + «typeIndexer.referInstanceOf(turnoutType, Modality.MUST, "source")» + «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "target")» + «relationDefinitionIndexer.referPattern(fqnToPQuery.get(Adjacent.instance.fullyQualifiedName), #["source", "target"], Modality.MUST, true, false)» + } + + pattern «TURNOUT_NEIGHBOR_COUNT»(problem: LogicProblem, interpretation: PartialInterpretation, element: DefinedElement, N) { + find interpretation(problem, interpretation); + find mustExist(problem, interpretation, element); + «typeIndexer.referInstanceOf(turnoutType, Modality.MUST, "element")» + N == count find «TURNOUT_NEIGHBOR_COUNT»_helper(problem, interpretation, element, _); + } + ''' + } + + override createConstraintUpdater(LinearTypeExpressionBuilderFactory builderFactory) { + val turnoutNeighborCountMatcher = builderFactory.createMatcher(TURNOUT_NEIGHBOR_COUNT) + val newNeighbors = builderFactory.createBuilder.add(1, segmentType).build + + return [ partialInterpretation | + val requiredNeighbbors = turnoutNeighborCountMatcher.getRemainingCount(partialInterpretation, 3) + newNeighbors.tightenLowerBound(requiredNeighbbors) + ] + } + + private static def getRemainingCount(ViatraQueryMatcher matcher, + PartialInterpretation partialInterpretation, int capacity) { + val partialMatch = matcher.newEmptyMatch + partialMatch.set(0, partialInterpretation.problem) + partialMatch.set(1, partialInterpretation) + val iterator = matcher.streamAllMatches(partialMatch).iterator + var int max = 0 + while (iterator.hasNext) { + val match = iterator.next + val n = (match.get(3) as Integer).intValue + if (n < capacity) { + val required = capacity - n + if (max < required) { + max = required + } + } + } + max + } +} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/Modes3UnitPropagationGenerator.xtend b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/Modes3UnitPropagationGenerator.xtend index 61bd2814..953a21d4 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/Modes3UnitPropagationGenerator.xtend +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/Modes3UnitPropagationGenerator.xtend @@ -9,20 +9,21 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternGene import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.UnitPropagationPatternGenerator import java.util.Map import modes3.Modes3Package -import modes3.queries.ExtraInputOfTurnout +import modes3.queries.Adjacent import modes3.queries.Output -import modes3.queries.TurnoutOutput import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery import org.eclipse.xtend2.lib.StringConcatenationClient class Modes3UnitPropagationGenerator implements UnitPropagationPatternGenerator { static val MUST_NOT_CONNECTED_TO = "mustNotConnectedTo" - static val MUST_NOT_CONNECTED_TO_HELPER = "mustNotConnectedTo_helper" - static val MUST_NOT_TURNOUT_OUTPUT = "mustNotTurnoutOutput" static val MUST_NOT_STRAIGHT = "mustNotStraight" static val MUST_NOT_DIVERGENT = "mustNotDivergent" + static val MUST_CONNECTED_TO = "mustConnectedTo" + static val MUST_STRAIGHT = "mustStraight" + static val MUST_DIVERGENT = "mustDivergent" val Type segmentType + val Type simpleSegmentType val Type turnoutType val Relation connectedToRelation val Relation straightRelation @@ -31,6 +32,7 @@ class Modes3UnitPropagationGenerator implements UnitPropagationPatternGenerator new(extension Ecore2Logic ecore2Logic, Ecore2Logic_Trace ecore2LogicTrace) { extension val Modes3Package = Modes3Package.eINSTANCE segmentType = ecore2LogicTrace.TypeofEClass(segment) + simpleSegmentType = ecore2LogicTrace.TypeofEClass(simpleSegment) turnoutType = ecore2LogicTrace.TypeofEClass(turnout) connectedToRelation = ecore2LogicTrace.relationOfReference(segment_ConnectedTo) straightRelation = ecore2LogicTrace.relationOfReference(turnout_Straight) @@ -38,7 +40,11 @@ class Modes3UnitPropagationGenerator implements UnitPropagationPatternGenerator } override getMustPatterns() { - emptyMap + #{ + connectedToRelation -> MUST_CONNECTED_TO, + straightRelation -> MUST_STRAIGHT, + divergentRelation -> MUST_DIVERGENT + } } override getMustNotPatterns() { @@ -55,150 +61,356 @@ class Modes3UnitPropagationGenerator implements UnitPropagationPatternGenerator source: DefinedElement, target: DefinedElement ''' - val StringConcatenationClient commonParameterConstraints = ''' + val StringConcatenationClient commonMustParameterConstraints = ''' find interpretation(problem, interpretation); find mustExist(problem, interpretation, source); find mustExist(problem, interpretation, target); ''' + + val StringConcatenationClient commonMayParameterConstraints = ''' + find interpretation(problem, interpretation); + find mayExist(problem, interpretation, source); + find mayExist(problem, interpretation, target); + ''' ''' - pattern «MUST_NOT_CONNECTED_TO_HELPER»(«parameters») { - // connectedToReflexive unit propagation - «commonParameterConstraints» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "source")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "target")» - source == target; + pattern mayInput(«parameters») { + «commonMayParameterConstraints» + «typeIndexer.referInstanceOf(segmentType, Modality.MAY, "target")» + «relationDefinitionIndexer.referPattern(fqnToPQuery.get(Adjacent.instance.fullyQualifiedName), #["target", "source"], Modality.MAY, true, false)» + neg «referRelation(straightRelation, "target", "source", Modality.MUST, fqnToPQuery)» + neg «referRelation(straightRelation, "target", "source", Modality.MUST, fqnToPQuery)» + } + + pattern multipleMayInput(problem: LogicProblem, interpretation: PartialInterpretation, + target: DefinedElement) { + find interpretation(problem, interpretation); + find mustExist(problem, interpretation, target); + find mayInput(problem, interpretaton, source1, target); + find mayInput(problem, interpretaton, source2, target); + neg find mustEquivalent(problem, interpretation, source1, source2); + } + + pattern multipleMayStraight(problem: LogicProblem, interpretation: PartialInterpretation, + source: DefinedElement) { + find interpretation(problem, interpretation); + find mustExist(problem, interpretation, source); + «typeIndexer.referInstanceOf(turnoutType, Modality.MAY, "source")» + «referRelation(straightRelation, "source", "target1", Modality.MAY, fqnToPQuery)» + «referRelation(straightRelation, "source", "target2", Modality.MAY, fqnToPQuery)» + neg find mustEquivalent(problem, interpretation, target1, target2); + } + + pattern multipleMayDivergent(problem: LogicProblem, interpretation: PartialInterpretation, + source: DefinedElement) { + find interpretation(problem, interpretation); + find mustExist(problem, interpretation, source); + «typeIndexer.referInstanceOf(turnoutType, Modality.MAY, "source")» + «referRelation(divergentRelation, "source", "target1", Modality.MAY, fqnToPQuery)» + «referRelation(divergentRelation, "source", "target2", Modality.MAY, fqnToPQuery)» + neg find mustEquivalent(problem, interpretation, target1, target2); + } + + pattern «MUST_CONNECTED_TO»(«parameters») { + «commonMustParameterConstraints» + «typeIndexer.referInstanceOf(segmentType, Modality.MAY, "target")» + find mayInput(problem, interpretaton, source, target); + neg find multipleMayInput(problem, interpretaton, target); + «referRelation(connectedToRelation, "source", "target", Modality.MAY, fqnToPQuery)» + neg «referRelation(connectedToRelation, "source", "target", Modality.MUST, fqnToPQuery)» + neg «referRelation(straightRelation, "source", "target", Modality.MAY, fqnToPQuery)» + neg «referRelation(divergentRelation, "source", "target", Modality.MAY, fqnToPQuery)» + } + + pattern «MUST_STRAIGHT»(«parameters») { + «commonMustParameterConstraints» + neg «referRelation(straightRelation, "source", "_", Modality.MUST, fqnToPQuery)» + neg find multipleMayStraight(problem, interpretation, source); + «referRelation(straightRelation, "source", "target", Modality.MAY, fqnToPQuery)» + neg «referRelation(straightRelation, "source", "target", Modality.MUST, fqnToPQuery)» } or { - // tooManyInputsOfSegment unit propagation - «commonParameterConstraints» + «commonMustParameterConstraints» + «typeIndexer.referInstanceOf(segmentType, Modality.MAY, "target")» + find mayInput(problem, interpretaton, source, target); + neg find multipleMayInput(problem, interpretaton, target); + neg «referRelation(connectedToRelation, "source", "target", Modality.MAY, fqnToPQuery)» + «referRelation(straightRelation, "source", "target", Modality.MAY, fqnToPQuery)» + neg «referRelation(straightRelation, "source", "target", Modality.MUST, fqnToPQuery)» + neg «referRelation(divergentRelation, "source", "target", Modality.MAY, fqnToPQuery)» + } + + pattern «MUST_DIVERGENT»(«parameters») { + «commonMustParameterConstraints» + neg «referRelation(divergentRelation, "source", "_", Modality.MUST, fqnToPQuery)» + neg find multipleMayDivergent(problem, interpretation, source); + «referRelation(divergentRelation, "source", "target", Modality.MAY, fqnToPQuery)» + neg «referRelation(divergentRelation, "source", "target", Modality.MUST, fqnToPQuery)» + } or { + «commonMustParameterConstraints» + «typeIndexer.referInstanceOf(segmentType, Modality.MAY, "target")» + find mayInput(problem, interpretaton, source, target); + neg find multipleMayInput(problem, interpretaton, target); + neg «referRelation(connectedToRelation, "source", "target", Modality.MAY, fqnToPQuery)» + neg «referRelation(straightRelation, "source", "target", Modality.MAY, fqnToPQuery)» + «referRelation(divergentRelation, "source", "target", Modality.MAY, fqnToPQuery)» + neg «referRelation(divergentRelation, "source", "target", Modality.MUST, fqnToPQuery)» + } + + pattern turnoutOutput_must_to_true_by_straight(«parameters», T : DefinedElement, S : DefinedElement) { + «commonMayParameterConstraints» + «typeIndexer.referInstanceOf(turnoutType, Modality.MAY, "source")» + «typeIndexer.referInstanceOf(segmentType, Modality.MAY, "target")» + T == source; + S == target; + } + + pattern turnoutOutput_must_to_true_by_divergent(«parameters», T : DefinedElement, S : DefinedElement) { + «commonMayParameterConstraints» + «typeIndexer.referInstanceOf(turnoutType, Modality.MAY, "source")» + «typeIndexer.referInstanceOf(segmentType, Modality.MAY, "target")» + T == source; + S == target; + } + + pattern output_must_to_true_by_connectedTo(«parameters», S1 : DefinedElement, S2 : DefinedElement) { + «commonMayParameterConstraints» + «typeIndexer.referInstanceOf(segmentType, Modality.MAY, "source")» + «typeIndexer.referInstanceOf(segmentType, Modality.MAY, "target")» + S1 == source; + S2 == target; + } + + pattern output_must_to_true_by_straight(«parameters», S1 : DefinedElement, S2 : DefinedElement) { + find turnoutOutput_must_to_true_by_straight(problem, interpretation, source, target, S1, S2); + } + + pattern output_must_to_true_by_divergent(«parameters», S1 : DefinedElement, S2 : DefinedElement) { + find turnoutOutput_must_to_true_by_divergent(problem, interpretation, source, target, S1, S2); + } + + pattern adjacent_must_to_true_by_connectedTo(«parameters», S1 : DefinedElement, S2 : DefinedElement) { + find output_must_to_true_by_connectedTo(problem, interpretation, source, target, S1, S2); + } + + pattern adjacent_must_to_true_by_straight(«parameters», S1 : DefinedElement, S2 : DefinedElement) { + find output_must_to_true_by_straight(problem, interpretation, source, target, S1, S2); + } or { + find turnoutOutput_must_to_true_by_straight(problem, interpretation, source, target, S2, S1); + } + + pattern adjacent_must_to_true_by_divergent(«parameters», S1 : DefinedElement, S2 : DefinedElement) { + find output_must_to_true_by_divergent(problem, interpretation, source, target, S1, S2); + } or { + find turnoutOutput_must_to_true_by_divergent(problem, interpretation, source, target, S2, S1); + } + + pattern connectedToReflexive_must_to_true_by_connectedTo(«parameters», S : DefinedElement) { + find mustExist(problem, interpretation, source); «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "source")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "target")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "input1")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "input2")» - neg «typeIndexer.referInstanceOf(turnoutType, Modality.MAY, "source")» - «relationDefinitionIndexer.referPattern(fqnToPQuery.get(Output.instance.fullyQualifiedName), #["input1", "source"], Modality.MUST, true, false)» - «relationDefinitionIndexer.referPattern(fqnToPQuery.get(Output.instance.fullyQualifiedName), #["input2", "source"], Modality.MUST, true, false)» - input1 != input2; - input1 != target; - input2 != target; - } or { - // turnoutConnectedToBothOutputs unit propagation 1 - «commonParameterConstraints» - «typeIndexer.referInstanceOf(turnoutType, Modality.MUST, "source")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "target")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "divergent")» - «referRelation(straightRelation, "source", "target", Modality.MUST, fqnToPQuery)» - «referRelation(divergentRelation, "source", "divergent", Modality.MUST, fqnToPQuery)» - «referRelation(connectedToRelation, "source", "divergent", Modality.MUST, fqnToPQuery)» - } or { - // turnoutConnectedToBothOutputs unit propagation 2 - «commonParameterConstraints» - «typeIndexer.referInstanceOf(turnoutType, Modality.MUST, "source")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "target")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "straight")» - «referRelation(straightRelation, "source", "straight", Modality.MUST, fqnToPQuery)» - «referRelation(divergentRelation, "source", "target", Modality.MUST, fqnToPQuery)» - «referRelation(connectedToRelation, "source", "straight", Modality.MUST, fqnToPQuery)» - } or { - // tooManyExtraInputsOfTurnout unit propagation - «commonParameterConstraints» - «typeIndexer.referInstanceOf(turnoutType, Modality.MUST, "source")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "target")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "extraInput")» - «relationDefinitionIndexer.referPattern(fqnToPQuery.get(TurnoutOutput.instance.fullyQualifiedName), #["source", "target"], Modality.MAY, false, false)» - «relationDefinitionIndexer.referPattern(fqnToPQuery.get(ExtraInputOfTurnout.instance.fullyQualifiedName), #["source", "extraInput"], Modality.MUST, true, false)» - target != extraInput; + S == source; + S == target; } - pattern «MUST_NOT_CONNECTED_TO»(«parameters») { - find «MUST_NOT_CONNECTED_TO_HELPER»(problem, interpretation, source, target); + pattern outputReflexive_must_to_true_by_straight(«parameters», T : DefinedElement) { + find turnoutOutput_must_to_true_by_straight(problem, interpretation, source, target, T, T); + } + + pattern outputReflexive_must_to_true_by_divergent(«parameters», T : DefinedElement) { + find turnoutOutput_must_to_true_by_divergent(problem, interpretation, source, target, T, T); + } + + pattern turnoutOutputsAreSame_must_to_true_by_straight(«parameters», T : DefinedElement) { + «commonMayParameterConstraints» + «typeIndexer.referInstanceOf(turnoutType, Modality.MAY, "source")» + «typeIndexer.referInstanceOf(segmentType, Modality.MAY, "target")» + T == source; + S == target; + «referRelation(divergentRelation, "T", "S", Modality.MUST, fqnToPQuery)» + } + + pattern turnoutOutputsAreSame_must_to_true_by_divergent(«parameters», T : DefinedElement) { + «commonMayParameterConstraints» + «typeIndexer.referInstanceOf(turnoutType, Modality.MAY, "source")» + «typeIndexer.referInstanceOf(segmentType, Modality.MAY, "target")» + T == source; + S == target; + «referRelation(straightRelation, "T", "S", Modality.MUST, fqnToPQuery)» + } + + pattern tooManyInputsOfSegment_must_to_true_by_connectedTo(«parameters», S : DefinedElement) { + find mustExist(problem, interpretation, S); + «typeIndexer.referInstanceOf(simpleSegmentType, Modality.MUST, "S")» + find output_must_to_true_by_connectedTo(problem, interpretation, source, target, I1, S); + «relationDefinitionIndexer.referPattern(fqnToPQuery.get(Output.instance.fullyQualifiedName), #["I2", "S"], Modality.MUST, true, false)» + «relationDefinitionIndexer.referPattern(fqnToPQuery.get(Output.instance.fullyQualifiedName), #["I3", "S"], Modality.MUST, true, false)» + I1 != I2; + I1 != I3; + I2 != I3; + } + + pattern tooManyInputsOfSegment_must_to_true_by_straight(«parameters», S : DefinedElement) { + find mustExist(problem, interpretation, S); + «typeIndexer.referInstanceOf(simpleSegmentType, Modality.MUST, "S")» + find output_must_to_true_by_straight(problem, interpretation, source, target, I1, S); + «relationDefinitionIndexer.referPattern(fqnToPQuery.get(Output.instance.fullyQualifiedName), #["I2", "S"], Modality.MUST, true, false)» + «relationDefinitionIndexer.referPattern(fqnToPQuery.get(Output.instance.fullyQualifiedName), #["I3", "S"], Modality.MUST, true, false)» + I1 != I2; + I1 != I3; + I2 != I3; + } + + pattern tooManyInputsOfSegment_must_to_true_by_divergent(«parameters», S : DefinedElement) { + find mustExist(problem, interpretation, S); + «typeIndexer.referInstanceOf(simpleSegmentType, Modality.MUST, "S")» + find output_must_to_true_by_divergent(problem, interpretation, source, target, I1, S); + «relationDefinitionIndexer.referPattern(fqnToPQuery.get(Output.instance.fullyQualifiedName), #["I2", "S"], Modality.MUST, true, false)» + «relationDefinitionIndexer.referPattern(fqnToPQuery.get(Output.instance.fullyQualifiedName), #["I3", "S"], Modality.MUST, true, false)» + I1 != I2; + I1 != I3; + I2 != I3; + } + + pattern turnoutConnectedToBothOutputs_must_to_true_by_connectedTo(«parameters», T : DefinedElement) { + «commonMayParameterConstraints» + find mustExist(problem, interpretation, Straight); + find mustExist(problem, interpretation, Divergent); + «typeIndexer.referInstanceOf(turnoutType, Modality.MAY, "source")» + «typeIndexer.referInstanceOf(segmentType, Modality.MAY, "target")» + «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "Straight")» + «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "Divergent")» + «referRelation(straightRelation, "T", "Straight", Modality.MUST, fqnToPQuery)» + «referRelation(divergentRelation, "T", "Divergent", Modality.MUST, fqnToPQuery)» + T == source; + Straight == target; + «referRelation(connectedToRelation, "T", "Divergent", Modality.MUST, fqnToPQuery)» } or { - find «MUST_NOT_CONNECTED_TO_HELPER»(problem, interpretation, target, source); + «commonMayParameterConstraints» + find mustExist(problem, interpretation, Straight); + find mustExist(problem, interpretation, Divergent); + «typeIndexer.referInstanceOf(turnoutType, Modality.MAY, "source")» + «typeIndexer.referInstanceOf(segmentType, Modality.MAY, "target")» + «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "Straight")» + «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "Divergent")» + «referRelation(straightRelation, "T", "Straight", Modality.MUST, fqnToPQuery)» + «referRelation(divergentRelation, "T", "Divergent", Modality.MUST, fqnToPQuery)» + «referRelation(connectedToRelation, "T", "Straight", Modality.MUST, fqnToPQuery)» + T == source; + Straight == target; } - pattern «MUST_NOT_TURNOUT_OUTPUT»(«parameters») { - // outputReflexive unit propagation - «commonParameterConstraints» - «typeIndexer.referInstanceOf(turnoutType, Modality.MUST, "source")» - «typeIndexer.referInstanceOf(turnoutType, Modality.MUST, "target")» - source == target; + pattern turnoutConnectedToBothOutputs_must_to_true_by_straight(«parameters», T : DefinedElement) { + «commonMayParameterConstraints» + find mustExist(problem, interpretation, Straight); + find mustExist(problem, interpretation, Divergent); + «typeIndexer.referInstanceOf(turnoutType, Modality.MAY, "source")» + «typeIndexer.referInstanceOf(segmentType, Modality.MAY, "target")» + «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "Straight")» + «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "Divergent")» + T == source; + Straight == target; + «referRelation(divergentRelation, "T", "Divergent", Modality.MUST, fqnToPQuery)» + «referRelation(connectedToRelation, "T", "Straight", Modality.MUST, fqnToPQuery)» + «referRelation(connectedToRelation, "T", "Divergent", Modality.MUST, fqnToPQuery)» + } + + pattern turnoutConnectedToBothOutputs_must_to_true_by_divergent(«parameters», T : DefinedElement) { + «commonMayParameterConstraints» + find mustExist(problem, interpretation, Straight); + find mustExist(problem, interpretation, Divergent); + «typeIndexer.referInstanceOf(turnoutType, Modality.MAY, "source")» + «typeIndexer.referInstanceOf(segmentType, Modality.MAY, "target")» + «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "Straight")» + «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "Divergent")» + «referRelation(straightRelation, "T", "Straight", Modality.MUST, fqnToPQuery)» + T == source; + Divergent == target; + «referRelation(connectedToRelation, "T", "Straight", Modality.MUST, fqnToPQuery)» + «referRelation(connectedToRelation, "T", "Divergent", Modality.MUST, fqnToPQuery)» + } + + pattern tooManyInputsOfTurnout_must_to_true_by_connectedTo(«parameters», T : DefinedElement) { + find mustExist(problem, interpretation, S); + «typeIndexer.referInstanceOf(turnoutType, Modality.MUST, "S")» + find adjacent_must_to_true_by_connectedTo(problem, interpretation, source, target, I1, S); + «relationDefinitionIndexer.referPattern(fqnToPQuery.get(Adjacent.instance.fullyQualifiedName), #["I2", "S"], Modality.MUST, true, false)» + «relationDefinitionIndexer.referPattern(fqnToPQuery.get(Adjacent.instance.fullyQualifiedName), #["I3", "S"], Modality.MUST, true, false)» + «relationDefinitionIndexer.referPattern(fqnToPQuery.get(Adjacent.instance.fullyQualifiedName), #["I4", "S"], Modality.MUST, true, false)» + I1 != I2; + I1 != I3; + I1 != I4; + I2 != I3; + I2 != I4; + I3 != I4; + } + + pattern tooManyInputsOfTurnout_must_to_true_by_straight(«parameters», T : DefinedElement) { + find mustExist(problem, interpretation, S); + «typeIndexer.referInstanceOf(turnoutType, Modality.MUST, "S")» + find adjacent_must_to_true_by_straight(problem, interpretation, source, target, I1, S); + «relationDefinitionIndexer.referPattern(fqnToPQuery.get(Adjacent.instance.fullyQualifiedName), #["I2", "S"], Modality.MUST, true, false)» + «relationDefinitionIndexer.referPattern(fqnToPQuery.get(Adjacent.instance.fullyQualifiedName), #["I3", "S"], Modality.MUST, true, false)» + «relationDefinitionIndexer.referPattern(fqnToPQuery.get(Adjacent.instance.fullyQualifiedName), #["I4", "S"], Modality.MUST, true, false)» + I1 != I2; + I1 != I3; + I1 != I4; + I2 != I3; + I2 != I4; + I3 != I4; + } + + pattern tooManyInputsOfTurnout_must_to_true_by_divergent(«parameters», T : DefinedElement) { + find mustExist(problem, interpretation, S); + «typeIndexer.referInstanceOf(turnoutType, Modality.MUST, "S")» + find adjacent_must_to_true_by_divergent(problem, interpretation, source, target, I1, S); + «relationDefinitionIndexer.referPattern(fqnToPQuery.get(Adjacent.instance.fullyQualifiedName), #["I2", "S"], Modality.MUST, true, false)» + «relationDefinitionIndexer.referPattern(fqnToPQuery.get(Adjacent.instance.fullyQualifiedName), #["I3", "S"], Modality.MUST, true, false)» + «relationDefinitionIndexer.referPattern(fqnToPQuery.get(Adjacent.instance.fullyQualifiedName), #["I4", "S"], Modality.MUST, true, false)» + I1 != I2; + I1 != I3; + I1 != I4; + I2 != I3; + I2 != I4; + I3 != I4; + } + + pattern «MUST_NOT_CONNECTED_TO»_helper(«parameters») { + find connectedToReflexive_must_to_true_by_connectedTo(problem, interpretation, source, target, _); } or { - // tooManyInputsOfSegment unit propagation - «commonParameterConstraints» - «typeIndexer.referInstanceOf(turnoutType, Modality.MUST, "source")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "target")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "input1")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "input2")» - neg «typeIndexer.referInstanceOf(turnoutType, Modality.MAY, "target")» - «relationDefinitionIndexer.referPattern(fqnToPQuery.get(Output.instance.fullyQualifiedName), #["input1", "target"], Modality.MUST, true, false)» - «relationDefinitionIndexer.referPattern(fqnToPQuery.get(Output.instance.fullyQualifiedName), #["input2", "target"], Modality.MUST, true, false)» - input1 != input2; - input1 != source; - input2 != source; + find tooManyInputsOfSegment_must_to_true_by_connectedTo(problem, interpretation, source, target, _); + } or { + find turnoutConnectedToBothOutputs_must_to_true_by_connectedTo(problem, interpretation, source, target, _); + } or { + find tooManyInputsOfTurnout_must_to_true_by_connectedTo(problem, interpretation, source, target, _); + } + + pattern «MUST_NOT_CONNECTED_TO»(«parameters») { + find «MUST_NOT_CONNECTED_TO»_helper(problem, interpretation, source, target); + } or { + find «MUST_NOT_CONNECTED_TO»_helper(problem, interpretation, target, source); } pattern «MUST_NOT_STRAIGHT»(«parameters») { - find «MUST_NOT_TURNOUT_OUTPUT»(problem, interpretation, source, target); - } or { - // turnoutOutputsAreSame unit propagation - «commonParameterConstraints» - «typeIndexer.referInstanceOf(turnoutType, Modality.MUST, "source")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "target")» - «referRelation(divergentRelation, "source", "target", Modality.MUST, fqnToPQuery)» - } or { - // turnoutConnectedToBothOutputs unit propagation - «commonParameterConstraints» - «typeIndexer.referInstanceOf(turnoutType, Modality.MUST, "source")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "target")» - «typeIndexer.referInstanceOf(turnoutType, Modality.MUST, "divergent")» - «referRelation(connectedToRelation, "source", "target", Modality.MUST, fqnToPQuery)» - «referRelation(divergentRelation, "source", "divergent", Modality.MUST, fqnToPQuery)» - «referRelation(connectedToRelation, "source", "divergent", Modality.MUST, fqnToPQuery)» - } or { - // tooManyExtraInputsOfTurnout unit propagation - «commonParameterConstraints» - «typeIndexer.referInstanceOf(turnoutType, Modality.MUST, "source")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "target")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "extraInput")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "potentialExtraInput")» - «relationDefinitionIndexer.referPattern(fqnToPQuery.get(ExtraInputOfTurnout.instance.fullyQualifiedName), #["source", "extraInput"], Modality.MUST, true, false)» - «referRelation(connectedToRelation, "source", "potentialExtraInput", Modality.MUST, fqnToPQuery)» - neg «referRelation(divergentRelation, "source", "potentialExtraInput", Modality.MAY, fqnToPQuery)» - extraInput != potentialExtraInput; - extraInput != target; - potentialExtraInput != target; + find outputReflexive_must_to_true_by_straight(problem, interpretation, source, target, _); + } or { + find turnoutOutputsAreSame_must_to_true_by_straight(problem, interpretation, source, target, _); + } or { + find tooManyInputsOfSegment_must_to_true_by_straight(problem, interpretation, source, target, _); + } or { + find turnoutConnectedToBothOutputs_must_to_true_by_straight(problem, interpretation, source, target, _); + } or { + find tooManyInputsOfTurnout_must_to_true_by_straight(problem, interpretation, source, target, _); } pattern «MUST_NOT_DIVERGENT»(«parameters») { - find «MUST_NOT_TURNOUT_OUTPUT»(problem, interpretation, source, target); - } or { - // turnoutOutputsAreSame unit propagation - «commonParameterConstraints» - «typeIndexer.referInstanceOf(turnoutType, Modality.MUST, "source")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "target")» - «referRelation(straightRelation, "source", "target", Modality.MUST, fqnToPQuery)» - } or { - // turnoutConnectedToBothOutputs unit propagation - «commonParameterConstraints» - «typeIndexer.referInstanceOf(turnoutType, Modality.MUST, "source")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "target")» - «typeIndexer.referInstanceOf(turnoutType, Modality.MUST, "straight")» - «referRelation(connectedToRelation, "source", "target", Modality.MUST, fqnToPQuery)» - «referRelation(straightRelation, "source", "straight", Modality.MUST, fqnToPQuery)» - «referRelation(connectedToRelation, "source", "straight", Modality.MUST, fqnToPQuery)» - } or { - // tooManyExtraInputsOfTurnout unit propagation - «commonParameterConstraints» - «typeIndexer.referInstanceOf(turnoutType, Modality.MUST, "source")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "target")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "extraInput")» - «typeIndexer.referInstanceOf(segmentType, Modality.MUST, "potentialExtraInput")» - «relationDefinitionIndexer.referPattern(fqnToPQuery.get(ExtraInputOfTurnout.instance.fullyQualifiedName), #["source", "extraInput"], Modality.MUST, true, false)» - «referRelation(connectedToRelation, "source", "potentialExtraInput", Modality.MUST, fqnToPQuery)» - neg «referRelation(straightRelation, "source", "potentialExtraInput", Modality.MAY, fqnToPQuery)» - extraInput != potentialExtraInput; - extraInput != target; - potentialExtraInput != target; + find outputReflexive_must_to_true_by_divergent(problem, interpretation, source, target, _); + } or { + find turnoutOutputsAreSame_must_to_true_by_divergent(problem, interpretation, source, target, _); + } or { + find tooManyInputsOfSegment_must_to_true_by_divergent(problem, interpretation, source, target, _); + } or { + find turnoutConnectedToBothOutputs_must_to_true_by_divergent(problem, interpretation, source, target, _); + } or { + find tooManyInputsOfTurnout_must_to_true_by_divergent(problem, interpretation, source, target, _); } ''' } diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/.gitignore b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/.gitignore index e3a0ad7e..b3e38571 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/.gitignore +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/.gitignore @@ -24,3 +24,10 @@ /.ExtraInputOfTurnout.java._trace /.NoExtraInputOfTurnout.java._trace /.TooManyExtraInputsOfTurnout.java._trace +/.TooManyInputsOfTurnout.java._trace +/.NonDivergentInputOfTurnout.java._trace +/.NonStraightInputOfTurnout.java._trace +/.TooManyNonDivergentInputsOfTurnout.java._trace +/.TooManyNonStraightInputsOfTurnout.java._trace +/.InputsOfTurnout.java._trace +/.TooFewInputsOfTurnout.java._trace diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/ExtraInputOfTurnout.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/ExtraInputOfTurnout.java deleted file mode 100644 index 62e2a54d..00000000 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/ExtraInputOfTurnout.java +++ /dev/null @@ -1,730 +0,0 @@ -/** - * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql - */ -package modes3.queries; - -import java.util.Arrays; -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.function.Consumer; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import modes3.Segment; -import modes3.Turnout; -import modes3.queries.Output; -import org.apache.log4j.Logger; -import org.eclipse.emf.ecore.EClass; -import org.eclipse.viatra.query.runtime.api.IPatternMatch; -import org.eclipse.viatra.query.runtime.api.IQuerySpecification; -import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine; -import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery; -import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification; -import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher; -import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch; -import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey; -import org.eclipse.viatra.query.runtime.emf.types.EStructuralFeatureInstancesKey; -import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint; -import org.eclipse.viatra.query.runtime.matchers.psystem.PBody; -import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable; -import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Equality; -import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter; -import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Inequality; -import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.PositivePatternCall; -import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint; -import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter; -import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection; -import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility; -import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple; -import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples; -import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil; - -/** - * A pattern-specific query specification that can instantiate Matcher in a type-safe way. - * - *

Original source: - *

- *         pattern extraInputOfTurnout(T : Turnout, S : Segment) {
- *         	Turnout.straight(T, Straight);
- *         	Turnout.divergent(T, Divergent);
- *         	find output(S, T);
- *         	S != Straight;
- *         	S != Divergent;
- *         }
- * 
- * - * @see Matcher - * @see Match - * - */ -@SuppressWarnings("all") -public final class ExtraInputOfTurnout extends BaseGeneratedEMFQuerySpecification { - /** - * Pattern-specific match representation of the modes3.queries.extraInputOfTurnout pattern, - * to be used in conjunction with {@link Matcher}. - * - *

Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned. - * Each instance is a (possibly partial) substitution of pattern parameters, - * usable to represent a match of the pattern in the result of a query, - * or to specify the bound (fixed) input parameters when issuing a query. - * - * @see Matcher - * - */ - public static abstract class Match extends BasePatternMatch { - private Turnout fT; - - private Segment fS; - - private static List parameterNames = makeImmutableList("T", "S"); - - private Match(final Turnout pT, final Segment pS) { - this.fT = pT; - this.fS = pS; - } - - @Override - public Object get(final String parameterName) { - switch(parameterName) { - case "T": return this.fT; - case "S": return this.fS; - default: return null; - } - } - - @Override - public Object get(final int index) { - switch(index) { - case 0: return this.fT; - case 1: return this.fS; - default: return null; - } - } - - public Turnout getT() { - return this.fT; - } - - public Segment getS() { - return this.fS; - } - - @Override - public boolean set(final String parameterName, final Object newValue) { - if (!isMutable()) throw new java.lang.UnsupportedOperationException(); - if ("T".equals(parameterName) ) { - this.fT = (Turnout) newValue; - return true; - } - if ("S".equals(parameterName) ) { - this.fS = (Segment) newValue; - return true; - } - return false; - } - - public void setT(final Turnout pT) { - if (!isMutable()) throw new java.lang.UnsupportedOperationException(); - this.fT = pT; - } - - public void setS(final Segment pS) { - if (!isMutable()) throw new java.lang.UnsupportedOperationException(); - this.fS = pS; - } - - @Override - public String patternName() { - return "modes3.queries.extraInputOfTurnout"; - } - - @Override - public List parameterNames() { - return ExtraInputOfTurnout.Match.parameterNames; - } - - @Override - public Object[] toArray() { - return new Object[]{fT, fS}; - } - - @Override - public ExtraInputOfTurnout.Match toImmutable() { - return isMutable() ? newMatch(fT, fS) : this; - } - - @Override - public String prettyPrint() { - StringBuilder result = new StringBuilder(); - result.append("\"T\"=" + prettyPrintValue(fT) + ", "); - result.append("\"S\"=" + prettyPrintValue(fS)); - return result.toString(); - } - - @Override - public int hashCode() { - return Objects.hash(fT, fS); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) { - return false; - } - if ((obj instanceof ExtraInputOfTurnout.Match)) { - ExtraInputOfTurnout.Match other = (ExtraInputOfTurnout.Match) obj; - return Objects.equals(fT, other.fT) && Objects.equals(fS, other.fS); - } else { - // this should be infrequent - if (!(obj instanceof IPatternMatch)) { - return false; - } - IPatternMatch otherSig = (IPatternMatch) obj; - return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray()); - } - } - - @Override - public ExtraInputOfTurnout specification() { - return ExtraInputOfTurnout.instance(); - } - - /** - * Returns an empty, mutable match. - * Fields of the mutable match can be filled to create a partial match, usable as matcher input. - * - * @return the empty match. - * - */ - public static ExtraInputOfTurnout.Match newEmptyMatch() { - return new Mutable(null, null); - } - - /** - * Returns a mutable (partial) match. - * Fields of the mutable match can be filled to create a partial match, usable as matcher input. - * - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @param pS the fixed value of pattern parameter S, or null if not bound. - * @return the new, mutable (partial) match object. - * - */ - public static ExtraInputOfTurnout.Match newMutableMatch(final Turnout pT, final Segment pS) { - return new Mutable(pT, pS); - } - - /** - * Returns a new (partial) match. - * This can be used e.g. to call the matcher with a partial match. - *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @param pS the fixed value of pattern parameter S, or null if not bound. - * @return the (partial) match object. - * - */ - public static ExtraInputOfTurnout.Match newMatch(final Turnout pT, final Segment pS) { - return new Immutable(pT, pS); - } - - private static final class Mutable extends ExtraInputOfTurnout.Match { - Mutable(final Turnout pT, final Segment pS) { - super(pT, pS); - } - - @Override - public boolean isMutable() { - return true; - } - } - - private static final class Immutable extends ExtraInputOfTurnout.Match { - Immutable(final Turnout pT, final Segment pS) { - super(pT, pS); - } - - @Override - public boolean isMutable() { - return false; - } - } - } - - /** - * Generated pattern matcher API of the modes3.queries.extraInputOfTurnout pattern, - * providing pattern-specific query methods. - * - *

Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)}, - * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}. - * - *

Matches of the pattern will be represented as {@link Match}. - * - *

Original source: - *

-   * pattern extraInputOfTurnout(T : Turnout, S : Segment) {
-   * 	Turnout.straight(T, Straight);
-   * 	Turnout.divergent(T, Divergent);
-   * 	find output(S, T);
-   * 	S != Straight;
-   * 	S != Divergent;
-   * }
-   * 
- * - * @see Match - * @see ExtraInputOfTurnout - * - */ - public static class Matcher extends BaseMatcher { - /** - * Initializes the pattern matcher within an existing VIATRA Query engine. - * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. - * - * @param engine the existing VIATRA Query engine in which this matcher will be created. - * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation - * - */ - public static ExtraInputOfTurnout.Matcher on(final ViatraQueryEngine engine) { - // check if matcher already exists - Matcher matcher = engine.getExistingMatcher(querySpecification()); - if (matcher == null) { - matcher = (Matcher)engine.getMatcher(querySpecification()); - } - return matcher; - } - - /** - * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation - * @return an initialized matcher - * @noreference This method is for internal matcher initialization by the framework, do not call it manually. - * - */ - public static ExtraInputOfTurnout.Matcher create() { - return new Matcher(); - } - - private static final int POSITION_T = 0; - - private static final int POSITION_S = 1; - - private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(ExtraInputOfTurnout.Matcher.class); - - /** - * Initializes the pattern matcher within an existing VIATRA Query engine. - * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. - * - * @param engine the existing VIATRA Query engine in which this matcher will be created. - * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation - * - */ - private Matcher() { - super(querySpecification()); - } - - /** - * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @param pS the fixed value of pattern parameter S, or null if not bound. - * @return matches represented as a Match object. - * - */ - public Collection getAllMatches(final Turnout pT, final Segment pS) { - return rawStreamAllMatches(new Object[]{pT, pS}).collect(Collectors.toSet()); - } - - /** - * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters. - *

- * NOTE: It is important not to modify the source model while the stream is being processed. - * If the match set of the pattern changes during processing, the contents of the stream is undefined. - * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @param pS the fixed value of pattern parameter S, or null if not bound. - * @return a stream of matches represented as a Match object. - * - */ - public Stream streamAllMatches(final Turnout pT, final Segment pS) { - return rawStreamAllMatches(new Object[]{pT, pS}); - } - - /** - * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. - * Neither determinism nor randomness of selection is guaranteed. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @param pS the fixed value of pattern parameter S, or null if not bound. - * @return a match represented as a Match object, or null if no match is found. - * - */ - public Optional getOneArbitraryMatch(final Turnout pT, final Segment pS) { - return rawGetOneArbitraryMatch(new Object[]{pT, pS}); - } - - /** - * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, - * under any possible substitution of the unspecified parameters (if any). - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @param pS the fixed value of pattern parameter S, or null if not bound. - * @return true if the input is a valid (partial) match of the pattern. - * - */ - public boolean hasMatch(final Turnout pT, final Segment pS) { - return rawHasMatch(new Object[]{pT, pS}); - } - - /** - * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @param pS the fixed value of pattern parameter S, or null if not bound. - * @return the number of pattern matches found. - * - */ - public int countMatches(final Turnout pT, final Segment pS) { - return rawCountMatches(new Object[]{pT, pS}); - } - - /** - * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. - * Neither determinism nor randomness of selection is guaranteed. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @param pS the fixed value of pattern parameter S, or null if not bound. - * @param processor the action that will process the selected match. - * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked - * - */ - public boolean forOneArbitraryMatch(final Turnout pT, final Segment pS, final Consumer processor) { - return rawForOneArbitraryMatch(new Object[]{pT, pS}, processor); - } - - /** - * Returns a new (partial) match. - * This can be used e.g. to call the matcher with a partial match. - *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @param pS the fixed value of pattern parameter S, or null if not bound. - * @return the (partial) match object. - * - */ - public ExtraInputOfTurnout.Match newMatch(final Turnout pT, final Segment pS) { - return ExtraInputOfTurnout.Match.newMatch(pT, pS); - } - - /** - * Retrieve the set of values that occur in matches for T. - * @return the Set of all values or empty set if there are no matches - * - */ - protected Stream rawStreamAllValuesOfT(final Object[] parameters) { - return rawStreamAllValues(POSITION_T, parameters).map(Turnout.class::cast); - } - - /** - * Retrieve the set of values that occur in matches for T. - * @return the Set of all values or empty set if there are no matches - * - */ - public Set getAllValuesOfT() { - return rawStreamAllValuesOfT(emptyArray()).collect(Collectors.toSet()); - } - - /** - * Retrieve the set of values that occur in matches for T. - * @return the Set of all values or empty set if there are no matches - * - */ - public Stream streamAllValuesOfT() { - return rawStreamAllValuesOfT(emptyArray()); - } - - /** - * Retrieve the set of values that occur in matches for T. - *

- * NOTE: It is important not to modify the source model while the stream is being processed. - * If the match set of the pattern changes during processing, the contents of the stream is undefined. - * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. - * - * @return the Stream of all values or empty set if there are no matches - * - */ - public Stream streamAllValuesOfT(final ExtraInputOfTurnout.Match partialMatch) { - return rawStreamAllValuesOfT(partialMatch.toArray()); - } - - /** - * Retrieve the set of values that occur in matches for T. - *

- * NOTE: It is important not to modify the source model while the stream is being processed. - * If the match set of the pattern changes during processing, the contents of the stream is undefined. - * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. - * - * @return the Stream of all values or empty set if there are no matches - * - */ - public Stream streamAllValuesOfT(final Segment pS) { - return rawStreamAllValuesOfT(new Object[]{null, pS}); - } - - /** - * Retrieve the set of values that occur in matches for T. - * @return the Set of all values or empty set if there are no matches - * - */ - public Set getAllValuesOfT(final ExtraInputOfTurnout.Match partialMatch) { - return rawStreamAllValuesOfT(partialMatch.toArray()).collect(Collectors.toSet()); - } - - /** - * Retrieve the set of values that occur in matches for T. - * @return the Set of all values or empty set if there are no matches - * - */ - public Set getAllValuesOfT(final Segment pS) { - return rawStreamAllValuesOfT(new Object[]{null, pS}).collect(Collectors.toSet()); - } - - /** - * Retrieve the set of values that occur in matches for S. - * @return the Set of all values or empty set if there are no matches - * - */ - protected Stream rawStreamAllValuesOfS(final Object[] parameters) { - return rawStreamAllValues(POSITION_S, parameters).map(Segment.class::cast); - } - - /** - * Retrieve the set of values that occur in matches for S. - * @return the Set of all values or empty set if there are no matches - * - */ - public Set getAllValuesOfS() { - return rawStreamAllValuesOfS(emptyArray()).collect(Collectors.toSet()); - } - - /** - * Retrieve the set of values that occur in matches for S. - * @return the Set of all values or empty set if there are no matches - * - */ - public Stream streamAllValuesOfS() { - return rawStreamAllValuesOfS(emptyArray()); - } - - /** - * Retrieve the set of values that occur in matches for S. - *

- * NOTE: It is important not to modify the source model while the stream is being processed. - * If the match set of the pattern changes during processing, the contents of the stream is undefined. - * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. - * - * @return the Stream of all values or empty set if there are no matches - * - */ - public Stream streamAllValuesOfS(final ExtraInputOfTurnout.Match partialMatch) { - return rawStreamAllValuesOfS(partialMatch.toArray()); - } - - /** - * Retrieve the set of values that occur in matches for S. - *

- * NOTE: It is important not to modify the source model while the stream is being processed. - * If the match set of the pattern changes during processing, the contents of the stream is undefined. - * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. - * - * @return the Stream of all values or empty set if there are no matches - * - */ - public Stream streamAllValuesOfS(final Turnout pT) { - return rawStreamAllValuesOfS(new Object[]{pT, null}); - } - - /** - * Retrieve the set of values that occur in matches for S. - * @return the Set of all values or empty set if there are no matches - * - */ - public Set getAllValuesOfS(final ExtraInputOfTurnout.Match partialMatch) { - return rawStreamAllValuesOfS(partialMatch.toArray()).collect(Collectors.toSet()); - } - - /** - * Retrieve the set of values that occur in matches for S. - * @return the Set of all values or empty set if there are no matches - * - */ - public Set getAllValuesOfS(final Turnout pT) { - return rawStreamAllValuesOfS(new Object[]{pT, null}).collect(Collectors.toSet()); - } - - @Override - protected ExtraInputOfTurnout.Match tupleToMatch(final Tuple t) { - try { - return ExtraInputOfTurnout.Match.newMatch((Turnout) t.get(POSITION_T), (Segment) t.get(POSITION_S)); - } catch(ClassCastException e) { - LOGGER.error("Element(s) in tuple not properly typed!",e); - return null; - } - } - - @Override - protected ExtraInputOfTurnout.Match arrayToMatch(final Object[] match) { - try { - return ExtraInputOfTurnout.Match.newMatch((Turnout) match[POSITION_T], (Segment) match[POSITION_S]); - } catch(ClassCastException e) { - LOGGER.error("Element(s) in array not properly typed!",e); - return null; - } - } - - @Override - protected ExtraInputOfTurnout.Match arrayToMatchMutable(final Object[] match) { - try { - return ExtraInputOfTurnout.Match.newMutableMatch((Turnout) match[POSITION_T], (Segment) match[POSITION_S]); - } catch(ClassCastException e) { - LOGGER.error("Element(s) in array not properly typed!",e); - return null; - } - } - - /** - * @return the singleton instance of the query specification of this pattern - * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded - * - */ - public static IQuerySpecification querySpecification() { - return ExtraInputOfTurnout.instance(); - } - } - - private ExtraInputOfTurnout() { - super(GeneratedPQuery.INSTANCE); - } - - /** - * @return the singleton instance of the query specification - * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded - * - */ - public static ExtraInputOfTurnout instance() { - try{ - return LazyHolder.INSTANCE; - } catch (ExceptionInInitializerError err) { - throw processInitializerError(err); - } - } - - @Override - protected ExtraInputOfTurnout.Matcher instantiate(final ViatraQueryEngine engine) { - return ExtraInputOfTurnout.Matcher.on(engine); - } - - @Override - public ExtraInputOfTurnout.Matcher instantiate() { - return ExtraInputOfTurnout.Matcher.create(); - } - - @Override - public ExtraInputOfTurnout.Match newEmptyMatch() { - return ExtraInputOfTurnout.Match.newEmptyMatch(); - } - - @Override - public ExtraInputOfTurnout.Match newMatch(final Object... parameters) { - return ExtraInputOfTurnout.Match.newMatch((modes3.Turnout) parameters[0], (modes3.Segment) parameters[1]); - } - - /** - * Inner class allowing the singleton instance of {@link ExtraInputOfTurnout} to be created - * not at the class load time of the outer class, - * but rather at the first call to {@link ExtraInputOfTurnout#instance()}. - * - *

This workaround is required e.g. to support recursion. - * - */ - private static class LazyHolder { - private static final ExtraInputOfTurnout INSTANCE = new ExtraInputOfTurnout(); - - /** - * Statically initializes the query specification after the field {@link #INSTANCE} is assigned. - * This initialization order is required to support indirect recursion. - * - *

The static initializer is defined using a helper field to work around limitations of the code generator. - * - */ - private static final Object STATIC_INITIALIZER = ensureInitialized(); - - public static Object ensureInitialized() { - INSTANCE.ensureInitializedInternal(); - return null; - } - } - - private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { - private static final ExtraInputOfTurnout.GeneratedPQuery INSTANCE = new GeneratedPQuery(); - - private final PParameter parameter_T = new PParameter("T", "modes3.Turnout", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Turnout")), PParameterDirection.INOUT); - - private final PParameter parameter_S = new PParameter("S", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT); - - private final List parameters = Arrays.asList(parameter_T, parameter_S); - - private GeneratedPQuery() { - super(PVisibility.PUBLIC); - } - - @Override - public String getFullyQualifiedName() { - return "modes3.queries.extraInputOfTurnout"; - } - - @Override - public List getParameterNames() { - return Arrays.asList("T","S"); - } - - @Override - public List getParameters() { - return parameters; - } - - @Override - public Set doGetContainedBodies() { - setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED)); - Set bodies = new LinkedHashSet<>(); - { - PBody body = new PBody(this); - PVariable var_T = body.getOrCreateVariableByName("T"); - PVariable var_S = body.getOrCreateVariableByName("S"); - PVariable var_Straight = body.getOrCreateVariableByName("Straight"); - PVariable var_Divergent = body.getOrCreateVariableByName("Divergent"); - new TypeConstraint(body, Tuples.flatTupleOf(var_T), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Turnout"))); - new TypeConstraint(body, Tuples.flatTupleOf(var_S), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); - body.setSymbolicParameters(Arrays.asList( - new ExportedParameter(body, var_T, parameter_T), - new ExportedParameter(body, var_S, parameter_S) - )); - // Turnout.straight(T, Straight) - new TypeConstraint(body, Tuples.flatTupleOf(var_T), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Turnout"))); - PVariable var__virtual_0_ = body.getOrCreateVariableByName(".virtual{0}"); - new TypeConstraint(body, Tuples.flatTupleOf(var_T, var__virtual_0_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Turnout", "straight"))); - new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_0_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); - new Equality(body, var__virtual_0_, var_Straight); - // Turnout.divergent(T, Divergent) - new TypeConstraint(body, Tuples.flatTupleOf(var_T), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Turnout"))); - PVariable var__virtual_1_ = body.getOrCreateVariableByName(".virtual{1}"); - new TypeConstraint(body, Tuples.flatTupleOf(var_T, var__virtual_1_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Turnout", "divergent"))); - new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_1_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); - new Equality(body, var__virtual_1_, var_Divergent); - // find output(S, T) - new PositivePatternCall(body, Tuples.flatTupleOf(var_S, var_T), Output.instance().getInternalQueryRepresentation()); - // S != Straight - new Inequality(body, var_S, var_Straight); - // S != Divergent - new Inequality(body, var_S, var_Divergent); - bodies.add(body); - } - return bodies; - } - } -} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/InputsOfTurnout.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/InputsOfTurnout.java new file mode 100644 index 00000000..2f2eea11 --- /dev/null +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/InputsOfTurnout.java @@ -0,0 +1,570 @@ +/** + * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql + */ +package modes3.queries; + +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import modes3.Turnout; +import modes3.queries.Adjacent; +import org.apache.log4j.Logger; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.viatra.query.runtime.api.IPatternMatch; +import org.eclipse.viatra.query.runtime.api.IQuerySpecification; +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification; +import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher; +import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch; +import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey; +import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint; +import org.eclipse.viatra.query.runtime.matchers.psystem.PBody; +import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Inequality; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.PositivePatternCall; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples; +import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil; + +/** + * A pattern-specific query specification that can instantiate Matcher in a type-safe way. + * + *

Original source: + *

+ *         pattern inputsOfTurnout(T : Turnout) {
+ *         	find adjacent(I1, T);
+ *         	find adjacent(I2, T);
+ *         	find adjacent(I3, T);
+ *         	I1 != I2;
+ *         	I1 != I3;
+ *         	I2 != I3;
+ *         }
+ * 
+ * + * @see Matcher + * @see Match + * + */ +@SuppressWarnings("all") +public final class InputsOfTurnout extends BaseGeneratedEMFQuerySpecification { + /** + * Pattern-specific match representation of the modes3.queries.inputsOfTurnout pattern, + * to be used in conjunction with {@link Matcher}. + * + *

Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned. + * Each instance is a (possibly partial) substitution of pattern parameters, + * usable to represent a match of the pattern in the result of a query, + * or to specify the bound (fixed) input parameters when issuing a query. + * + * @see Matcher + * + */ + public static abstract class Match extends BasePatternMatch { + private Turnout fT; + + private static List parameterNames = makeImmutableList("T"); + + private Match(final Turnout pT) { + this.fT = pT; + } + + @Override + public Object get(final String parameterName) { + switch(parameterName) { + case "T": return this.fT; + default: return null; + } + } + + @Override + public Object get(final int index) { + switch(index) { + case 0: return this.fT; + default: return null; + } + } + + public Turnout getT() { + return this.fT; + } + + @Override + public boolean set(final String parameterName, final Object newValue) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + if ("T".equals(parameterName) ) { + this.fT = (Turnout) newValue; + return true; + } + return false; + } + + public void setT(final Turnout pT) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fT = pT; + } + + @Override + public String patternName() { + return "modes3.queries.inputsOfTurnout"; + } + + @Override + public List parameterNames() { + return InputsOfTurnout.Match.parameterNames; + } + + @Override + public Object[] toArray() { + return new Object[]{fT}; + } + + @Override + public InputsOfTurnout.Match toImmutable() { + return isMutable() ? newMatch(fT) : this; + } + + @Override + public String prettyPrint() { + StringBuilder result = new StringBuilder(); + result.append("\"T\"=" + prettyPrintValue(fT)); + return result.toString(); + } + + @Override + public int hashCode() { + return Objects.hash(fT); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) { + return false; + } + if ((obj instanceof InputsOfTurnout.Match)) { + InputsOfTurnout.Match other = (InputsOfTurnout.Match) obj; + return Objects.equals(fT, other.fT); + } else { + // this should be infrequent + if (!(obj instanceof IPatternMatch)) { + return false; + } + IPatternMatch otherSig = (IPatternMatch) obj; + return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray()); + } + } + + @Override + public InputsOfTurnout specification() { + return InputsOfTurnout.instance(); + } + + /** + * Returns an empty, mutable match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @return the empty match. + * + */ + public static InputsOfTurnout.Match newEmptyMatch() { + return new Mutable(null); + } + + /** + * Returns a mutable (partial) match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return the new, mutable (partial) match object. + * + */ + public static InputsOfTurnout.Match newMutableMatch(final Turnout pT) { + return new Mutable(pT); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return the (partial) match object. + * + */ + public static InputsOfTurnout.Match newMatch(final Turnout pT) { + return new Immutable(pT); + } + + private static final class Mutable extends InputsOfTurnout.Match { + Mutable(final Turnout pT) { + super(pT); + } + + @Override + public boolean isMutable() { + return true; + } + } + + private static final class Immutable extends InputsOfTurnout.Match { + Immutable(final Turnout pT) { + super(pT); + } + + @Override + public boolean isMutable() { + return false; + } + } + } + + /** + * Generated pattern matcher API of the modes3.queries.inputsOfTurnout pattern, + * providing pattern-specific query methods. + * + *

Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)}, + * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}. + * + *

Matches of the pattern will be represented as {@link Match}. + * + *

Original source: + *

+   * pattern inputsOfTurnout(T : Turnout) {
+   * 	find adjacent(I1, T);
+   * 	find adjacent(I2, T);
+   * 	find adjacent(I3, T);
+   * 	I1 != I2;
+   * 	I1 != I3;
+   * 	I2 != I3;
+   * }
+   * 
+ * + * @see Match + * @see InputsOfTurnout + * + */ + public static class Matcher extends BaseMatcher { + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + public static InputsOfTurnout.Matcher on(final ViatraQueryEngine engine) { + // check if matcher already exists + Matcher matcher = engine.getExistingMatcher(querySpecification()); + if (matcher == null) { + matcher = (Matcher)engine.getMatcher(querySpecification()); + } + return matcher; + } + + /** + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * @return an initialized matcher + * @noreference This method is for internal matcher initialization by the framework, do not call it manually. + * + */ + public static InputsOfTurnout.Matcher create() { + return new Matcher(); + } + + private static final int POSITION_T = 0; + + private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(InputsOfTurnout.Matcher.class); + + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + private Matcher() { + super(querySpecification()); + } + + /** + * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return matches represented as a Match object. + * + */ + public Collection getAllMatches(final Turnout pT) { + return rawStreamAllMatches(new Object[]{pT}).collect(Collectors.toSet()); + } + + /** + * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return a stream of matches represented as a Match object. + * + */ + public Stream streamAllMatches(final Turnout pT) { + return rawStreamAllMatches(new Object[]{pT}); + } + + /** + * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return a match represented as a Match object, or null if no match is found. + * + */ + public Optional getOneArbitraryMatch(final Turnout pT) { + return rawGetOneArbitraryMatch(new Object[]{pT}); + } + + /** + * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, + * under any possible substitution of the unspecified parameters (if any). + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return true if the input is a valid (partial) match of the pattern. + * + */ + public boolean hasMatch(final Turnout pT) { + return rawHasMatch(new Object[]{pT}); + } + + /** + * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return the number of pattern matches found. + * + */ + public int countMatches(final Turnout pT) { + return rawCountMatches(new Object[]{pT}); + } + + /** + * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @param processor the action that will process the selected match. + * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked + * + */ + public boolean forOneArbitraryMatch(final Turnout pT, final Consumer processor) { + return rawForOneArbitraryMatch(new Object[]{pT}, processor); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return the (partial) match object. + * + */ + public InputsOfTurnout.Match newMatch(final Turnout pT) { + return InputsOfTurnout.Match.newMatch(pT); + } + + /** + * Retrieve the set of values that occur in matches for T. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOfT(final Object[] parameters) { + return rawStreamAllValues(POSITION_T, parameters).map(Turnout.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for T. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOfT() { + return rawStreamAllValuesOfT(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for T. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOfT() { + return rawStreamAllValuesOfT(emptyArray()); + } + + @Override + protected InputsOfTurnout.Match tupleToMatch(final Tuple t) { + try { + return InputsOfTurnout.Match.newMatch((Turnout) t.get(POSITION_T)); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in tuple not properly typed!",e); + return null; + } + } + + @Override + protected InputsOfTurnout.Match arrayToMatch(final Object[] match) { + try { + return InputsOfTurnout.Match.newMatch((Turnout) match[POSITION_T]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + @Override + protected InputsOfTurnout.Match arrayToMatchMutable(final Object[] match) { + try { + return InputsOfTurnout.Match.newMutableMatch((Turnout) match[POSITION_T]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + /** + * @return the singleton instance of the query specification of this pattern + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static IQuerySpecification querySpecification() { + return InputsOfTurnout.instance(); + } + } + + private InputsOfTurnout() { + super(GeneratedPQuery.INSTANCE); + } + + /** + * @return the singleton instance of the query specification + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static InputsOfTurnout instance() { + try{ + return LazyHolder.INSTANCE; + } catch (ExceptionInInitializerError err) { + throw processInitializerError(err); + } + } + + @Override + protected InputsOfTurnout.Matcher instantiate(final ViatraQueryEngine engine) { + return InputsOfTurnout.Matcher.on(engine); + } + + @Override + public InputsOfTurnout.Matcher instantiate() { + return InputsOfTurnout.Matcher.create(); + } + + @Override + public InputsOfTurnout.Match newEmptyMatch() { + return InputsOfTurnout.Match.newEmptyMatch(); + } + + @Override + public InputsOfTurnout.Match newMatch(final Object... parameters) { + return InputsOfTurnout.Match.newMatch((modes3.Turnout) parameters[0]); + } + + /** + * Inner class allowing the singleton instance of {@link InputsOfTurnout} to be created + * not at the class load time of the outer class, + * but rather at the first call to {@link InputsOfTurnout#instance()}. + * + *

This workaround is required e.g. to support recursion. + * + */ + private static class LazyHolder { + private static final InputsOfTurnout INSTANCE = new InputsOfTurnout(); + + /** + * Statically initializes the query specification after the field {@link #INSTANCE} is assigned. + * This initialization order is required to support indirect recursion. + * + *

The static initializer is defined using a helper field to work around limitations of the code generator. + * + */ + private static final Object STATIC_INITIALIZER = ensureInitialized(); + + public static Object ensureInitialized() { + INSTANCE.ensureInitializedInternal(); + return null; + } + } + + private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { + private static final InputsOfTurnout.GeneratedPQuery INSTANCE = new GeneratedPQuery(); + + private final PParameter parameter_T = new PParameter("T", "modes3.Turnout", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Turnout")), PParameterDirection.INOUT); + + private final List parameters = Arrays.asList(parameter_T); + + private GeneratedPQuery() { + super(PVisibility.PUBLIC); + } + + @Override + public String getFullyQualifiedName() { + return "modes3.queries.inputsOfTurnout"; + } + + @Override + public List getParameterNames() { + return Arrays.asList("T"); + } + + @Override + public List getParameters() { + return parameters; + } + + @Override + public Set doGetContainedBodies() { + setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED)); + Set bodies = new LinkedHashSet<>(); + { + PBody body = new PBody(this); + PVariable var_T = body.getOrCreateVariableByName("T"); + PVariable var_I1 = body.getOrCreateVariableByName("I1"); + PVariable var_I2 = body.getOrCreateVariableByName("I2"); + PVariable var_I3 = body.getOrCreateVariableByName("I3"); + new TypeConstraint(body, Tuples.flatTupleOf(var_T), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Turnout"))); + body.setSymbolicParameters(Arrays.asList( + new ExportedParameter(body, var_T, parameter_T) + )); + // find adjacent(I1, T) + new PositivePatternCall(body, Tuples.flatTupleOf(var_I1, var_T), Adjacent.instance().getInternalQueryRepresentation()); + // find adjacent(I2, T) + new PositivePatternCall(body, Tuples.flatTupleOf(var_I2, var_T), Adjacent.instance().getInternalQueryRepresentation()); + // find adjacent(I3, T) + new PositivePatternCall(body, Tuples.flatTupleOf(var_I3, var_T), Adjacent.instance().getInternalQueryRepresentation()); + // I1 != I2 + new Inequality(body, var_I1, var_I2); + // I1 != I3 + new Inequality(body, var_I1, var_I3); + // I2 != I3 + new Inequality(body, var_I2, var_I3); + bodies.add(body); + } + return bodies; + } + } +} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/Modes3Queries.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/Modes3Queries.java index 01ec77a1..6e244430 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/Modes3Queries.java +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/Modes3Queries.java @@ -7,16 +7,14 @@ import modes3.queries.Adjacent; import modes3.queries.ConnectedTo; import modes3.queries.ConnectedToNotSymmetric; import modes3.queries.ConnectedToReflexive; -import modes3.queries.ExtraInputOfTurnout; -import modes3.queries.NoExtraInputOfTurnout; +import modes3.queries.InputsOfTurnout; import modes3.queries.Output; import modes3.queries.OutputReflexive; import modes3.queries.Reachable; -import modes3.queries.TooManyExtraInputsOfTurnout; +import modes3.queries.TooFewInputsOfTurnout; import modes3.queries.TooManyInputsOfSegment; -import modes3.queries.Turnout; +import modes3.queries.TooManyInputsOfTurnout; import modes3.queries.TurnoutConnectedToBothOutputs; -import modes3.queries.TurnoutInSegments; import modes3.queries.TurnoutOutput; import modes3.queries.TurnoutOutputsAreSame; import modes3.queries.Unreachable; @@ -31,21 +29,19 @@ import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedPatternGroup; * in order to achieve better performance than one-by-one on-demand matcher initialization. * *

From package modes3.queries, the group contains the definition of the following patterns:

    - *
  • turnoutInSegments
  • *
  • connectedTo
  • *
  • connectedToNotSymmetric
  • *
  • connectedToReflexive
  • *
  • turnoutOutput
  • *
  • outputReflexive
  • *
  • turnoutOutputsAreSame
  • - *
  • turnout
  • *
  • output
  • *
  • tooManyInputsOfSegment
  • *
  • turnoutConnectedToBothOutputs
  • - *
  • extraInputOfTurnout
  • - *
  • noExtraInputOfTurnout
  • - *
  • tooManyExtraInputsOfTurnout
  • *
  • adjacent
  • + *
  • tooManyInputsOfTurnout
  • + *
  • inputsOfTurnout
  • + *
  • tooFewInputsOfTurnout
  • *
  • reachable
  • *
  • unreachable
  • *
@@ -72,33 +68,23 @@ public final class Modes3Queries extends BaseGeneratedPatternGroup { private static Modes3Queries INSTANCE; private Modes3Queries() { - querySpecifications.add(TurnoutInSegments.instance()); querySpecifications.add(ConnectedTo.instance()); querySpecifications.add(ConnectedToNotSymmetric.instance()); querySpecifications.add(ConnectedToReflexive.instance()); querySpecifications.add(TurnoutOutput.instance()); querySpecifications.add(OutputReflexive.instance()); querySpecifications.add(TurnoutOutputsAreSame.instance()); - querySpecifications.add(Turnout.instance()); querySpecifications.add(Output.instance()); querySpecifications.add(TooManyInputsOfSegment.instance()); querySpecifications.add(TurnoutConnectedToBothOutputs.instance()); - querySpecifications.add(ExtraInputOfTurnout.instance()); - querySpecifications.add(NoExtraInputOfTurnout.instance()); - querySpecifications.add(TooManyExtraInputsOfTurnout.instance()); querySpecifications.add(Adjacent.instance()); + querySpecifications.add(TooManyInputsOfTurnout.instance()); + querySpecifications.add(InputsOfTurnout.instance()); + querySpecifications.add(TooFewInputsOfTurnout.instance()); querySpecifications.add(Reachable.instance()); querySpecifications.add(Unreachable.instance()); } - public TurnoutInSegments getTurnoutInSegments() { - return TurnoutInSegments.instance(); - } - - public TurnoutInSegments.Matcher getTurnoutInSegments(final ViatraQueryEngine engine) { - return TurnoutInSegments.Matcher.on(engine); - } - public ConnectedTo getConnectedTo() { return ConnectedTo.instance(); } @@ -147,14 +133,6 @@ public final class Modes3Queries extends BaseGeneratedPatternGroup { return TurnoutOutputsAreSame.Matcher.on(engine); } - public Turnout getTurnout() { - return Turnout.instance(); - } - - public Turnout.Matcher getTurnout(final ViatraQueryEngine engine) { - return Turnout.Matcher.on(engine); - } - public Output getOutput() { return Output.instance(); } @@ -179,36 +157,36 @@ public final class Modes3Queries extends BaseGeneratedPatternGroup { return TurnoutConnectedToBothOutputs.Matcher.on(engine); } - public ExtraInputOfTurnout getExtraInputOfTurnout() { - return ExtraInputOfTurnout.instance(); + public Adjacent getAdjacent() { + return Adjacent.instance(); } - public ExtraInputOfTurnout.Matcher getExtraInputOfTurnout(final ViatraQueryEngine engine) { - return ExtraInputOfTurnout.Matcher.on(engine); + public Adjacent.Matcher getAdjacent(final ViatraQueryEngine engine) { + return Adjacent.Matcher.on(engine); } - public NoExtraInputOfTurnout getNoExtraInputOfTurnout() { - return NoExtraInputOfTurnout.instance(); + public TooManyInputsOfTurnout getTooManyInputsOfTurnout() { + return TooManyInputsOfTurnout.instance(); } - public NoExtraInputOfTurnout.Matcher getNoExtraInputOfTurnout(final ViatraQueryEngine engine) { - return NoExtraInputOfTurnout.Matcher.on(engine); + public TooManyInputsOfTurnout.Matcher getTooManyInputsOfTurnout(final ViatraQueryEngine engine) { + return TooManyInputsOfTurnout.Matcher.on(engine); } - public TooManyExtraInputsOfTurnout getTooManyExtraInputsOfTurnout() { - return TooManyExtraInputsOfTurnout.instance(); + public InputsOfTurnout getInputsOfTurnout() { + return InputsOfTurnout.instance(); } - public TooManyExtraInputsOfTurnout.Matcher getTooManyExtraInputsOfTurnout(final ViatraQueryEngine engine) { - return TooManyExtraInputsOfTurnout.Matcher.on(engine); + public InputsOfTurnout.Matcher getInputsOfTurnout(final ViatraQueryEngine engine) { + return InputsOfTurnout.Matcher.on(engine); } - public Adjacent getAdjacent() { - return Adjacent.instance(); + public TooFewInputsOfTurnout getTooFewInputsOfTurnout() { + return TooFewInputsOfTurnout.instance(); } - public Adjacent.Matcher getAdjacent(final ViatraQueryEngine engine) { - return Adjacent.Matcher.on(engine); + public TooFewInputsOfTurnout.Matcher getTooFewInputsOfTurnout(final ViatraQueryEngine engine) { + return TooFewInputsOfTurnout.Matcher.on(engine); } public Reachable getReachable() { diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/NoExtraInputOfTurnout.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/NoExtraInputOfTurnout.java deleted file mode 100644 index 621d736f..00000000 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/NoExtraInputOfTurnout.java +++ /dev/null @@ -1,560 +0,0 @@ -/** - * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql - */ -package modes3.queries; - -import java.util.Arrays; -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.function.Consumer; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import modes3.Turnout; -import modes3.queries.ExtraInputOfTurnout; -import org.apache.log4j.Logger; -import org.eclipse.emf.ecore.EClass; -import org.eclipse.viatra.query.runtime.api.IPatternMatch; -import org.eclipse.viatra.query.runtime.api.IQuerySpecification; -import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine; -import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery; -import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification; -import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher; -import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch; -import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey; -import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint; -import org.eclipse.viatra.query.runtime.matchers.psystem.PBody; -import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable; -import org.eclipse.viatra.query.runtime.matchers.psystem.annotations.PAnnotation; -import org.eclipse.viatra.query.runtime.matchers.psystem.annotations.ParameterReference; -import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter; -import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.NegativePatternCall; -import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint; -import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter; -import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection; -import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility; -import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple; -import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples; -import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil; - -/** - * A pattern-specific query specification that can instantiate Matcher in a type-safe way. - * - *

Original source: - *

- *         {@literal @}Constraint(message = "noExtraInputOfTurnout", severity = "error", key = { T })
- *         pattern noExtraInputOfTurnout(T : Turnout) {
- *         	neg find extraInputOfTurnout(T, _);
- *         }
- * 
- * - * @see Matcher - * @see Match - * - */ -@SuppressWarnings("all") -public final class NoExtraInputOfTurnout extends BaseGeneratedEMFQuerySpecification { - /** - * Pattern-specific match representation of the modes3.queries.noExtraInputOfTurnout pattern, - * to be used in conjunction with {@link Matcher}. - * - *

Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned. - * Each instance is a (possibly partial) substitution of pattern parameters, - * usable to represent a match of the pattern in the result of a query, - * or to specify the bound (fixed) input parameters when issuing a query. - * - * @see Matcher - * - */ - public static abstract class Match extends BasePatternMatch { - private Turnout fT; - - private static List parameterNames = makeImmutableList("T"); - - private Match(final Turnout pT) { - this.fT = pT; - } - - @Override - public Object get(final String parameterName) { - switch(parameterName) { - case "T": return this.fT; - default: return null; - } - } - - @Override - public Object get(final int index) { - switch(index) { - case 0: return this.fT; - default: return null; - } - } - - public Turnout getT() { - return this.fT; - } - - @Override - public boolean set(final String parameterName, final Object newValue) { - if (!isMutable()) throw new java.lang.UnsupportedOperationException(); - if ("T".equals(parameterName) ) { - this.fT = (Turnout) newValue; - return true; - } - return false; - } - - public void setT(final Turnout pT) { - if (!isMutable()) throw new java.lang.UnsupportedOperationException(); - this.fT = pT; - } - - @Override - public String patternName() { - return "modes3.queries.noExtraInputOfTurnout"; - } - - @Override - public List parameterNames() { - return NoExtraInputOfTurnout.Match.parameterNames; - } - - @Override - public Object[] toArray() { - return new Object[]{fT}; - } - - @Override - public NoExtraInputOfTurnout.Match toImmutable() { - return isMutable() ? newMatch(fT) : this; - } - - @Override - public String prettyPrint() { - StringBuilder result = new StringBuilder(); - result.append("\"T\"=" + prettyPrintValue(fT)); - return result.toString(); - } - - @Override - public int hashCode() { - return Objects.hash(fT); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) { - return false; - } - if ((obj instanceof NoExtraInputOfTurnout.Match)) { - NoExtraInputOfTurnout.Match other = (NoExtraInputOfTurnout.Match) obj; - return Objects.equals(fT, other.fT); - } else { - // this should be infrequent - if (!(obj instanceof IPatternMatch)) { - return false; - } - IPatternMatch otherSig = (IPatternMatch) obj; - return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray()); - } - } - - @Override - public NoExtraInputOfTurnout specification() { - return NoExtraInputOfTurnout.instance(); - } - - /** - * Returns an empty, mutable match. - * Fields of the mutable match can be filled to create a partial match, usable as matcher input. - * - * @return the empty match. - * - */ - public static NoExtraInputOfTurnout.Match newEmptyMatch() { - return new Mutable(null); - } - - /** - * Returns a mutable (partial) match. - * Fields of the mutable match can be filled to create a partial match, usable as matcher input. - * - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return the new, mutable (partial) match object. - * - */ - public static NoExtraInputOfTurnout.Match newMutableMatch(final Turnout pT) { - return new Mutable(pT); - } - - /** - * Returns a new (partial) match. - * This can be used e.g. to call the matcher with a partial match. - *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return the (partial) match object. - * - */ - public static NoExtraInputOfTurnout.Match newMatch(final Turnout pT) { - return new Immutable(pT); - } - - private static final class Mutable extends NoExtraInputOfTurnout.Match { - Mutable(final Turnout pT) { - super(pT); - } - - @Override - public boolean isMutable() { - return true; - } - } - - private static final class Immutable extends NoExtraInputOfTurnout.Match { - Immutable(final Turnout pT) { - super(pT); - } - - @Override - public boolean isMutable() { - return false; - } - } - } - - /** - * Generated pattern matcher API of the modes3.queries.noExtraInputOfTurnout pattern, - * providing pattern-specific query methods. - * - *

Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)}, - * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}. - * - *

Matches of the pattern will be represented as {@link Match}. - * - *

Original source: - *

-   * {@literal @}Constraint(message = "noExtraInputOfTurnout", severity = "error", key = { T })
-   * pattern noExtraInputOfTurnout(T : Turnout) {
-   * 	neg find extraInputOfTurnout(T, _);
-   * }
-   * 
- * - * @see Match - * @see NoExtraInputOfTurnout - * - */ - public static class Matcher extends BaseMatcher { - /** - * Initializes the pattern matcher within an existing VIATRA Query engine. - * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. - * - * @param engine the existing VIATRA Query engine in which this matcher will be created. - * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation - * - */ - public static NoExtraInputOfTurnout.Matcher on(final ViatraQueryEngine engine) { - // check if matcher already exists - Matcher matcher = engine.getExistingMatcher(querySpecification()); - if (matcher == null) { - matcher = (Matcher)engine.getMatcher(querySpecification()); - } - return matcher; - } - - /** - * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation - * @return an initialized matcher - * @noreference This method is for internal matcher initialization by the framework, do not call it manually. - * - */ - public static NoExtraInputOfTurnout.Matcher create() { - return new Matcher(); - } - - private static final int POSITION_T = 0; - - private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(NoExtraInputOfTurnout.Matcher.class); - - /** - * Initializes the pattern matcher within an existing VIATRA Query engine. - * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. - * - * @param engine the existing VIATRA Query engine in which this matcher will be created. - * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation - * - */ - private Matcher() { - super(querySpecification()); - } - - /** - * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return matches represented as a Match object. - * - */ - public Collection getAllMatches(final Turnout pT) { - return rawStreamAllMatches(new Object[]{pT}).collect(Collectors.toSet()); - } - - /** - * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters. - *

- * NOTE: It is important not to modify the source model while the stream is being processed. - * If the match set of the pattern changes during processing, the contents of the stream is undefined. - * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return a stream of matches represented as a Match object. - * - */ - public Stream streamAllMatches(final Turnout pT) { - return rawStreamAllMatches(new Object[]{pT}); - } - - /** - * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. - * Neither determinism nor randomness of selection is guaranteed. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return a match represented as a Match object, or null if no match is found. - * - */ - public Optional getOneArbitraryMatch(final Turnout pT) { - return rawGetOneArbitraryMatch(new Object[]{pT}); - } - - /** - * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, - * under any possible substitution of the unspecified parameters (if any). - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return true if the input is a valid (partial) match of the pattern. - * - */ - public boolean hasMatch(final Turnout pT) { - return rawHasMatch(new Object[]{pT}); - } - - /** - * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return the number of pattern matches found. - * - */ - public int countMatches(final Turnout pT) { - return rawCountMatches(new Object[]{pT}); - } - - /** - * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. - * Neither determinism nor randomness of selection is guaranteed. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @param processor the action that will process the selected match. - * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked - * - */ - public boolean forOneArbitraryMatch(final Turnout pT, final Consumer processor) { - return rawForOneArbitraryMatch(new Object[]{pT}, processor); - } - - /** - * Returns a new (partial) match. - * This can be used e.g. to call the matcher with a partial match. - *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return the (partial) match object. - * - */ - public NoExtraInputOfTurnout.Match newMatch(final Turnout pT) { - return NoExtraInputOfTurnout.Match.newMatch(pT); - } - - /** - * Retrieve the set of values that occur in matches for T. - * @return the Set of all values or empty set if there are no matches - * - */ - protected Stream rawStreamAllValuesOfT(final Object[] parameters) { - return rawStreamAllValues(POSITION_T, parameters).map(Turnout.class::cast); - } - - /** - * Retrieve the set of values that occur in matches for T. - * @return the Set of all values or empty set if there are no matches - * - */ - public Set getAllValuesOfT() { - return rawStreamAllValuesOfT(emptyArray()).collect(Collectors.toSet()); - } - - /** - * Retrieve the set of values that occur in matches for T. - * @return the Set of all values or empty set if there are no matches - * - */ - public Stream streamAllValuesOfT() { - return rawStreamAllValuesOfT(emptyArray()); - } - - @Override - protected NoExtraInputOfTurnout.Match tupleToMatch(final Tuple t) { - try { - return NoExtraInputOfTurnout.Match.newMatch((Turnout) t.get(POSITION_T)); - } catch(ClassCastException e) { - LOGGER.error("Element(s) in tuple not properly typed!",e); - return null; - } - } - - @Override - protected NoExtraInputOfTurnout.Match arrayToMatch(final Object[] match) { - try { - return NoExtraInputOfTurnout.Match.newMatch((Turnout) match[POSITION_T]); - } catch(ClassCastException e) { - LOGGER.error("Element(s) in array not properly typed!",e); - return null; - } - } - - @Override - protected NoExtraInputOfTurnout.Match arrayToMatchMutable(final Object[] match) { - try { - return NoExtraInputOfTurnout.Match.newMutableMatch((Turnout) match[POSITION_T]); - } catch(ClassCastException e) { - LOGGER.error("Element(s) in array not properly typed!",e); - return null; - } - } - - /** - * @return the singleton instance of the query specification of this pattern - * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded - * - */ - public static IQuerySpecification querySpecification() { - return NoExtraInputOfTurnout.instance(); - } - } - - private NoExtraInputOfTurnout() { - super(GeneratedPQuery.INSTANCE); - } - - /** - * @return the singleton instance of the query specification - * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded - * - */ - public static NoExtraInputOfTurnout instance() { - try{ - return LazyHolder.INSTANCE; - } catch (ExceptionInInitializerError err) { - throw processInitializerError(err); - } - } - - @Override - protected NoExtraInputOfTurnout.Matcher instantiate(final ViatraQueryEngine engine) { - return NoExtraInputOfTurnout.Matcher.on(engine); - } - - @Override - public NoExtraInputOfTurnout.Matcher instantiate() { - return NoExtraInputOfTurnout.Matcher.create(); - } - - @Override - public NoExtraInputOfTurnout.Match newEmptyMatch() { - return NoExtraInputOfTurnout.Match.newEmptyMatch(); - } - - @Override - public NoExtraInputOfTurnout.Match newMatch(final Object... parameters) { - return NoExtraInputOfTurnout.Match.newMatch((modes3.Turnout) parameters[0]); - } - - /** - * Inner class allowing the singleton instance of {@link NoExtraInputOfTurnout} to be created - * not at the class load time of the outer class, - * but rather at the first call to {@link NoExtraInputOfTurnout#instance()}. - * - *

This workaround is required e.g. to support recursion. - * - */ - private static class LazyHolder { - private static final NoExtraInputOfTurnout INSTANCE = new NoExtraInputOfTurnout(); - - /** - * Statically initializes the query specification after the field {@link #INSTANCE} is assigned. - * This initialization order is required to support indirect recursion. - * - *

The static initializer is defined using a helper field to work around limitations of the code generator. - * - */ - private static final Object STATIC_INITIALIZER = ensureInitialized(); - - public static Object ensureInitialized() { - INSTANCE.ensureInitializedInternal(); - return null; - } - } - - private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { - private static final NoExtraInputOfTurnout.GeneratedPQuery INSTANCE = new GeneratedPQuery(); - - private final PParameter parameter_T = new PParameter("T", "modes3.Turnout", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Turnout")), PParameterDirection.INOUT); - - private final List parameters = Arrays.asList(parameter_T); - - private GeneratedPQuery() { - super(PVisibility.PUBLIC); - } - - @Override - public String getFullyQualifiedName() { - return "modes3.queries.noExtraInputOfTurnout"; - } - - @Override - public List getParameterNames() { - return Arrays.asList("T"); - } - - @Override - public List getParameters() { - return parameters; - } - - @Override - public Set doGetContainedBodies() { - setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED)); - Set bodies = new LinkedHashSet<>(); - { - PBody body = new PBody(this); - PVariable var_T = body.getOrCreateVariableByName("T"); - PVariable var___0_ = body.getOrCreateVariableByName("_<0>"); - new TypeConstraint(body, Tuples.flatTupleOf(var_T), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Turnout"))); - body.setSymbolicParameters(Arrays.asList( - new ExportedParameter(body, var_T, parameter_T) - )); - // neg find extraInputOfTurnout(T, _) - new NegativePatternCall(body, Tuples.flatTupleOf(var_T, var___0_), ExtraInputOfTurnout.instance().getInternalQueryRepresentation()); - bodies.add(body); - } - { - PAnnotation annotation = new PAnnotation("Constraint"); - annotation.addAttribute("message", "noExtraInputOfTurnout"); - annotation.addAttribute("severity", "error"); - annotation.addAttribute("key", Arrays.asList(new Object[] { - new ParameterReference("T") - })); - addAnnotation(annotation); - } - return bodies; - } - } -} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooFewInputsOfTurnout.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooFewInputsOfTurnout.java new file mode 100644 index 00000000..088640ca --- /dev/null +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooFewInputsOfTurnout.java @@ -0,0 +1,559 @@ +/** + * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql + */ +package modes3.queries; + +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import modes3.Turnout; +import modes3.queries.InputsOfTurnout; +import org.apache.log4j.Logger; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.viatra.query.runtime.api.IPatternMatch; +import org.eclipse.viatra.query.runtime.api.IQuerySpecification; +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification; +import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher; +import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch; +import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey; +import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint; +import org.eclipse.viatra.query.runtime.matchers.psystem.PBody; +import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable; +import org.eclipse.viatra.query.runtime.matchers.psystem.annotations.PAnnotation; +import org.eclipse.viatra.query.runtime.matchers.psystem.annotations.ParameterReference; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.NegativePatternCall; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples; +import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil; + +/** + * A pattern-specific query specification that can instantiate Matcher in a type-safe way. + * + *

Original source: + *

+ *         {@literal @}Constraint(message = "tooFewInputsOfTurnout", severity = "error", key = { T })
+ *         pattern tooFewInputsOfTurnout(T : Turnout) {
+ *         	neg find inputsOfTurnout(T);
+ *         }
+ * 
+ * + * @see Matcher + * @see Match + * + */ +@SuppressWarnings("all") +public final class TooFewInputsOfTurnout extends BaseGeneratedEMFQuerySpecification { + /** + * Pattern-specific match representation of the modes3.queries.tooFewInputsOfTurnout pattern, + * to be used in conjunction with {@link Matcher}. + * + *

Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned. + * Each instance is a (possibly partial) substitution of pattern parameters, + * usable to represent a match of the pattern in the result of a query, + * or to specify the bound (fixed) input parameters when issuing a query. + * + * @see Matcher + * + */ + public static abstract class Match extends BasePatternMatch { + private Turnout fT; + + private static List parameterNames = makeImmutableList("T"); + + private Match(final Turnout pT) { + this.fT = pT; + } + + @Override + public Object get(final String parameterName) { + switch(parameterName) { + case "T": return this.fT; + default: return null; + } + } + + @Override + public Object get(final int index) { + switch(index) { + case 0: return this.fT; + default: return null; + } + } + + public Turnout getT() { + return this.fT; + } + + @Override + public boolean set(final String parameterName, final Object newValue) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + if ("T".equals(parameterName) ) { + this.fT = (Turnout) newValue; + return true; + } + return false; + } + + public void setT(final Turnout pT) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fT = pT; + } + + @Override + public String patternName() { + return "modes3.queries.tooFewInputsOfTurnout"; + } + + @Override + public List parameterNames() { + return TooFewInputsOfTurnout.Match.parameterNames; + } + + @Override + public Object[] toArray() { + return new Object[]{fT}; + } + + @Override + public TooFewInputsOfTurnout.Match toImmutable() { + return isMutable() ? newMatch(fT) : this; + } + + @Override + public String prettyPrint() { + StringBuilder result = new StringBuilder(); + result.append("\"T\"=" + prettyPrintValue(fT)); + return result.toString(); + } + + @Override + public int hashCode() { + return Objects.hash(fT); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) { + return false; + } + if ((obj instanceof TooFewInputsOfTurnout.Match)) { + TooFewInputsOfTurnout.Match other = (TooFewInputsOfTurnout.Match) obj; + return Objects.equals(fT, other.fT); + } else { + // this should be infrequent + if (!(obj instanceof IPatternMatch)) { + return false; + } + IPatternMatch otherSig = (IPatternMatch) obj; + return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray()); + } + } + + @Override + public TooFewInputsOfTurnout specification() { + return TooFewInputsOfTurnout.instance(); + } + + /** + * Returns an empty, mutable match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @return the empty match. + * + */ + public static TooFewInputsOfTurnout.Match newEmptyMatch() { + return new Mutable(null); + } + + /** + * Returns a mutable (partial) match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return the new, mutable (partial) match object. + * + */ + public static TooFewInputsOfTurnout.Match newMutableMatch(final Turnout pT) { + return new Mutable(pT); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return the (partial) match object. + * + */ + public static TooFewInputsOfTurnout.Match newMatch(final Turnout pT) { + return new Immutable(pT); + } + + private static final class Mutable extends TooFewInputsOfTurnout.Match { + Mutable(final Turnout pT) { + super(pT); + } + + @Override + public boolean isMutable() { + return true; + } + } + + private static final class Immutable extends TooFewInputsOfTurnout.Match { + Immutable(final Turnout pT) { + super(pT); + } + + @Override + public boolean isMutable() { + return false; + } + } + } + + /** + * Generated pattern matcher API of the modes3.queries.tooFewInputsOfTurnout pattern, + * providing pattern-specific query methods. + * + *

Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)}, + * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}. + * + *

Matches of the pattern will be represented as {@link Match}. + * + *

Original source: + *

+   * {@literal @}Constraint(message = "tooFewInputsOfTurnout", severity = "error", key = { T })
+   * pattern tooFewInputsOfTurnout(T : Turnout) {
+   * 	neg find inputsOfTurnout(T);
+   * }
+   * 
+ * + * @see Match + * @see TooFewInputsOfTurnout + * + */ + public static class Matcher extends BaseMatcher { + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + public static TooFewInputsOfTurnout.Matcher on(final ViatraQueryEngine engine) { + // check if matcher already exists + Matcher matcher = engine.getExistingMatcher(querySpecification()); + if (matcher == null) { + matcher = (Matcher)engine.getMatcher(querySpecification()); + } + return matcher; + } + + /** + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * @return an initialized matcher + * @noreference This method is for internal matcher initialization by the framework, do not call it manually. + * + */ + public static TooFewInputsOfTurnout.Matcher create() { + return new Matcher(); + } + + private static final int POSITION_T = 0; + + private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(TooFewInputsOfTurnout.Matcher.class); + + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + private Matcher() { + super(querySpecification()); + } + + /** + * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return matches represented as a Match object. + * + */ + public Collection getAllMatches(final Turnout pT) { + return rawStreamAllMatches(new Object[]{pT}).collect(Collectors.toSet()); + } + + /** + * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return a stream of matches represented as a Match object. + * + */ + public Stream streamAllMatches(final Turnout pT) { + return rawStreamAllMatches(new Object[]{pT}); + } + + /** + * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return a match represented as a Match object, or null if no match is found. + * + */ + public Optional getOneArbitraryMatch(final Turnout pT) { + return rawGetOneArbitraryMatch(new Object[]{pT}); + } + + /** + * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, + * under any possible substitution of the unspecified parameters (if any). + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return true if the input is a valid (partial) match of the pattern. + * + */ + public boolean hasMatch(final Turnout pT) { + return rawHasMatch(new Object[]{pT}); + } + + /** + * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return the number of pattern matches found. + * + */ + public int countMatches(final Turnout pT) { + return rawCountMatches(new Object[]{pT}); + } + + /** + * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @param processor the action that will process the selected match. + * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked + * + */ + public boolean forOneArbitraryMatch(final Turnout pT, final Consumer processor) { + return rawForOneArbitraryMatch(new Object[]{pT}, processor); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return the (partial) match object. + * + */ + public TooFewInputsOfTurnout.Match newMatch(final Turnout pT) { + return TooFewInputsOfTurnout.Match.newMatch(pT); + } + + /** + * Retrieve the set of values that occur in matches for T. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOfT(final Object[] parameters) { + return rawStreamAllValues(POSITION_T, parameters).map(Turnout.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for T. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOfT() { + return rawStreamAllValuesOfT(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for T. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOfT() { + return rawStreamAllValuesOfT(emptyArray()); + } + + @Override + protected TooFewInputsOfTurnout.Match tupleToMatch(final Tuple t) { + try { + return TooFewInputsOfTurnout.Match.newMatch((Turnout) t.get(POSITION_T)); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in tuple not properly typed!",e); + return null; + } + } + + @Override + protected TooFewInputsOfTurnout.Match arrayToMatch(final Object[] match) { + try { + return TooFewInputsOfTurnout.Match.newMatch((Turnout) match[POSITION_T]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + @Override + protected TooFewInputsOfTurnout.Match arrayToMatchMutable(final Object[] match) { + try { + return TooFewInputsOfTurnout.Match.newMutableMatch((Turnout) match[POSITION_T]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + /** + * @return the singleton instance of the query specification of this pattern + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static IQuerySpecification querySpecification() { + return TooFewInputsOfTurnout.instance(); + } + } + + private TooFewInputsOfTurnout() { + super(GeneratedPQuery.INSTANCE); + } + + /** + * @return the singleton instance of the query specification + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static TooFewInputsOfTurnout instance() { + try{ + return LazyHolder.INSTANCE; + } catch (ExceptionInInitializerError err) { + throw processInitializerError(err); + } + } + + @Override + protected TooFewInputsOfTurnout.Matcher instantiate(final ViatraQueryEngine engine) { + return TooFewInputsOfTurnout.Matcher.on(engine); + } + + @Override + public TooFewInputsOfTurnout.Matcher instantiate() { + return TooFewInputsOfTurnout.Matcher.create(); + } + + @Override + public TooFewInputsOfTurnout.Match newEmptyMatch() { + return TooFewInputsOfTurnout.Match.newEmptyMatch(); + } + + @Override + public TooFewInputsOfTurnout.Match newMatch(final Object... parameters) { + return TooFewInputsOfTurnout.Match.newMatch((modes3.Turnout) parameters[0]); + } + + /** + * Inner class allowing the singleton instance of {@link TooFewInputsOfTurnout} to be created + * not at the class load time of the outer class, + * but rather at the first call to {@link TooFewInputsOfTurnout#instance()}. + * + *

This workaround is required e.g. to support recursion. + * + */ + private static class LazyHolder { + private static final TooFewInputsOfTurnout INSTANCE = new TooFewInputsOfTurnout(); + + /** + * Statically initializes the query specification after the field {@link #INSTANCE} is assigned. + * This initialization order is required to support indirect recursion. + * + *

The static initializer is defined using a helper field to work around limitations of the code generator. + * + */ + private static final Object STATIC_INITIALIZER = ensureInitialized(); + + public static Object ensureInitialized() { + INSTANCE.ensureInitializedInternal(); + return null; + } + } + + private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { + private static final TooFewInputsOfTurnout.GeneratedPQuery INSTANCE = new GeneratedPQuery(); + + private final PParameter parameter_T = new PParameter("T", "modes3.Turnout", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Turnout")), PParameterDirection.INOUT); + + private final List parameters = Arrays.asList(parameter_T); + + private GeneratedPQuery() { + super(PVisibility.PUBLIC); + } + + @Override + public String getFullyQualifiedName() { + return "modes3.queries.tooFewInputsOfTurnout"; + } + + @Override + public List getParameterNames() { + return Arrays.asList("T"); + } + + @Override + public List getParameters() { + return parameters; + } + + @Override + public Set doGetContainedBodies() { + setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED)); + Set bodies = new LinkedHashSet<>(); + { + PBody body = new PBody(this); + PVariable var_T = body.getOrCreateVariableByName("T"); + new TypeConstraint(body, Tuples.flatTupleOf(var_T), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Turnout"))); + body.setSymbolicParameters(Arrays.asList( + new ExportedParameter(body, var_T, parameter_T) + )); + // neg find inputsOfTurnout(T) + new NegativePatternCall(body, Tuples.flatTupleOf(var_T), InputsOfTurnout.instance().getInternalQueryRepresentation()); + bodies.add(body); + } + { + PAnnotation annotation = new PAnnotation("Constraint"); + annotation.addAttribute("message", "tooFewInputsOfTurnout"); + annotation.addAttribute("severity", "error"); + annotation.addAttribute("key", Arrays.asList(new Object[] { + new ParameterReference("T") + })); + addAnnotation(annotation); + } + return bodies; + } + } +} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooManyExtraInputsOfTurnout.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooManyExtraInputsOfTurnout.java deleted file mode 100644 index 9f417795..00000000 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooManyExtraInputsOfTurnout.java +++ /dev/null @@ -1,570 +0,0 @@ -/** - * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql - */ -package modes3.queries; - -import java.util.Arrays; -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.function.Consumer; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import modes3.Turnout; -import modes3.queries.ExtraInputOfTurnout; -import org.apache.log4j.Logger; -import org.eclipse.emf.ecore.EClass; -import org.eclipse.viatra.query.runtime.api.IPatternMatch; -import org.eclipse.viatra.query.runtime.api.IQuerySpecification; -import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine; -import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery; -import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification; -import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher; -import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch; -import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey; -import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint; -import org.eclipse.viatra.query.runtime.matchers.psystem.PBody; -import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable; -import org.eclipse.viatra.query.runtime.matchers.psystem.annotations.PAnnotation; -import org.eclipse.viatra.query.runtime.matchers.psystem.annotations.ParameterReference; -import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter; -import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Inequality; -import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.PositivePatternCall; -import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint; -import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter; -import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection; -import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility; -import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple; -import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples; -import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil; - -/** - * A pattern-specific query specification that can instantiate Matcher in a type-safe way. - * - *

Original source: - *

- *         {@literal @}Constraint(message = "tooManyExtraInputsOfTurnout", severity = "error", key = { T })
- *         pattern tooManyExtraInputsOfTurnout(T : Turnout) {
- *         	find extraInputOfTurnout(T, I1);
- *         	find extraInputOfTurnout(T, I2);
- *         	I1 != I2;
- *         }
- * 
- * - * @see Matcher - * @see Match - * - */ -@SuppressWarnings("all") -public final class TooManyExtraInputsOfTurnout extends BaseGeneratedEMFQuerySpecification { - /** - * Pattern-specific match representation of the modes3.queries.tooManyExtraInputsOfTurnout pattern, - * to be used in conjunction with {@link Matcher}. - * - *

Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned. - * Each instance is a (possibly partial) substitution of pattern parameters, - * usable to represent a match of the pattern in the result of a query, - * or to specify the bound (fixed) input parameters when issuing a query. - * - * @see Matcher - * - */ - public static abstract class Match extends BasePatternMatch { - private Turnout fT; - - private static List parameterNames = makeImmutableList("T"); - - private Match(final Turnout pT) { - this.fT = pT; - } - - @Override - public Object get(final String parameterName) { - switch(parameterName) { - case "T": return this.fT; - default: return null; - } - } - - @Override - public Object get(final int index) { - switch(index) { - case 0: return this.fT; - default: return null; - } - } - - public Turnout getT() { - return this.fT; - } - - @Override - public boolean set(final String parameterName, final Object newValue) { - if (!isMutable()) throw new java.lang.UnsupportedOperationException(); - if ("T".equals(parameterName) ) { - this.fT = (Turnout) newValue; - return true; - } - return false; - } - - public void setT(final Turnout pT) { - if (!isMutable()) throw new java.lang.UnsupportedOperationException(); - this.fT = pT; - } - - @Override - public String patternName() { - return "modes3.queries.tooManyExtraInputsOfTurnout"; - } - - @Override - public List parameterNames() { - return TooManyExtraInputsOfTurnout.Match.parameterNames; - } - - @Override - public Object[] toArray() { - return new Object[]{fT}; - } - - @Override - public TooManyExtraInputsOfTurnout.Match toImmutable() { - return isMutable() ? newMatch(fT) : this; - } - - @Override - public String prettyPrint() { - StringBuilder result = new StringBuilder(); - result.append("\"T\"=" + prettyPrintValue(fT)); - return result.toString(); - } - - @Override - public int hashCode() { - return Objects.hash(fT); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) { - return false; - } - if ((obj instanceof TooManyExtraInputsOfTurnout.Match)) { - TooManyExtraInputsOfTurnout.Match other = (TooManyExtraInputsOfTurnout.Match) obj; - return Objects.equals(fT, other.fT); - } else { - // this should be infrequent - if (!(obj instanceof IPatternMatch)) { - return false; - } - IPatternMatch otherSig = (IPatternMatch) obj; - return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray()); - } - } - - @Override - public TooManyExtraInputsOfTurnout specification() { - return TooManyExtraInputsOfTurnout.instance(); - } - - /** - * Returns an empty, mutable match. - * Fields of the mutable match can be filled to create a partial match, usable as matcher input. - * - * @return the empty match. - * - */ - public static TooManyExtraInputsOfTurnout.Match newEmptyMatch() { - return new Mutable(null); - } - - /** - * Returns a mutable (partial) match. - * Fields of the mutable match can be filled to create a partial match, usable as matcher input. - * - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return the new, mutable (partial) match object. - * - */ - public static TooManyExtraInputsOfTurnout.Match newMutableMatch(final Turnout pT) { - return new Mutable(pT); - } - - /** - * Returns a new (partial) match. - * This can be used e.g. to call the matcher with a partial match. - *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return the (partial) match object. - * - */ - public static TooManyExtraInputsOfTurnout.Match newMatch(final Turnout pT) { - return new Immutable(pT); - } - - private static final class Mutable extends TooManyExtraInputsOfTurnout.Match { - Mutable(final Turnout pT) { - super(pT); - } - - @Override - public boolean isMutable() { - return true; - } - } - - private static final class Immutable extends TooManyExtraInputsOfTurnout.Match { - Immutable(final Turnout pT) { - super(pT); - } - - @Override - public boolean isMutable() { - return false; - } - } - } - - /** - * Generated pattern matcher API of the modes3.queries.tooManyExtraInputsOfTurnout pattern, - * providing pattern-specific query methods. - * - *

Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)}, - * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}. - * - *

Matches of the pattern will be represented as {@link Match}. - * - *

Original source: - *

-   * {@literal @}Constraint(message = "tooManyExtraInputsOfTurnout", severity = "error", key = { T })
-   * pattern tooManyExtraInputsOfTurnout(T : Turnout) {
-   * 	find extraInputOfTurnout(T, I1);
-   * 	find extraInputOfTurnout(T, I2);
-   * 	I1 != I2;
-   * }
-   * 
- * - * @see Match - * @see TooManyExtraInputsOfTurnout - * - */ - public static class Matcher extends BaseMatcher { - /** - * Initializes the pattern matcher within an existing VIATRA Query engine. - * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. - * - * @param engine the existing VIATRA Query engine in which this matcher will be created. - * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation - * - */ - public static TooManyExtraInputsOfTurnout.Matcher on(final ViatraQueryEngine engine) { - // check if matcher already exists - Matcher matcher = engine.getExistingMatcher(querySpecification()); - if (matcher == null) { - matcher = (Matcher)engine.getMatcher(querySpecification()); - } - return matcher; - } - - /** - * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation - * @return an initialized matcher - * @noreference This method is for internal matcher initialization by the framework, do not call it manually. - * - */ - public static TooManyExtraInputsOfTurnout.Matcher create() { - return new Matcher(); - } - - private static final int POSITION_T = 0; - - private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(TooManyExtraInputsOfTurnout.Matcher.class); - - /** - * Initializes the pattern matcher within an existing VIATRA Query engine. - * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. - * - * @param engine the existing VIATRA Query engine in which this matcher will be created. - * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation - * - */ - private Matcher() { - super(querySpecification()); - } - - /** - * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return matches represented as a Match object. - * - */ - public Collection getAllMatches(final Turnout pT) { - return rawStreamAllMatches(new Object[]{pT}).collect(Collectors.toSet()); - } - - /** - * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters. - *

- * NOTE: It is important not to modify the source model while the stream is being processed. - * If the match set of the pattern changes during processing, the contents of the stream is undefined. - * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return a stream of matches represented as a Match object. - * - */ - public Stream streamAllMatches(final Turnout pT) { - return rawStreamAllMatches(new Object[]{pT}); - } - - /** - * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. - * Neither determinism nor randomness of selection is guaranteed. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return a match represented as a Match object, or null if no match is found. - * - */ - public Optional getOneArbitraryMatch(final Turnout pT) { - return rawGetOneArbitraryMatch(new Object[]{pT}); - } - - /** - * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, - * under any possible substitution of the unspecified parameters (if any). - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return true if the input is a valid (partial) match of the pattern. - * - */ - public boolean hasMatch(final Turnout pT) { - return rawHasMatch(new Object[]{pT}); - } - - /** - * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return the number of pattern matches found. - * - */ - public int countMatches(final Turnout pT) { - return rawCountMatches(new Object[]{pT}); - } - - /** - * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. - * Neither determinism nor randomness of selection is guaranteed. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @param processor the action that will process the selected match. - * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked - * - */ - public boolean forOneArbitraryMatch(final Turnout pT, final Consumer processor) { - return rawForOneArbitraryMatch(new Object[]{pT}, processor); - } - - /** - * Returns a new (partial) match. - * This can be used e.g. to call the matcher with a partial match. - *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return the (partial) match object. - * - */ - public TooManyExtraInputsOfTurnout.Match newMatch(final Turnout pT) { - return TooManyExtraInputsOfTurnout.Match.newMatch(pT); - } - - /** - * Retrieve the set of values that occur in matches for T. - * @return the Set of all values or empty set if there are no matches - * - */ - protected Stream rawStreamAllValuesOfT(final Object[] parameters) { - return rawStreamAllValues(POSITION_T, parameters).map(Turnout.class::cast); - } - - /** - * Retrieve the set of values that occur in matches for T. - * @return the Set of all values or empty set if there are no matches - * - */ - public Set getAllValuesOfT() { - return rawStreamAllValuesOfT(emptyArray()).collect(Collectors.toSet()); - } - - /** - * Retrieve the set of values that occur in matches for T. - * @return the Set of all values or empty set if there are no matches - * - */ - public Stream streamAllValuesOfT() { - return rawStreamAllValuesOfT(emptyArray()); - } - - @Override - protected TooManyExtraInputsOfTurnout.Match tupleToMatch(final Tuple t) { - try { - return TooManyExtraInputsOfTurnout.Match.newMatch((Turnout) t.get(POSITION_T)); - } catch(ClassCastException e) { - LOGGER.error("Element(s) in tuple not properly typed!",e); - return null; - } - } - - @Override - protected TooManyExtraInputsOfTurnout.Match arrayToMatch(final Object[] match) { - try { - return TooManyExtraInputsOfTurnout.Match.newMatch((Turnout) match[POSITION_T]); - } catch(ClassCastException e) { - LOGGER.error("Element(s) in array not properly typed!",e); - return null; - } - } - - @Override - protected TooManyExtraInputsOfTurnout.Match arrayToMatchMutable(final Object[] match) { - try { - return TooManyExtraInputsOfTurnout.Match.newMutableMatch((Turnout) match[POSITION_T]); - } catch(ClassCastException e) { - LOGGER.error("Element(s) in array not properly typed!",e); - return null; - } - } - - /** - * @return the singleton instance of the query specification of this pattern - * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded - * - */ - public static IQuerySpecification querySpecification() { - return TooManyExtraInputsOfTurnout.instance(); - } - } - - private TooManyExtraInputsOfTurnout() { - super(GeneratedPQuery.INSTANCE); - } - - /** - * @return the singleton instance of the query specification - * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded - * - */ - public static TooManyExtraInputsOfTurnout instance() { - try{ - return LazyHolder.INSTANCE; - } catch (ExceptionInInitializerError err) { - throw processInitializerError(err); - } - } - - @Override - protected TooManyExtraInputsOfTurnout.Matcher instantiate(final ViatraQueryEngine engine) { - return TooManyExtraInputsOfTurnout.Matcher.on(engine); - } - - @Override - public TooManyExtraInputsOfTurnout.Matcher instantiate() { - return TooManyExtraInputsOfTurnout.Matcher.create(); - } - - @Override - public TooManyExtraInputsOfTurnout.Match newEmptyMatch() { - return TooManyExtraInputsOfTurnout.Match.newEmptyMatch(); - } - - @Override - public TooManyExtraInputsOfTurnout.Match newMatch(final Object... parameters) { - return TooManyExtraInputsOfTurnout.Match.newMatch((modes3.Turnout) parameters[0]); - } - - /** - * Inner class allowing the singleton instance of {@link TooManyExtraInputsOfTurnout} to be created - * not at the class load time of the outer class, - * but rather at the first call to {@link TooManyExtraInputsOfTurnout#instance()}. - * - *

This workaround is required e.g. to support recursion. - * - */ - private static class LazyHolder { - private static final TooManyExtraInputsOfTurnout INSTANCE = new TooManyExtraInputsOfTurnout(); - - /** - * Statically initializes the query specification after the field {@link #INSTANCE} is assigned. - * This initialization order is required to support indirect recursion. - * - *

The static initializer is defined using a helper field to work around limitations of the code generator. - * - */ - private static final Object STATIC_INITIALIZER = ensureInitialized(); - - public static Object ensureInitialized() { - INSTANCE.ensureInitializedInternal(); - return null; - } - } - - private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { - private static final TooManyExtraInputsOfTurnout.GeneratedPQuery INSTANCE = new GeneratedPQuery(); - - private final PParameter parameter_T = new PParameter("T", "modes3.Turnout", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Turnout")), PParameterDirection.INOUT); - - private final List parameters = Arrays.asList(parameter_T); - - private GeneratedPQuery() { - super(PVisibility.PUBLIC); - } - - @Override - public String getFullyQualifiedName() { - return "modes3.queries.tooManyExtraInputsOfTurnout"; - } - - @Override - public List getParameterNames() { - return Arrays.asList("T"); - } - - @Override - public List getParameters() { - return parameters; - } - - @Override - public Set doGetContainedBodies() { - setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED)); - Set bodies = new LinkedHashSet<>(); - { - PBody body = new PBody(this); - PVariable var_T = body.getOrCreateVariableByName("T"); - PVariable var_I1 = body.getOrCreateVariableByName("I1"); - PVariable var_I2 = body.getOrCreateVariableByName("I2"); - new TypeConstraint(body, Tuples.flatTupleOf(var_T), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Turnout"))); - body.setSymbolicParameters(Arrays.asList( - new ExportedParameter(body, var_T, parameter_T) - )); - // find extraInputOfTurnout(T, I1) - new PositivePatternCall(body, Tuples.flatTupleOf(var_T, var_I1), ExtraInputOfTurnout.instance().getInternalQueryRepresentation()); - // find extraInputOfTurnout(T, I2) - new PositivePatternCall(body, Tuples.flatTupleOf(var_T, var_I2), ExtraInputOfTurnout.instance().getInternalQueryRepresentation()); - // I1 != I2 - new Inequality(body, var_I1, var_I2); - bodies.add(body); - } - { - PAnnotation annotation = new PAnnotation("Constraint"); - annotation.addAttribute("message", "tooManyExtraInputsOfTurnout"); - annotation.addAttribute("severity", "error"); - annotation.addAttribute("key", Arrays.asList(new Object[] { - new ParameterReference("T") - })); - addAnnotation(annotation); - } - return bodies; - } - } -} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooManyInputsOfSegment.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooManyInputsOfSegment.java index e5e8827c..ff82dda1 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooManyInputsOfSegment.java +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooManyInputsOfSegment.java @@ -13,9 +13,8 @@ import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; -import modes3.Segment; +import modes3.SimpleSegment; import modes3.queries.Output; -import modes3.queries.Turnout; import org.apache.log4j.Logger; import org.eclipse.emf.ecore.EClass; import org.eclipse.viatra.query.runtime.api.IPatternMatch; @@ -33,7 +32,6 @@ import org.eclipse.viatra.query.runtime.matchers.psystem.annotations.PAnnotation import org.eclipse.viatra.query.runtime.matchers.psystem.annotations.ParameterReference; import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter; import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Inequality; -import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.NegativePatternCall; import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.PositivePatternCall; import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint; import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter; @@ -55,8 +53,7 @@ import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil; * //} * * {@literal @}Constraint(message = "tooManyInputsOfSegment", severity = "error", key = { S }) - * pattern tooManyInputsOfSegment(S : Segment) { - * neg find turnout(S); + * pattern tooManyInputsOfSegment(S : SimpleSegment) { * find output(I1, S); * find output(I2, S); * find output(I3, S); @@ -85,11 +82,11 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica * */ public static abstract class Match extends BasePatternMatch { - private Segment fS; + private SimpleSegment fS; private static List parameterNames = makeImmutableList("S"); - private Match(final Segment pS) { + private Match(final SimpleSegment pS) { this.fS = pS; } @@ -109,7 +106,7 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica } } - public Segment getS() { + public SimpleSegment getS() { return this.fS; } @@ -117,13 +114,13 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica public boolean set(final String parameterName, final Object newValue) { if (!isMutable()) throw new java.lang.UnsupportedOperationException(); if ("S".equals(parameterName) ) { - this.fS = (Segment) newValue; + this.fS = (SimpleSegment) newValue; return true; } return false; } - public void setS(final Segment pS) { + public void setS(final SimpleSegment pS) { if (!isMutable()) throw new java.lang.UnsupportedOperationException(); this.fS = pS; } @@ -204,7 +201,7 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica * @return the new, mutable (partial) match object. * */ - public static TooManyInputsOfSegment.Match newMutableMatch(final Segment pS) { + public static TooManyInputsOfSegment.Match newMutableMatch(final SimpleSegment pS) { return new Mutable(pS); } @@ -216,12 +213,12 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica * @return the (partial) match object. * */ - public static TooManyInputsOfSegment.Match newMatch(final Segment pS) { + public static TooManyInputsOfSegment.Match newMatch(final SimpleSegment pS) { return new Immutable(pS); } private static final class Mutable extends TooManyInputsOfSegment.Match { - Mutable(final Segment pS) { + Mutable(final SimpleSegment pS) { super(pS); } @@ -232,7 +229,7 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica } private static final class Immutable extends TooManyInputsOfSegment.Match { - Immutable(final Segment pS) { + Immutable(final SimpleSegment pS) { super(pS); } @@ -261,8 +258,7 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica * //} * * {@literal @}Constraint(message = "tooManyInputsOfSegment", severity = "error", key = { S }) - * pattern tooManyInputsOfSegment(S : Segment) { - * neg find turnout(S); + * pattern tooManyInputsOfSegment(S : SimpleSegment) { * find output(I1, S); * find output(I2, S); * find output(I3, S); @@ -326,7 +322,7 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica * @return matches represented as a Match object. * */ - public Collection getAllMatches(final Segment pS) { + public Collection getAllMatches(final SimpleSegment pS) { return rawStreamAllMatches(new Object[]{pS}).collect(Collectors.toSet()); } @@ -340,7 +336,7 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica * @return a stream of matches represented as a Match object. * */ - public Stream streamAllMatches(final Segment pS) { + public Stream streamAllMatches(final SimpleSegment pS) { return rawStreamAllMatches(new Object[]{pS}); } @@ -351,7 +347,7 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica * @return a match represented as a Match object, or null if no match is found. * */ - public Optional getOneArbitraryMatch(final Segment pS) { + public Optional getOneArbitraryMatch(final SimpleSegment pS) { return rawGetOneArbitraryMatch(new Object[]{pS}); } @@ -362,7 +358,7 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica * @return true if the input is a valid (partial) match of the pattern. * */ - public boolean hasMatch(final Segment pS) { + public boolean hasMatch(final SimpleSegment pS) { return rawHasMatch(new Object[]{pS}); } @@ -372,7 +368,7 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica * @return the number of pattern matches found. * */ - public int countMatches(final Segment pS) { + public int countMatches(final SimpleSegment pS) { return rawCountMatches(new Object[]{pS}); } @@ -384,7 +380,7 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked * */ - public boolean forOneArbitraryMatch(final Segment pS, final Consumer processor) { + public boolean forOneArbitraryMatch(final SimpleSegment pS, final Consumer processor) { return rawForOneArbitraryMatch(new Object[]{pS}, processor); } @@ -396,7 +392,7 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica * @return the (partial) match object. * */ - public TooManyInputsOfSegment.Match newMatch(final Segment pS) { + public TooManyInputsOfSegment.Match newMatch(final SimpleSegment pS) { return TooManyInputsOfSegment.Match.newMatch(pS); } @@ -405,8 +401,8 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica * @return the Set of all values or empty set if there are no matches * */ - protected Stream rawStreamAllValuesOfS(final Object[] parameters) { - return rawStreamAllValues(POSITION_S, parameters).map(Segment.class::cast); + protected Stream rawStreamAllValuesOfS(final Object[] parameters) { + return rawStreamAllValues(POSITION_S, parameters).map(SimpleSegment.class::cast); } /** @@ -414,7 +410,7 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica * @return the Set of all values or empty set if there are no matches * */ - public Set getAllValuesOfS() { + public Set getAllValuesOfS() { return rawStreamAllValuesOfS(emptyArray()).collect(Collectors.toSet()); } @@ -423,14 +419,14 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica * @return the Set of all values or empty set if there are no matches * */ - public Stream streamAllValuesOfS() { + public Stream streamAllValuesOfS() { return rawStreamAllValuesOfS(emptyArray()); } @Override protected TooManyInputsOfSegment.Match tupleToMatch(final Tuple t) { try { - return TooManyInputsOfSegment.Match.newMatch((Segment) t.get(POSITION_S)); + return TooManyInputsOfSegment.Match.newMatch((SimpleSegment) t.get(POSITION_S)); } catch(ClassCastException e) { LOGGER.error("Element(s) in tuple not properly typed!",e); return null; @@ -440,7 +436,7 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica @Override protected TooManyInputsOfSegment.Match arrayToMatch(final Object[] match) { try { - return TooManyInputsOfSegment.Match.newMatch((Segment) match[POSITION_S]); + return TooManyInputsOfSegment.Match.newMatch((SimpleSegment) match[POSITION_S]); } catch(ClassCastException e) { LOGGER.error("Element(s) in array not properly typed!",e); return null; @@ -450,7 +446,7 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica @Override protected TooManyInputsOfSegment.Match arrayToMatchMutable(final Object[] match) { try { - return TooManyInputsOfSegment.Match.newMutableMatch((Segment) match[POSITION_S]); + return TooManyInputsOfSegment.Match.newMutableMatch((SimpleSegment) match[POSITION_S]); } catch(ClassCastException e) { LOGGER.error("Element(s) in array not properly typed!",e); return null; @@ -501,7 +497,7 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica @Override public TooManyInputsOfSegment.Match newMatch(final Object... parameters) { - return TooManyInputsOfSegment.Match.newMatch((modes3.Segment) parameters[0]); + return TooManyInputsOfSegment.Match.newMatch((modes3.SimpleSegment) parameters[0]); } /** @@ -533,7 +529,7 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { private static final TooManyInputsOfSegment.GeneratedPQuery INSTANCE = new GeneratedPQuery(); - private final PParameter parameter_S = new PParameter("S", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT); + private final PParameter parameter_S = new PParameter("S", "modes3.SimpleSegment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "SimpleSegment")), PParameterDirection.INOUT); private final List parameters = Arrays.asList(parameter_S); @@ -566,12 +562,10 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica PVariable var_I1 = body.getOrCreateVariableByName("I1"); PVariable var_I2 = body.getOrCreateVariableByName("I2"); PVariable var_I3 = body.getOrCreateVariableByName("I3"); - new TypeConstraint(body, Tuples.flatTupleOf(var_S), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + new TypeConstraint(body, Tuples.flatTupleOf(var_S), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "SimpleSegment"))); body.setSymbolicParameters(Arrays.asList( new ExportedParameter(body, var_S, parameter_S) )); - // neg find turnout(S) - new NegativePatternCall(body, Tuples.flatTupleOf(var_S), Turnout.instance().getInternalQueryRepresentation()); // find output(I1, S) new PositivePatternCall(body, Tuples.flatTupleOf(var_I1, var_S), Output.instance().getInternalQueryRepresentation()); // find output(I2, S) diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooManyInputsOfTurnout.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooManyInputsOfTurnout.java new file mode 100644 index 00000000..93076cbb --- /dev/null +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooManyInputsOfTurnout.java @@ -0,0 +1,600 @@ +/** + * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql + */ +package modes3.queries; + +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import modes3.Turnout; +import modes3.queries.Adjacent; +import org.apache.log4j.Logger; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.viatra.query.runtime.api.IPatternMatch; +import org.eclipse.viatra.query.runtime.api.IQuerySpecification; +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification; +import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher; +import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch; +import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey; +import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint; +import org.eclipse.viatra.query.runtime.matchers.psystem.PBody; +import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable; +import org.eclipse.viatra.query.runtime.matchers.psystem.annotations.PAnnotation; +import org.eclipse.viatra.query.runtime.matchers.psystem.annotations.ParameterReference; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Inequality; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.PositivePatternCall; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples; +import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil; + +/** + * A pattern-specific query specification that can instantiate Matcher in a type-safe way. + * + *

Original source: + *

+ *         {@literal @}Constraint(message = "turnoutConnectedToBothOutputs", severity = "error", key = { T })
+ *         pattern tooManyInputsOfTurnout(T : Turnout) {
+ *         	find adjacent(I1, T);
+ *         	find adjacent(I2, T);
+ *         	find adjacent(I3, T);
+ *         	find adjacent(I4, T);
+ *         	I1 != I2;
+ *         	I1 != I3;
+ *         	I1 != I4;
+ *         	I2 != I3;
+ *         	I2 != I4;
+ *         	I3 != I4;
+ *         }
+ * 
+ * + * @see Matcher + * @see Match + * + */ +@SuppressWarnings("all") +public final class TooManyInputsOfTurnout extends BaseGeneratedEMFQuerySpecification { + /** + * Pattern-specific match representation of the modes3.queries.tooManyInputsOfTurnout pattern, + * to be used in conjunction with {@link Matcher}. + * + *

Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned. + * Each instance is a (possibly partial) substitution of pattern parameters, + * usable to represent a match of the pattern in the result of a query, + * or to specify the bound (fixed) input parameters when issuing a query. + * + * @see Matcher + * + */ + public static abstract class Match extends BasePatternMatch { + private Turnout fT; + + private static List parameterNames = makeImmutableList("T"); + + private Match(final Turnout pT) { + this.fT = pT; + } + + @Override + public Object get(final String parameterName) { + switch(parameterName) { + case "T": return this.fT; + default: return null; + } + } + + @Override + public Object get(final int index) { + switch(index) { + case 0: return this.fT; + default: return null; + } + } + + public Turnout getT() { + return this.fT; + } + + @Override + public boolean set(final String parameterName, final Object newValue) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + if ("T".equals(parameterName) ) { + this.fT = (Turnout) newValue; + return true; + } + return false; + } + + public void setT(final Turnout pT) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fT = pT; + } + + @Override + public String patternName() { + return "modes3.queries.tooManyInputsOfTurnout"; + } + + @Override + public List parameterNames() { + return TooManyInputsOfTurnout.Match.parameterNames; + } + + @Override + public Object[] toArray() { + return new Object[]{fT}; + } + + @Override + public TooManyInputsOfTurnout.Match toImmutable() { + return isMutable() ? newMatch(fT) : this; + } + + @Override + public String prettyPrint() { + StringBuilder result = new StringBuilder(); + result.append("\"T\"=" + prettyPrintValue(fT)); + return result.toString(); + } + + @Override + public int hashCode() { + return Objects.hash(fT); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) { + return false; + } + if ((obj instanceof TooManyInputsOfTurnout.Match)) { + TooManyInputsOfTurnout.Match other = (TooManyInputsOfTurnout.Match) obj; + return Objects.equals(fT, other.fT); + } else { + // this should be infrequent + if (!(obj instanceof IPatternMatch)) { + return false; + } + IPatternMatch otherSig = (IPatternMatch) obj; + return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray()); + } + } + + @Override + public TooManyInputsOfTurnout specification() { + return TooManyInputsOfTurnout.instance(); + } + + /** + * Returns an empty, mutable match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @return the empty match. + * + */ + public static TooManyInputsOfTurnout.Match newEmptyMatch() { + return new Mutable(null); + } + + /** + * Returns a mutable (partial) match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return the new, mutable (partial) match object. + * + */ + public static TooManyInputsOfTurnout.Match newMutableMatch(final Turnout pT) { + return new Mutable(pT); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return the (partial) match object. + * + */ + public static TooManyInputsOfTurnout.Match newMatch(final Turnout pT) { + return new Immutable(pT); + } + + private static final class Mutable extends TooManyInputsOfTurnout.Match { + Mutable(final Turnout pT) { + super(pT); + } + + @Override + public boolean isMutable() { + return true; + } + } + + private static final class Immutable extends TooManyInputsOfTurnout.Match { + Immutable(final Turnout pT) { + super(pT); + } + + @Override + public boolean isMutable() { + return false; + } + } + } + + /** + * Generated pattern matcher API of the modes3.queries.tooManyInputsOfTurnout pattern, + * providing pattern-specific query methods. + * + *

Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)}, + * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}. + * + *

Matches of the pattern will be represented as {@link Match}. + * + *

Original source: + *

+   * {@literal @}Constraint(message = "turnoutConnectedToBothOutputs", severity = "error", key = { T })
+   * pattern tooManyInputsOfTurnout(T : Turnout) {
+   * 	find adjacent(I1, T);
+   * 	find adjacent(I2, T);
+   * 	find adjacent(I3, T);
+   * 	find adjacent(I4, T);
+   * 	I1 != I2;
+   * 	I1 != I3;
+   * 	I1 != I4;
+   * 	I2 != I3;
+   * 	I2 != I4;
+   * 	I3 != I4;
+   * }
+   * 
+ * + * @see Match + * @see TooManyInputsOfTurnout + * + */ + public static class Matcher extends BaseMatcher { + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + public static TooManyInputsOfTurnout.Matcher on(final ViatraQueryEngine engine) { + // check if matcher already exists + Matcher matcher = engine.getExistingMatcher(querySpecification()); + if (matcher == null) { + matcher = (Matcher)engine.getMatcher(querySpecification()); + } + return matcher; + } + + /** + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * @return an initialized matcher + * @noreference This method is for internal matcher initialization by the framework, do not call it manually. + * + */ + public static TooManyInputsOfTurnout.Matcher create() { + return new Matcher(); + } + + private static final int POSITION_T = 0; + + private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(TooManyInputsOfTurnout.Matcher.class); + + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + private Matcher() { + super(querySpecification()); + } + + /** + * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return matches represented as a Match object. + * + */ + public Collection getAllMatches(final Turnout pT) { + return rawStreamAllMatches(new Object[]{pT}).collect(Collectors.toSet()); + } + + /** + * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return a stream of matches represented as a Match object. + * + */ + public Stream streamAllMatches(final Turnout pT) { + return rawStreamAllMatches(new Object[]{pT}); + } + + /** + * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return a match represented as a Match object, or null if no match is found. + * + */ + public Optional getOneArbitraryMatch(final Turnout pT) { + return rawGetOneArbitraryMatch(new Object[]{pT}); + } + + /** + * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, + * under any possible substitution of the unspecified parameters (if any). + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return true if the input is a valid (partial) match of the pattern. + * + */ + public boolean hasMatch(final Turnout pT) { + return rawHasMatch(new Object[]{pT}); + } + + /** + * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return the number of pattern matches found. + * + */ + public int countMatches(final Turnout pT) { + return rawCountMatches(new Object[]{pT}); + } + + /** + * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @param processor the action that will process the selected match. + * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked + * + */ + public boolean forOneArbitraryMatch(final Turnout pT, final Consumer processor) { + return rawForOneArbitraryMatch(new Object[]{pT}, processor); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pT the fixed value of pattern parameter T, or null if not bound. + * @return the (partial) match object. + * + */ + public TooManyInputsOfTurnout.Match newMatch(final Turnout pT) { + return TooManyInputsOfTurnout.Match.newMatch(pT); + } + + /** + * Retrieve the set of values that occur in matches for T. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOfT(final Object[] parameters) { + return rawStreamAllValues(POSITION_T, parameters).map(Turnout.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for T. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOfT() { + return rawStreamAllValuesOfT(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for T. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOfT() { + return rawStreamAllValuesOfT(emptyArray()); + } + + @Override + protected TooManyInputsOfTurnout.Match tupleToMatch(final Tuple t) { + try { + return TooManyInputsOfTurnout.Match.newMatch((Turnout) t.get(POSITION_T)); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in tuple not properly typed!",e); + return null; + } + } + + @Override + protected TooManyInputsOfTurnout.Match arrayToMatch(final Object[] match) { + try { + return TooManyInputsOfTurnout.Match.newMatch((Turnout) match[POSITION_T]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + @Override + protected TooManyInputsOfTurnout.Match arrayToMatchMutable(final Object[] match) { + try { + return TooManyInputsOfTurnout.Match.newMutableMatch((Turnout) match[POSITION_T]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + /** + * @return the singleton instance of the query specification of this pattern + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static IQuerySpecification querySpecification() { + return TooManyInputsOfTurnout.instance(); + } + } + + private TooManyInputsOfTurnout() { + super(GeneratedPQuery.INSTANCE); + } + + /** + * @return the singleton instance of the query specification + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static TooManyInputsOfTurnout instance() { + try{ + return LazyHolder.INSTANCE; + } catch (ExceptionInInitializerError err) { + throw processInitializerError(err); + } + } + + @Override + protected TooManyInputsOfTurnout.Matcher instantiate(final ViatraQueryEngine engine) { + return TooManyInputsOfTurnout.Matcher.on(engine); + } + + @Override + public TooManyInputsOfTurnout.Matcher instantiate() { + return TooManyInputsOfTurnout.Matcher.create(); + } + + @Override + public TooManyInputsOfTurnout.Match newEmptyMatch() { + return TooManyInputsOfTurnout.Match.newEmptyMatch(); + } + + @Override + public TooManyInputsOfTurnout.Match newMatch(final Object... parameters) { + return TooManyInputsOfTurnout.Match.newMatch((modes3.Turnout) parameters[0]); + } + + /** + * Inner class allowing the singleton instance of {@link TooManyInputsOfTurnout} to be created + * not at the class load time of the outer class, + * but rather at the first call to {@link TooManyInputsOfTurnout#instance()}. + * + *

This workaround is required e.g. to support recursion. + * + */ + private static class LazyHolder { + private static final TooManyInputsOfTurnout INSTANCE = new TooManyInputsOfTurnout(); + + /** + * Statically initializes the query specification after the field {@link #INSTANCE} is assigned. + * This initialization order is required to support indirect recursion. + * + *

The static initializer is defined using a helper field to work around limitations of the code generator. + * + */ + private static final Object STATIC_INITIALIZER = ensureInitialized(); + + public static Object ensureInitialized() { + INSTANCE.ensureInitializedInternal(); + return null; + } + } + + private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { + private static final TooManyInputsOfTurnout.GeneratedPQuery INSTANCE = new GeneratedPQuery(); + + private final PParameter parameter_T = new PParameter("T", "modes3.Turnout", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Turnout")), PParameterDirection.INOUT); + + private final List parameters = Arrays.asList(parameter_T); + + private GeneratedPQuery() { + super(PVisibility.PUBLIC); + } + + @Override + public String getFullyQualifiedName() { + return "modes3.queries.tooManyInputsOfTurnout"; + } + + @Override + public List getParameterNames() { + return Arrays.asList("T"); + } + + @Override + public List getParameters() { + return parameters; + } + + @Override + public Set doGetContainedBodies() { + setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED)); + Set bodies = new LinkedHashSet<>(); + { + PBody body = new PBody(this); + PVariable var_T = body.getOrCreateVariableByName("T"); + PVariable var_I1 = body.getOrCreateVariableByName("I1"); + PVariable var_I2 = body.getOrCreateVariableByName("I2"); + PVariable var_I3 = body.getOrCreateVariableByName("I3"); + PVariable var_I4 = body.getOrCreateVariableByName("I4"); + new TypeConstraint(body, Tuples.flatTupleOf(var_T), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Turnout"))); + body.setSymbolicParameters(Arrays.asList( + new ExportedParameter(body, var_T, parameter_T) + )); + // find adjacent(I1, T) + new PositivePatternCall(body, Tuples.flatTupleOf(var_I1, var_T), Adjacent.instance().getInternalQueryRepresentation()); + // find adjacent(I2, T) + new PositivePatternCall(body, Tuples.flatTupleOf(var_I2, var_T), Adjacent.instance().getInternalQueryRepresentation()); + // find adjacent(I3, T) + new PositivePatternCall(body, Tuples.flatTupleOf(var_I3, var_T), Adjacent.instance().getInternalQueryRepresentation()); + // find adjacent(I4, T) + new PositivePatternCall(body, Tuples.flatTupleOf(var_I4, var_T), Adjacent.instance().getInternalQueryRepresentation()); + // I1 != I2 + new Inequality(body, var_I1, var_I2); + // I1 != I3 + new Inequality(body, var_I1, var_I3); + // I1 != I4 + new Inequality(body, var_I1, var_I4); + // I2 != I3 + new Inequality(body, var_I2, var_I3); + // I2 != I4 + new Inequality(body, var_I2, var_I4); + // I3 != I4 + new Inequality(body, var_I3, var_I4); + bodies.add(body); + } + { + PAnnotation annotation = new PAnnotation("Constraint"); + annotation.addAttribute("message", "turnoutConnectedToBothOutputs"); + annotation.addAttribute("severity", "error"); + annotation.addAttribute("key", Arrays.asList(new Object[] { + new ParameterReference("T") + })); + addAnnotation(annotation); + } + return bodies; + } + } +} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/Turnout.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/Turnout.java deleted file mode 100644 index 34c7631c..00000000 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/Turnout.java +++ /dev/null @@ -1,543 +0,0 @@ -/** - * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql - */ -package modes3.queries; - -import java.util.Arrays; -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.function.Consumer; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import org.apache.log4j.Logger; -import org.eclipse.emf.ecore.EClass; -import org.eclipse.viatra.query.runtime.api.IPatternMatch; -import org.eclipse.viatra.query.runtime.api.IQuerySpecification; -import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine; -import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery; -import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification; -import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher; -import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch; -import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey; -import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint; -import org.eclipse.viatra.query.runtime.matchers.psystem.PBody; -import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable; -import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter; -import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint; -import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter; -import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection; -import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility; -import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple; -import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples; -import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil; - -/** - * A pattern-specific query specification that can instantiate Matcher in a type-safe way. - * - *

Original source: - *

- *         pattern turnout(T : Turnout) {
- *         	Turnout(T);
- *         }
- * 
- * - * @see Matcher - * @see Match - * - */ -@SuppressWarnings("all") -public final class Turnout extends BaseGeneratedEMFQuerySpecification { - /** - * Pattern-specific match representation of the modes3.queries.turnout pattern, - * to be used in conjunction with {@link Matcher}. - * - *

Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned. - * Each instance is a (possibly partial) substitution of pattern parameters, - * usable to represent a match of the pattern in the result of a query, - * or to specify the bound (fixed) input parameters when issuing a query. - * - * @see Matcher - * - */ - public static abstract class Match extends BasePatternMatch { - private modes3.Turnout fT; - - private static List parameterNames = makeImmutableList("T"); - - private Match(final modes3.Turnout pT) { - this.fT = pT; - } - - @Override - public Object get(final String parameterName) { - switch(parameterName) { - case "T": return this.fT; - default: return null; - } - } - - @Override - public Object get(final int index) { - switch(index) { - case 0: return this.fT; - default: return null; - } - } - - public modes3.Turnout getT() { - return this.fT; - } - - @Override - public boolean set(final String parameterName, final Object newValue) { - if (!isMutable()) throw new java.lang.UnsupportedOperationException(); - if ("T".equals(parameterName) ) { - this.fT = (modes3.Turnout) newValue; - return true; - } - return false; - } - - public void setT(final modes3.Turnout pT) { - if (!isMutable()) throw new java.lang.UnsupportedOperationException(); - this.fT = pT; - } - - @Override - public String patternName() { - return "modes3.queries.turnout"; - } - - @Override - public List parameterNames() { - return Turnout.Match.parameterNames; - } - - @Override - public Object[] toArray() { - return new Object[]{fT}; - } - - @Override - public Turnout.Match toImmutable() { - return isMutable() ? newMatch(fT) : this; - } - - @Override - public String prettyPrint() { - StringBuilder result = new StringBuilder(); - result.append("\"T\"=" + prettyPrintValue(fT)); - return result.toString(); - } - - @Override - public int hashCode() { - return Objects.hash(fT); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) { - return false; - } - if ((obj instanceof Turnout.Match)) { - Turnout.Match other = (Turnout.Match) obj; - return Objects.equals(fT, other.fT); - } else { - // this should be infrequent - if (!(obj instanceof IPatternMatch)) { - return false; - } - IPatternMatch otherSig = (IPatternMatch) obj; - return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray()); - } - } - - @Override - public Turnout specification() { - return Turnout.instance(); - } - - /** - * Returns an empty, mutable match. - * Fields of the mutable match can be filled to create a partial match, usable as matcher input. - * - * @return the empty match. - * - */ - public static Turnout.Match newEmptyMatch() { - return new Mutable(null); - } - - /** - * Returns a mutable (partial) match. - * Fields of the mutable match can be filled to create a partial match, usable as matcher input. - * - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return the new, mutable (partial) match object. - * - */ - public static Turnout.Match newMutableMatch(final modes3.Turnout pT) { - return new Mutable(pT); - } - - /** - * Returns a new (partial) match. - * This can be used e.g. to call the matcher with a partial match. - *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return the (partial) match object. - * - */ - public static Turnout.Match newMatch(final modes3.Turnout pT) { - return new Immutable(pT); - } - - private static final class Mutable extends Turnout.Match { - Mutable(final modes3.Turnout pT) { - super(pT); - } - - @Override - public boolean isMutable() { - return true; - } - } - - private static final class Immutable extends Turnout.Match { - Immutable(final modes3.Turnout pT) { - super(pT); - } - - @Override - public boolean isMutable() { - return false; - } - } - } - - /** - * Generated pattern matcher API of the modes3.queries.turnout pattern, - * providing pattern-specific query methods. - * - *

Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)}, - * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}. - * - *

Matches of the pattern will be represented as {@link Match}. - * - *

Original source: - *

-   * pattern turnout(T : Turnout) {
-   * 	Turnout(T);
-   * }
-   * 
- * - * @see Match - * @see Turnout - * - */ - public static class Matcher extends BaseMatcher { - /** - * Initializes the pattern matcher within an existing VIATRA Query engine. - * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. - * - * @param engine the existing VIATRA Query engine in which this matcher will be created. - * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation - * - */ - public static Turnout.Matcher on(final ViatraQueryEngine engine) { - // check if matcher already exists - Matcher matcher = engine.getExistingMatcher(querySpecification()); - if (matcher == null) { - matcher = (Matcher)engine.getMatcher(querySpecification()); - } - return matcher; - } - - /** - * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation - * @return an initialized matcher - * @noreference This method is for internal matcher initialization by the framework, do not call it manually. - * - */ - public static Turnout.Matcher create() { - return new Matcher(); - } - - private static final int POSITION_T = 0; - - private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(Turnout.Matcher.class); - - /** - * Initializes the pattern matcher within an existing VIATRA Query engine. - * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. - * - * @param engine the existing VIATRA Query engine in which this matcher will be created. - * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation - * - */ - private Matcher() { - super(querySpecification()); - } - - /** - * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return matches represented as a Match object. - * - */ - public Collection getAllMatches(final modes3.Turnout pT) { - return rawStreamAllMatches(new Object[]{pT}).collect(Collectors.toSet()); - } - - /** - * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters. - *

- * NOTE: It is important not to modify the source model while the stream is being processed. - * If the match set of the pattern changes during processing, the contents of the stream is undefined. - * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return a stream of matches represented as a Match object. - * - */ - public Stream streamAllMatches(final modes3.Turnout pT) { - return rawStreamAllMatches(new Object[]{pT}); - } - - /** - * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. - * Neither determinism nor randomness of selection is guaranteed. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return a match represented as a Match object, or null if no match is found. - * - */ - public Optional getOneArbitraryMatch(final modes3.Turnout pT) { - return rawGetOneArbitraryMatch(new Object[]{pT}); - } - - /** - * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, - * under any possible substitution of the unspecified parameters (if any). - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return true if the input is a valid (partial) match of the pattern. - * - */ - public boolean hasMatch(final modes3.Turnout pT) { - return rawHasMatch(new Object[]{pT}); - } - - /** - * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return the number of pattern matches found. - * - */ - public int countMatches(final modes3.Turnout pT) { - return rawCountMatches(new Object[]{pT}); - } - - /** - * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. - * Neither determinism nor randomness of selection is guaranteed. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @param processor the action that will process the selected match. - * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked - * - */ - public boolean forOneArbitraryMatch(final modes3.Turnout pT, final Consumer processor) { - return rawForOneArbitraryMatch(new Object[]{pT}, processor); - } - - /** - * Returns a new (partial) match. - * This can be used e.g. to call the matcher with a partial match. - *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return the (partial) match object. - * - */ - public Turnout.Match newMatch(final modes3.Turnout pT) { - return Turnout.Match.newMatch(pT); - } - - /** - * Retrieve the set of values that occur in matches for T. - * @return the Set of all values or empty set if there are no matches - * - */ - protected Stream rawStreamAllValuesOfT(final Object[] parameters) { - return rawStreamAllValues(POSITION_T, parameters).map(modes3.Turnout.class::cast); - } - - /** - * Retrieve the set of values that occur in matches for T. - * @return the Set of all values or empty set if there are no matches - * - */ - public Set getAllValuesOfT() { - return rawStreamAllValuesOfT(emptyArray()).collect(Collectors.toSet()); - } - - /** - * Retrieve the set of values that occur in matches for T. - * @return the Set of all values or empty set if there are no matches - * - */ - public Stream streamAllValuesOfT() { - return rawStreamAllValuesOfT(emptyArray()); - } - - @Override - protected Turnout.Match tupleToMatch(final Tuple t) { - try { - return Turnout.Match.newMatch((modes3.Turnout) t.get(POSITION_T)); - } catch(ClassCastException e) { - LOGGER.error("Element(s) in tuple not properly typed!",e); - return null; - } - } - - @Override - protected Turnout.Match arrayToMatch(final Object[] match) { - try { - return Turnout.Match.newMatch((modes3.Turnout) match[POSITION_T]); - } catch(ClassCastException e) { - LOGGER.error("Element(s) in array not properly typed!",e); - return null; - } - } - - @Override - protected Turnout.Match arrayToMatchMutable(final Object[] match) { - try { - return Turnout.Match.newMutableMatch((modes3.Turnout) match[POSITION_T]); - } catch(ClassCastException e) { - LOGGER.error("Element(s) in array not properly typed!",e); - return null; - } - } - - /** - * @return the singleton instance of the query specification of this pattern - * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded - * - */ - public static IQuerySpecification querySpecification() { - return Turnout.instance(); - } - } - - private Turnout() { - super(GeneratedPQuery.INSTANCE); - } - - /** - * @return the singleton instance of the query specification - * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded - * - */ - public static Turnout instance() { - try{ - return LazyHolder.INSTANCE; - } catch (ExceptionInInitializerError err) { - throw processInitializerError(err); - } - } - - @Override - protected Turnout.Matcher instantiate(final ViatraQueryEngine engine) { - return Turnout.Matcher.on(engine); - } - - @Override - public Turnout.Matcher instantiate() { - return Turnout.Matcher.create(); - } - - @Override - public Turnout.Match newEmptyMatch() { - return Turnout.Match.newEmptyMatch(); - } - - @Override - public Turnout.Match newMatch(final Object... parameters) { - return Turnout.Match.newMatch((modes3.Turnout) parameters[0]); - } - - /** - * Inner class allowing the singleton instance of {@link Turnout} to be created - * not at the class load time of the outer class, - * but rather at the first call to {@link Turnout#instance()}. - * - *

This workaround is required e.g. to support recursion. - * - */ - private static class LazyHolder { - private static final Turnout INSTANCE = new Turnout(); - - /** - * Statically initializes the query specification after the field {@link #INSTANCE} is assigned. - * This initialization order is required to support indirect recursion. - * - *

The static initializer is defined using a helper field to work around limitations of the code generator. - * - */ - private static final Object STATIC_INITIALIZER = ensureInitialized(); - - public static Object ensureInitialized() { - INSTANCE.ensureInitializedInternal(); - return null; - } - } - - private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { - private static final Turnout.GeneratedPQuery INSTANCE = new GeneratedPQuery(); - - private final PParameter parameter_T = new PParameter("T", "modes3.Turnout", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Turnout")), PParameterDirection.INOUT); - - private final List parameters = Arrays.asList(parameter_T); - - private GeneratedPQuery() { - super(PVisibility.PUBLIC); - } - - @Override - public String getFullyQualifiedName() { - return "modes3.queries.turnout"; - } - - @Override - public List getParameterNames() { - return Arrays.asList("T"); - } - - @Override - public List getParameters() { - return parameters; - } - - @Override - public Set doGetContainedBodies() { - setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED)); - Set bodies = new LinkedHashSet<>(); - { - PBody body = new PBody(this); - PVariable var_T = body.getOrCreateVariableByName("T"); - new TypeConstraint(body, Tuples.flatTupleOf(var_T), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Turnout"))); - body.setSymbolicParameters(Arrays.asList( - new ExportedParameter(body, var_T, parameter_T) - )); - // Turnout(T) - new TypeConstraint(body, Tuples.flatTupleOf(var_T), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Turnout"))); - bodies.add(body); - } - return bodies; - } - } -} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TurnoutInSegments.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TurnoutInSegments.java deleted file mode 100644 index 9c9a5d18..00000000 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TurnoutInSegments.java +++ /dev/null @@ -1,564 +0,0 @@ -/** - * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql - */ -package modes3.queries; - -import java.util.Arrays; -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.function.Consumer; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import modes3.Turnout; -import org.apache.log4j.Logger; -import org.eclipse.emf.ecore.EClass; -import org.eclipse.viatra.query.runtime.api.IPatternMatch; -import org.eclipse.viatra.query.runtime.api.IQuerySpecification; -import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine; -import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery; -import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification; -import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher; -import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch; -import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey; -import org.eclipse.viatra.query.runtime.emf.types.EStructuralFeatureInstancesKey; -import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint; -import org.eclipse.viatra.query.runtime.matchers.psystem.PBody; -import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable; -import org.eclipse.viatra.query.runtime.matchers.psystem.annotations.PAnnotation; -import org.eclipse.viatra.query.runtime.matchers.psystem.annotations.ParameterReference; -import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Equality; -import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter; -import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint; -import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter; -import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection; -import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility; -import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple; -import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples; -import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil; - -/** - * A pattern-specific query specification that can instantiate Matcher in a type-safe way. - * - *

Original source: - *

- *         {@literal @}Constraint(message = "turnoutInSegments", severity = "error", key = { T })
- *         pattern turnoutInSegments(T : Turnout) {
- *         	Modes3ModelRoot.segments(_, T);
- *         }
- * 
- * - * @see Matcher - * @see Match - * - */ -@SuppressWarnings("all") -public final class TurnoutInSegments extends BaseGeneratedEMFQuerySpecification { - /** - * Pattern-specific match representation of the modes3.queries.turnoutInSegments pattern, - * to be used in conjunction with {@link Matcher}. - * - *

Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned. - * Each instance is a (possibly partial) substitution of pattern parameters, - * usable to represent a match of the pattern in the result of a query, - * or to specify the bound (fixed) input parameters when issuing a query. - * - * @see Matcher - * - */ - public static abstract class Match extends BasePatternMatch { - private Turnout fT; - - private static List parameterNames = makeImmutableList("T"); - - private Match(final Turnout pT) { - this.fT = pT; - } - - @Override - public Object get(final String parameterName) { - switch(parameterName) { - case "T": return this.fT; - default: return null; - } - } - - @Override - public Object get(final int index) { - switch(index) { - case 0: return this.fT; - default: return null; - } - } - - public Turnout getT() { - return this.fT; - } - - @Override - public boolean set(final String parameterName, final Object newValue) { - if (!isMutable()) throw new java.lang.UnsupportedOperationException(); - if ("T".equals(parameterName) ) { - this.fT = (Turnout) newValue; - return true; - } - return false; - } - - public void setT(final Turnout pT) { - if (!isMutable()) throw new java.lang.UnsupportedOperationException(); - this.fT = pT; - } - - @Override - public String patternName() { - return "modes3.queries.turnoutInSegments"; - } - - @Override - public List parameterNames() { - return TurnoutInSegments.Match.parameterNames; - } - - @Override - public Object[] toArray() { - return new Object[]{fT}; - } - - @Override - public TurnoutInSegments.Match toImmutable() { - return isMutable() ? newMatch(fT) : this; - } - - @Override - public String prettyPrint() { - StringBuilder result = new StringBuilder(); - result.append("\"T\"=" + prettyPrintValue(fT)); - return result.toString(); - } - - @Override - public int hashCode() { - return Objects.hash(fT); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) { - return false; - } - if ((obj instanceof TurnoutInSegments.Match)) { - TurnoutInSegments.Match other = (TurnoutInSegments.Match) obj; - return Objects.equals(fT, other.fT); - } else { - // this should be infrequent - if (!(obj instanceof IPatternMatch)) { - return false; - } - IPatternMatch otherSig = (IPatternMatch) obj; - return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray()); - } - } - - @Override - public TurnoutInSegments specification() { - return TurnoutInSegments.instance(); - } - - /** - * Returns an empty, mutable match. - * Fields of the mutable match can be filled to create a partial match, usable as matcher input. - * - * @return the empty match. - * - */ - public static TurnoutInSegments.Match newEmptyMatch() { - return new Mutable(null); - } - - /** - * Returns a mutable (partial) match. - * Fields of the mutable match can be filled to create a partial match, usable as matcher input. - * - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return the new, mutable (partial) match object. - * - */ - public static TurnoutInSegments.Match newMutableMatch(final Turnout pT) { - return new Mutable(pT); - } - - /** - * Returns a new (partial) match. - * This can be used e.g. to call the matcher with a partial match. - *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return the (partial) match object. - * - */ - public static TurnoutInSegments.Match newMatch(final Turnout pT) { - return new Immutable(pT); - } - - private static final class Mutable extends TurnoutInSegments.Match { - Mutable(final Turnout pT) { - super(pT); - } - - @Override - public boolean isMutable() { - return true; - } - } - - private static final class Immutable extends TurnoutInSegments.Match { - Immutable(final Turnout pT) { - super(pT); - } - - @Override - public boolean isMutable() { - return false; - } - } - } - - /** - * Generated pattern matcher API of the modes3.queries.turnoutInSegments pattern, - * providing pattern-specific query methods. - * - *

Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)}, - * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}. - * - *

Matches of the pattern will be represented as {@link Match}. - * - *

Original source: - *

-   * {@literal @}Constraint(message = "turnoutInSegments", severity = "error", key = { T })
-   * pattern turnoutInSegments(T : Turnout) {
-   * 	Modes3ModelRoot.segments(_, T);
-   * }
-   * 
- * - * @see Match - * @see TurnoutInSegments - * - */ - public static class Matcher extends BaseMatcher { - /** - * Initializes the pattern matcher within an existing VIATRA Query engine. - * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. - * - * @param engine the existing VIATRA Query engine in which this matcher will be created. - * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation - * - */ - public static TurnoutInSegments.Matcher on(final ViatraQueryEngine engine) { - // check if matcher already exists - Matcher matcher = engine.getExistingMatcher(querySpecification()); - if (matcher == null) { - matcher = (Matcher)engine.getMatcher(querySpecification()); - } - return matcher; - } - - /** - * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation - * @return an initialized matcher - * @noreference This method is for internal matcher initialization by the framework, do not call it manually. - * - */ - public static TurnoutInSegments.Matcher create() { - return new Matcher(); - } - - private static final int POSITION_T = 0; - - private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(TurnoutInSegments.Matcher.class); - - /** - * Initializes the pattern matcher within an existing VIATRA Query engine. - * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. - * - * @param engine the existing VIATRA Query engine in which this matcher will be created. - * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation - * - */ - private Matcher() { - super(querySpecification()); - } - - /** - * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return matches represented as a Match object. - * - */ - public Collection getAllMatches(final Turnout pT) { - return rawStreamAllMatches(new Object[]{pT}).collect(Collectors.toSet()); - } - - /** - * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters. - *

- * NOTE: It is important not to modify the source model while the stream is being processed. - * If the match set of the pattern changes during processing, the contents of the stream is undefined. - * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return a stream of matches represented as a Match object. - * - */ - public Stream streamAllMatches(final Turnout pT) { - return rawStreamAllMatches(new Object[]{pT}); - } - - /** - * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. - * Neither determinism nor randomness of selection is guaranteed. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return a match represented as a Match object, or null if no match is found. - * - */ - public Optional getOneArbitraryMatch(final Turnout pT) { - return rawGetOneArbitraryMatch(new Object[]{pT}); - } - - /** - * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, - * under any possible substitution of the unspecified parameters (if any). - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return true if the input is a valid (partial) match of the pattern. - * - */ - public boolean hasMatch(final Turnout pT) { - return rawHasMatch(new Object[]{pT}); - } - - /** - * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return the number of pattern matches found. - * - */ - public int countMatches(final Turnout pT) { - return rawCountMatches(new Object[]{pT}); - } - - /** - * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. - * Neither determinism nor randomness of selection is guaranteed. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @param processor the action that will process the selected match. - * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked - * - */ - public boolean forOneArbitraryMatch(final Turnout pT, final Consumer processor) { - return rawForOneArbitraryMatch(new Object[]{pT}, processor); - } - - /** - * Returns a new (partial) match. - * This can be used e.g. to call the matcher with a partial match. - *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. - * @param pT the fixed value of pattern parameter T, or null if not bound. - * @return the (partial) match object. - * - */ - public TurnoutInSegments.Match newMatch(final Turnout pT) { - return TurnoutInSegments.Match.newMatch(pT); - } - - /** - * Retrieve the set of values that occur in matches for T. - * @return the Set of all values or empty set if there are no matches - * - */ - protected Stream rawStreamAllValuesOfT(final Object[] parameters) { - return rawStreamAllValues(POSITION_T, parameters).map(Turnout.class::cast); - } - - /** - * Retrieve the set of values that occur in matches for T. - * @return the Set of all values or empty set if there are no matches - * - */ - public Set getAllValuesOfT() { - return rawStreamAllValuesOfT(emptyArray()).collect(Collectors.toSet()); - } - - /** - * Retrieve the set of values that occur in matches for T. - * @return the Set of all values or empty set if there are no matches - * - */ - public Stream streamAllValuesOfT() { - return rawStreamAllValuesOfT(emptyArray()); - } - - @Override - protected TurnoutInSegments.Match tupleToMatch(final Tuple t) { - try { - return TurnoutInSegments.Match.newMatch((Turnout) t.get(POSITION_T)); - } catch(ClassCastException e) { - LOGGER.error("Element(s) in tuple not properly typed!",e); - return null; - } - } - - @Override - protected TurnoutInSegments.Match arrayToMatch(final Object[] match) { - try { - return TurnoutInSegments.Match.newMatch((Turnout) match[POSITION_T]); - } catch(ClassCastException e) { - LOGGER.error("Element(s) in array not properly typed!",e); - return null; - } - } - - @Override - protected TurnoutInSegments.Match arrayToMatchMutable(final Object[] match) { - try { - return TurnoutInSegments.Match.newMutableMatch((Turnout) match[POSITION_T]); - } catch(ClassCastException e) { - LOGGER.error("Element(s) in array not properly typed!",e); - return null; - } - } - - /** - * @return the singleton instance of the query specification of this pattern - * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded - * - */ - public static IQuerySpecification querySpecification() { - return TurnoutInSegments.instance(); - } - } - - private TurnoutInSegments() { - super(GeneratedPQuery.INSTANCE); - } - - /** - * @return the singleton instance of the query specification - * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded - * - */ - public static TurnoutInSegments instance() { - try{ - return LazyHolder.INSTANCE; - } catch (ExceptionInInitializerError err) { - throw processInitializerError(err); - } - } - - @Override - protected TurnoutInSegments.Matcher instantiate(final ViatraQueryEngine engine) { - return TurnoutInSegments.Matcher.on(engine); - } - - @Override - public TurnoutInSegments.Matcher instantiate() { - return TurnoutInSegments.Matcher.create(); - } - - @Override - public TurnoutInSegments.Match newEmptyMatch() { - return TurnoutInSegments.Match.newEmptyMatch(); - } - - @Override - public TurnoutInSegments.Match newMatch(final Object... parameters) { - return TurnoutInSegments.Match.newMatch((modes3.Turnout) parameters[0]); - } - - /** - * Inner class allowing the singleton instance of {@link TurnoutInSegments} to be created - * not at the class load time of the outer class, - * but rather at the first call to {@link TurnoutInSegments#instance()}. - * - *

This workaround is required e.g. to support recursion. - * - */ - private static class LazyHolder { - private static final TurnoutInSegments INSTANCE = new TurnoutInSegments(); - - /** - * Statically initializes the query specification after the field {@link #INSTANCE} is assigned. - * This initialization order is required to support indirect recursion. - * - *

The static initializer is defined using a helper field to work around limitations of the code generator. - * - */ - private static final Object STATIC_INITIALIZER = ensureInitialized(); - - public static Object ensureInitialized() { - INSTANCE.ensureInitializedInternal(); - return null; - } - } - - private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { - private static final TurnoutInSegments.GeneratedPQuery INSTANCE = new GeneratedPQuery(); - - private final PParameter parameter_T = new PParameter("T", "modes3.Turnout", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Turnout")), PParameterDirection.INOUT); - - private final List parameters = Arrays.asList(parameter_T); - - private GeneratedPQuery() { - super(PVisibility.PUBLIC); - } - - @Override - public String getFullyQualifiedName() { - return "modes3.queries.turnoutInSegments"; - } - - @Override - public List getParameterNames() { - return Arrays.asList("T"); - } - - @Override - public List getParameters() { - return parameters; - } - - @Override - public Set doGetContainedBodies() { - setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED)); - Set bodies = new LinkedHashSet<>(); - { - PBody body = new PBody(this); - PVariable var_T = body.getOrCreateVariableByName("T"); - PVariable var___0_ = body.getOrCreateVariableByName("_<0>"); - new TypeConstraint(body, Tuples.flatTupleOf(var_T), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Turnout"))); - body.setSymbolicParameters(Arrays.asList( - new ExportedParameter(body, var_T, parameter_T) - )); - // Modes3ModelRoot.segments(_, T) - new TypeConstraint(body, Tuples.flatTupleOf(var___0_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Modes3ModelRoot"))); - PVariable var__virtual_0_ = body.getOrCreateVariableByName(".virtual{0}"); - new TypeConstraint(body, Tuples.flatTupleOf(var___0_, var__virtual_0_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Modes3ModelRoot", "segments"))); - new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_0_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); - new Equality(body, var__virtual_0_, var_T); - bodies.add(body); - } - { - PAnnotation annotation = new PAnnotation("Constraint"); - annotation.addAttribute("message", "turnoutInSegments"); - annotation.addAttribute("severity", "error"); - annotation.addAttribute("key", Arrays.asList(new Object[] { - new ParameterReference("T") - })); - addAnnotation(annotation); - } - return bodies; - } - } -} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbin b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbin index 4f542a67..77f1ea6e 100644 Binary files a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbin and b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbin differ diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3TypeScopeHint.xtendbin b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3TypeScopeHint.xtendbin new file mode 100644 index 00000000..4fdbb71b Binary files /dev/null and b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3TypeScopeHint.xtendbin differ diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3UnitPropagationGenerator.xtendbin b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3UnitPropagationGenerator.xtendbin index 28e763b9..e5e1b63e 100644 Binary files a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3UnitPropagationGenerator.xtendbin and b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3UnitPropagationGenerator.xtendbin differ diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.gitignore b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.gitignore index 53dcf60f..fb94df96 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.gitignore +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.gitignore @@ -1,2 +1,3 @@ /.Modes3ModelGenerator.java._trace /.Modes3UnitPropagationGenerator.java._trace +/.Modes3TypeScopeHint.java._trace diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/Modes3ModelGenerator.java b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/Modes3ModelGenerator.java index c7364257..f32a7172 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/Modes3ModelGenerator.java +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/Modes3ModelGenerator.java @@ -12,7 +12,9 @@ import hu.bme.mit.inf.dslreasoner.ecore2logic.EcoreMetamodelDescriptor; import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.Ecore2logicannotationsFactory; import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.Ecore2logicannotationsPackage; import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.InverseRelationAssertion; +import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel; import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicProblemBuilder; +import hu.bme.mit.inf.dslreasoner.logic.model.builder.SolutionScope; import hu.bme.mit.inf.dslreasoner.logic.model.builder.TracedOutput; import hu.bme.mit.inf.dslreasoner.logic.model.builder.TypeScopes; import hu.bme.mit.inf.dslreasoner.logic.model.builder.VariableContext; @@ -48,6 +50,7 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.par import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.RelationLink; import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretation2Gml; import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualisation; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.DebugConfiguration; import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.StateCoderStrategy; import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasoner; import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration; @@ -57,12 +60,13 @@ import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.function.Consumer; import java.util.function.Predicate; import modes3.Modes3Factory; import modes3.Modes3ModelRoot; import modes3.Modes3Package; import modes3.queries.Modes3Queries; +import modes3.run.Modes3TypeScopeHint; +import modes3.run.Modes3UnitPropagationGenerator; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EAttribute; @@ -175,29 +179,47 @@ public class Modes3ModelGenerator { it_1.minNewElements = this.modelSize; it_1.maxNewElements = this.modelSize; final Procedure1> _function_4 = (Map it_2) -> { - it_2.put(this.ecore2Logic.TypeofEClass(metamodelLogic.getTrace(), Modes3Package.eINSTANCE.getTurnout()), Integer.valueOf(1)); }; ObjectExtensions.>operator_doubleArrow( it_1.minNewElementsByType, _function_4); final Procedure1> _function_5 = (Map it_2) -> { it_2.put(this.ecore2Logic.TypeofEClass(metamodelLogic.getTrace(), Modes3Package.eINSTANCE.getTrain()), Integer.valueOf(5)); + it_2.put(this.ecore2Logic.TypeofEClass(metamodelLogic.getTrace(), Modes3Package.eINSTANCE.getTurnout()), Integer.valueOf(5)); }; ObjectExtensions.>operator_doubleArrow( it_1.maxNewElementsByType, _function_5); }; ObjectExtensions.operator_doubleArrow( it.typeScopes, _function_3); - it.solutionScope.numberOfRequiredSolutions = 1; + final Procedure1 _function_4 = (SolutionScope it_1) -> { + it_1.numberOfRequiredSolutions = 1; + }; + ObjectExtensions.operator_doubleArrow( + it.solutionScope, _function_4); + it.scopeWeight = 5; it.nameNewElements = false; it.typeInferenceMethod = TypeInferenceMethod.PreliminaryAnalysis; - it.stateCoderStrategy = StateCoderStrategy.Neighbourhood; + it.stateCoderStrategy = StateCoderStrategy.PairwiseNeighbourhood; ScopePropagatorStrategy.Polyhedral _polyhedral = new ScopePropagatorStrategy.Polyhedral( PolyhedralScopePropagatorConstraints.Relational, PolyhedralScopePropagatorSolver.Clp); it.scopePropagatorStrategy = _polyhedral; - it.debugConfiguration.partialInterpretatioVisualiser = null; + Ecore2Logic_Trace _trace = metamodelLogic.getTrace(); + Modes3TypeScopeHint _modes3TypeScopeHint = new Modes3TypeScopeHint(this.ecore2Logic, _trace); + it.hints.add(_modes3TypeScopeHint); + Ecore2Logic_Trace _trace_1 = metamodelLogic.getTrace(); + Modes3UnitPropagationGenerator _modes3UnitPropagationGenerator = new Modes3UnitPropagationGenerator(this.ecore2Logic, _trace_1); + it.unitPropagationPatternGenerators.add(_modes3UnitPropagationGenerator); + final Procedure1 _function_5 = (DebugConfiguration it_1) -> { + GraphvizVisualiser _graphvizVisualiser = new GraphvizVisualiser(); + it_1.partialInterpretatioVisualiser = _graphvizVisualiser; + }; + ObjectExtensions.operator_doubleArrow( + it.debugConfiguration, _function_5); + it.documentationLevel = DocumentationLevel.NORMAL; }; final ViatraReasonerConfiguration config = ObjectExtensions.operator_doubleArrow(_viatraReasonerConfiguration, _function_2); final FileSystemWorkspace workspace = new FileSystemWorkspace("output/", ""); + workspace.writeModel(logic.getOutput(), "problem.logicproblem"); final LogicResult solution = this.solver.solve(logic.getOutput(), config, workspace); URI _xifexpression = null; if ((solution instanceof ModelResult)) { @@ -226,27 +248,23 @@ public class Modes3ModelGenerator { boolean _lessThan = (_size_1 < 160); if (_lessThan) { if ((representation instanceof PartialInterpretation)) { - final Consumer _function_3 = (Type it) -> { - InputOutput.println(it.getName()); - }; - ((PartialInterpretation)representation).getProblem().getTypes().forEach(_function_3); - final Function1 _function_4 = (Type it) -> { + final Function1 _function_3 = (Type it) -> { String _name_2 = it.getName(); return Boolean.valueOf(Objects.equal(_name_2, "Modes3ModelRoot class DefinedPart")); }; - Type _findFirst = IterableExtensions.findFirst(((PartialInterpretation)representation).getProblem().getTypes(), _function_4); + Type _findFirst = IterableExtensions.findFirst(((PartialInterpretation)representation).getProblem().getTypes(), _function_3); final TypeDefinition rootType = ((TypeDefinition) _findFirst); - final Function1 _function_5 = (PartialComplexTypeInterpretation it) -> { + final Function1 _function_4 = (PartialComplexTypeInterpretation it) -> { String _name_2 = it.getInterpretationOf().getName(); return Boolean.valueOf(Objects.equal(_name_2, "Modes3ModelRoot class")); }; final PartialComplexTypeInterpretation rootIntepretation = IterableExtensions.findFirst(Iterables.filter(((PartialInterpretation)representation).getPartialtypeinterpratation(), - PartialComplexTypeInterpretation.class), _function_5); + PartialComplexTypeInterpretation.class), _function_4); rootIntepretation.getElements().removeAll(rootType.getElements()); ((PartialInterpretation)representation).getProblem().getElements().removeAll(rootType.getElements()); EList _partialrelationinterpretation = ((PartialInterpretation)representation).getPartialrelationinterpretation(); for (final PartialRelationInterpretation relationInterpretation : _partialrelationinterpretation) { - final Predicate _function_6 = (RelationLink link) -> { + final Predicate _function_5 = (RelationLink link) -> { boolean _xifexpression_1 = false; if ((link instanceof BinaryElementRelationLink)) { _xifexpression_1 = (rootType.getElements().contains(((BinaryElementRelationLink)link).getParam1()) || rootType.getElements().contains(((BinaryElementRelationLink)link).getParam2())); @@ -255,7 +273,7 @@ public class Modes3ModelGenerator { } return _xifexpression_1; }; - relationInterpretation.getRelationlinks().removeIf(_function_6); + relationInterpretation.getRelationlinks().removeIf(_function_5); } rootType.getElements().clear(); } @@ -349,13 +367,7 @@ public class Modes3ModelGenerator { Viatra2LogicAnnotationsPackage.eINSTANCE.getClass(); Map _extensionToFactoryMap = Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap(); XMIResourceFactoryImpl _xMIResourceFactoryImpl = new XMIResourceFactoryImpl(); - _extensionToFactoryMap.put("ecore", _xMIResourceFactoryImpl); - Map _extensionToFactoryMap_1 = Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap(); - XMIResourceFactoryImpl _xMIResourceFactoryImpl_1 = new XMIResourceFactoryImpl(); - _extensionToFactoryMap_1.put("logicproblem", _xMIResourceFactoryImpl_1); - Map _extensionToFactoryMap_2 = Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap(); - XMIResourceFactoryImpl _xMIResourceFactoryImpl_2 = new XMIResourceFactoryImpl(); - _xblockexpression = _extensionToFactoryMap_2.put("partialinterpretation", _xMIResourceFactoryImpl_2); + _xblockexpression = _extensionToFactoryMap.put("*", _xMIResourceFactoryImpl); } return _xblockexpression; } diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/Modes3TypeScopeHint.java b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/Modes3TypeScopeHint.java new file mode 100644 index 00000000..adb69760 --- /dev/null +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/Modes3TypeScopeHint.java @@ -0,0 +1,133 @@ +package modes3.run; + +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic; +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace; +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearBoundedExpression; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeExpressionBuilderFactory; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.RelationConstraintUpdater; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternGenerator; +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation; +import java.util.Iterator; +import java.util.Map; +import modes3.Modes3Package; +import modes3.queries.Adjacent; +import org.eclipse.viatra.query.runtime.api.IPatternMatch; +import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery; +import org.eclipse.xtend2.lib.StringConcatenation; +import org.eclipse.xtext.xbase.lib.Extension; + +@SuppressWarnings("all") +public class Modes3TypeScopeHint implements LinearTypeConstraintHint { + private static final String TURNOUT_NEIGHBOR_COUNT = "turnoutNeighborCount"; + + private final Type segmentType; + + private final Type turnoutType; + + public Modes3TypeScopeHint(@Extension final Ecore2Logic ecore2Logic, final Ecore2Logic_Trace ecore2LogicTrace) { + @Extension + final Modes3Package Modes3Package = modes3.Modes3Package.eINSTANCE; + this.segmentType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getSegment()); + this.turnoutType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getTurnout()); + } + + @Override + public CharSequence getAdditionalPatterns(@Extension final PatternGenerator patternGenerator, final Map fqnToPQuery) { + StringConcatenation _builder = new StringConcatenation(); + _builder.append("\t"); + _builder.append("pattern "); + _builder.append(Modes3TypeScopeHint.TURNOUT_NEIGHBOR_COUNT, "\t"); + _builder.append("_helper(problem: LogicProblem, interpretation: PartialInterpretation, source: DefinedElement, target: DefinedElement) {"); + _builder.newLineIfNotEmpty(); + _builder.append("\t\t"); + _builder.append("find interpretation(problem, interpretation);"); + _builder.newLine(); + _builder.append("\t\t"); + _builder.append("find mustExist(problem, interpretation, source);"); + _builder.newLine(); + _builder.append("\t\t"); + _builder.append("find mustExist(problem, interpretation, target);"); + _builder.newLine(); + _builder.append("\t\t"); + CharSequence _referInstanceOf = patternGenerator.getTypeIndexer().referInstanceOf(this.turnoutType, Modality.MUST, "source"); + _builder.append(_referInstanceOf, "\t\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t\t"); + CharSequence _referInstanceOf_1 = patternGenerator.getTypeIndexer().referInstanceOf(this.segmentType, Modality.MUST, "target"); + _builder.append(_referInstanceOf_1, "\t\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t\t"); + CharSequence _referPattern = patternGenerator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(Adjacent.instance().getFullyQualifiedName()), new String[] { "source", "target" }, Modality.MUST, true, false); + _builder.append(_referPattern, "\t\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("\t"); + _builder.append("pattern "); + _builder.append(Modes3TypeScopeHint.TURNOUT_NEIGHBOR_COUNT, "\t"); + _builder.append("(problem: LogicProblem, interpretation: PartialInterpretation, element: DefinedElement, N) {"); + _builder.newLineIfNotEmpty(); + _builder.append("\t\t"); + _builder.append("find interpretation(problem, interpretation);"); + _builder.newLine(); + _builder.append("\t\t"); + _builder.append("find mustExist(problem, interpretation, element);"); + _builder.newLine(); + _builder.append("\t\t"); + CharSequence _referInstanceOf_2 = patternGenerator.getTypeIndexer().referInstanceOf(this.turnoutType, Modality.MUST, "element"); + _builder.append(_referInstanceOf_2, "\t\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t\t"); + _builder.append("N == count find "); + _builder.append(Modes3TypeScopeHint.TURNOUT_NEIGHBOR_COUNT, "\t\t"); + _builder.append("_helper(problem, interpretation, element, _);"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("}"); + _builder.newLine(); + return _builder; + } + + @Override + public RelationConstraintUpdater createConstraintUpdater(final LinearTypeExpressionBuilderFactory builderFactory) { + final ViatraQueryMatcher turnoutNeighborCountMatcher = builderFactory.createMatcher(Modes3TypeScopeHint.TURNOUT_NEIGHBOR_COUNT); + final LinearBoundedExpression newNeighbors = builderFactory.createBuilder().add(1, this.segmentType).build(); + final RelationConstraintUpdater _function = (PartialInterpretation partialInterpretation) -> { + final int requiredNeighbbors = Modes3TypeScopeHint.getRemainingCount(turnoutNeighborCountMatcher, partialInterpretation, 3); + newNeighbors.tightenLowerBound(Integer.valueOf(requiredNeighbbors)); + }; + return _function; + } + + private static int getRemainingCount(final ViatraQueryMatcher matcher, final PartialInterpretation partialInterpretation, final int capacity) { + int _xblockexpression = (int) 0; + { + final T partialMatch = matcher.newEmptyMatch(); + partialMatch.set(0, partialInterpretation.getProblem()); + partialMatch.set(1, partialInterpretation); + final Iterator iterator = matcher.streamAllMatches(partialMatch).iterator(); + int max = 0; + while (iterator.hasNext()) { + { + final T match = iterator.next(); + Object _get = match.get(3); + final int n = ((Integer) _get).intValue(); + if ((n < capacity)) { + final int required = (capacity - n); + if ((max < required)) { + max = required; + } + } + } + } + _xblockexpression = max; + } + return _xblockexpression; + } +} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/Modes3UnitPropagationGenerator.java b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/Modes3UnitPropagationGenerator.java index 91adaaaa..5c5f82c5 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/Modes3UnitPropagationGenerator.java +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/Modes3UnitPropagationGenerator.java @@ -10,9 +10,8 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.UnitPropaga import java.util.Collections; import java.util.Map; import modes3.Modes3Package; -import modes3.queries.ExtraInputOfTurnout; +import modes3.queries.Adjacent; import modes3.queries.Output; -import modes3.queries.TurnoutOutput; import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery; import org.eclipse.xtend2.lib.StringConcatenationClient; import org.eclipse.xtext.xbase.lib.CollectionLiterals; @@ -23,16 +22,20 @@ import org.eclipse.xtext.xbase.lib.Pair; public class Modes3UnitPropagationGenerator implements UnitPropagationPatternGenerator { private static final String MUST_NOT_CONNECTED_TO = "mustNotConnectedTo"; - private static final String MUST_NOT_CONNECTED_TO_HELPER = "mustNotConnectedTo_helper"; - - private static final String MUST_NOT_TURNOUT_OUTPUT = "mustNotTurnoutOutput"; - private static final String MUST_NOT_STRAIGHT = "mustNotStraight"; private static final String MUST_NOT_DIVERGENT = "mustNotDivergent"; + private static final String MUST_CONNECTED_TO = "mustConnectedTo"; + + private static final String MUST_STRAIGHT = "mustStraight"; + + private static final String MUST_DIVERGENT = "mustDivergent"; + private final Type segmentType; + private final Type simpleSegmentType; + private final Type turnoutType; private final Relation connectedToRelation; @@ -45,6 +48,7 @@ public class Modes3UnitPropagationGenerator implements UnitPropagationPatternGen @Extension final Modes3Package Modes3Package = modes3.Modes3Package.eINSTANCE; this.segmentType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getSegment()); + this.simpleSegmentType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getSimpleSegment()); this.turnoutType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getTurnout()); this.connectedToRelation = ecore2Logic.relationOfReference(ecore2LogicTrace, Modes3Package.getSegment_ConnectedTo()); this.straightRelation = ecore2Logic.relationOfReference(ecore2LogicTrace, Modes3Package.getTurnout_Straight()); @@ -53,7 +57,10 @@ public class Modes3UnitPropagationGenerator implements UnitPropagationPatternGen @Override public Map getMustPatterns() { - return CollectionLiterals.emptyMap(); + Pair _mappedTo = Pair.of(this.connectedToRelation, Modes3UnitPropagationGenerator.MUST_CONNECTED_TO); + Pair _mappedTo_1 = Pair.of(this.straightRelation, Modes3UnitPropagationGenerator.MUST_STRAIGHT); + Pair _mappedTo_2 = Pair.of(this.divergentRelation, Modes3UnitPropagationGenerator.MUST_DIVERGENT); + return Collections.unmodifiableMap(CollectionLiterals.newHashMap(_mappedTo, _mappedTo_1, _mappedTo_2)); } @Override @@ -89,496 +96,1078 @@ public class Modes3UnitPropagationGenerator implements UnitPropagationPatternGen _builder.newLine(); } }; - final StringConcatenationClient commonParameterConstraints = _client_1; + final StringConcatenationClient commonMustParameterConstraints = _client_1; StringConcatenationClient _client_2 = new StringConcatenationClient() { @Override protected void appendTo(StringConcatenationClient.TargetStringConcatenation _builder) { - _builder.append("pattern "); - _builder.append(Modes3UnitPropagationGenerator.MUST_NOT_CONNECTED_TO_HELPER); - _builder.append("("); - _builder.append(parameters); - _builder.append(") {"); - _builder.newLineIfNotEmpty(); - _builder.append("\t"); - _builder.append("// connectedToReflexive unit propagation"); - _builder.newLine(); - _builder.append("\t"); - _builder.append(commonParameterConstraints, "\t"); - _builder.newLineIfNotEmpty(); - _builder.append("\t"); - CharSequence _referInstanceOf = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "source"); - _builder.append(_referInstanceOf, "\t"); - _builder.newLineIfNotEmpty(); - _builder.append("\t"); - CharSequence _referInstanceOf_1 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "target"); - _builder.append(_referInstanceOf_1, "\t"); - _builder.newLineIfNotEmpty(); - _builder.append("\t"); - _builder.append("source == target;"); + _builder.append("find interpretation(problem, interpretation);"); _builder.newLine(); - _builder.append("} or {"); + _builder.append("find mayExist(problem, interpretation, source);"); _builder.newLine(); - _builder.append("\t"); - _builder.append("// tooManyInputsOfSegment unit propagation"); + _builder.append("find mayExist(problem, interpretation, target);"); _builder.newLine(); - _builder.append("\t"); - _builder.append(commonParameterConstraints, "\t"); + } + }; + final StringConcatenationClient commonMayParameterConstraints = _client_2; + StringConcatenationClient _client_3 = new StringConcatenationClient() { + @Override + protected void appendTo(StringConcatenationClient.TargetStringConcatenation _builder) { + _builder.append("pattern mayInput("); + _builder.append(parameters); + _builder.append(") {"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_2 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "source"); - _builder.append(_referInstanceOf_2, "\t"); + _builder.append(commonMayParameterConstraints, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_3 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "target"); - _builder.append(_referInstanceOf_3, "\t"); + CharSequence _referInstanceOf = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MAY, "target"); + _builder.append(_referInstanceOf, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_4 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "input1"); - _builder.append(_referInstanceOf_4, "\t"); + CharSequence _referPattern = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(Adjacent.instance().getFullyQualifiedName()), new String[] { "target", "source" }, Modality.MAY, true, false); + _builder.append(_referPattern, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_5 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "input2"); - _builder.append(_referInstanceOf_5, "\t"); + _builder.append("neg "); + CharSequence _referRelation = generator.referRelation(Modes3UnitPropagationGenerator.this.straightRelation, "target", "source", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); _builder.append("neg "); - CharSequence _referInstanceOf_6 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MAY, "source"); - _builder.append(_referInstanceOf_6, "\t"); + CharSequence _referRelation_1 = generator.referRelation(Modes3UnitPropagationGenerator.this.straightRelation, "target", "source", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation_1, "\t"); _builder.newLineIfNotEmpty(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern multipleMayInput(problem: LogicProblem, interpretation: PartialInterpretation,"); + _builder.newLine(); + _builder.append("\t\t\t"); + _builder.append("target: DefinedElement) {"); + _builder.newLine(); _builder.append("\t"); - CharSequence _referPattern = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(Output.instance().getFullyQualifiedName()), new String[] { "input1", "source" }, Modality.MUST, true, false); - _builder.append(_referPattern, "\t"); - _builder.newLineIfNotEmpty(); + _builder.append("find interpretation(problem, interpretation);"); + _builder.newLine(); _builder.append("\t"); - CharSequence _referPattern_1 = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(Output.instance().getFullyQualifiedName()), new String[] { "input2", "source" }, Modality.MUST, true, false); - _builder.append(_referPattern_1, "\t"); - _builder.newLineIfNotEmpty(); + _builder.append("find mustExist(problem, interpretation, target);"); + _builder.newLine(); _builder.append("\t"); - _builder.append("input1 != input2;"); + _builder.append("find mayInput(problem, interpretaton, source1, target);"); _builder.newLine(); _builder.append("\t"); - _builder.append("input1 != target;"); + _builder.append("find mayInput(problem, interpretaton, source2, target);"); _builder.newLine(); _builder.append("\t"); - _builder.append("input2 != target;"); + _builder.append("neg find mustEquivalent(problem, interpretation, source1, source2);"); _builder.newLine(); - _builder.append("} or {"); + _builder.append("}"); _builder.newLine(); - _builder.append("\t"); - _builder.append("// turnoutConnectedToBothOutputs unit propagation 1"); + _builder.newLine(); + _builder.append("pattern multipleMayStraight(problem: LogicProblem, interpretation: PartialInterpretation,"); + _builder.newLine(); + _builder.append("\t\t\t"); + _builder.append("source: DefinedElement) {"); _builder.newLine(); _builder.append("\t"); - _builder.append(commonParameterConstraints, "\t"); - _builder.newLineIfNotEmpty(); + _builder.append("find interpretation(problem, interpretation);"); + _builder.newLine(); _builder.append("\t"); - CharSequence _referInstanceOf_7 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MUST, "source"); - _builder.append(_referInstanceOf_7, "\t"); - _builder.newLineIfNotEmpty(); + _builder.append("find mustExist(problem, interpretation, source);"); + _builder.newLine(); _builder.append("\t"); - CharSequence _referInstanceOf_8 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "target"); - _builder.append(_referInstanceOf_8, "\t"); + CharSequence _referInstanceOf_1 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MAY, "source"); + _builder.append(_referInstanceOf_1, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_9 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "divergent"); - _builder.append(_referInstanceOf_9, "\t"); + CharSequence _referRelation_2 = generator.referRelation(Modes3UnitPropagationGenerator.this.straightRelation, "source", "target1", Modality.MAY, fqnToPQuery); + _builder.append(_referRelation_2, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referRelation = generator.referRelation(Modes3UnitPropagationGenerator.this.straightRelation, "source", "target", Modality.MUST, fqnToPQuery); - _builder.append(_referRelation, "\t"); + CharSequence _referRelation_3 = generator.referRelation(Modes3UnitPropagationGenerator.this.straightRelation, "source", "target2", Modality.MAY, fqnToPQuery); + _builder.append(_referRelation_3, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referRelation_1 = generator.referRelation(Modes3UnitPropagationGenerator.this.divergentRelation, "source", "divergent", Modality.MUST, fqnToPQuery); - _builder.append(_referRelation_1, "\t"); - _builder.newLineIfNotEmpty(); + _builder.append("neg find mustEquivalent(problem, interpretation, target1, target2);"); + _builder.newLine(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern multipleMayDivergent(problem: LogicProblem, interpretation: PartialInterpretation,"); + _builder.newLine(); + _builder.append("\t\t\t"); + _builder.append("source: DefinedElement) {"); + _builder.newLine(); _builder.append("\t"); - CharSequence _referRelation_2 = generator.referRelation(Modes3UnitPropagationGenerator.this.connectedToRelation, "source", "divergent", Modality.MUST, fqnToPQuery); - _builder.append(_referRelation_2, "\t"); - _builder.newLineIfNotEmpty(); - _builder.append("} or {"); + _builder.append("find interpretation(problem, interpretation);"); _builder.newLine(); _builder.append("\t"); - _builder.append("// turnoutConnectedToBothOutputs unit propagation 2"); + _builder.append("find mustExist(problem, interpretation, source);"); _builder.newLine(); _builder.append("\t"); - _builder.append(commonParameterConstraints, "\t"); + CharSequence _referInstanceOf_2 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MAY, "source"); + _builder.append(_referInstanceOf_2, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_10 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MUST, "source"); - _builder.append(_referInstanceOf_10, "\t"); + CharSequence _referRelation_4 = generator.referRelation(Modes3UnitPropagationGenerator.this.divergentRelation, "source", "target1", Modality.MAY, fqnToPQuery); + _builder.append(_referRelation_4, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_11 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "target"); - _builder.append(_referInstanceOf_11, "\t"); + CharSequence _referRelation_5 = generator.referRelation(Modes3UnitPropagationGenerator.this.divergentRelation, "source", "target2", Modality.MAY, fqnToPQuery); + _builder.append(_referRelation_5, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_12 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "straight"); - _builder.append(_referInstanceOf_12, "\t"); + _builder.append("neg find mustEquivalent(problem, interpretation, target1, target2);"); + _builder.newLine(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern "); + _builder.append(Modes3UnitPropagationGenerator.MUST_CONNECTED_TO); + _builder.append("("); + _builder.append(parameters); + _builder.append(") {"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referRelation_3 = generator.referRelation(Modes3UnitPropagationGenerator.this.straightRelation, "source", "straight", Modality.MUST, fqnToPQuery); - _builder.append(_referRelation_3, "\t"); + _builder.append(commonMustParameterConstraints, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referRelation_4 = generator.referRelation(Modes3UnitPropagationGenerator.this.divergentRelation, "source", "target", Modality.MUST, fqnToPQuery); - _builder.append(_referRelation_4, "\t"); + CharSequence _referInstanceOf_3 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MAY, "target"); + _builder.append(_referInstanceOf_3, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referRelation_5 = generator.referRelation(Modes3UnitPropagationGenerator.this.connectedToRelation, "source", "straight", Modality.MUST, fqnToPQuery); - _builder.append(_referRelation_5, "\t"); - _builder.newLineIfNotEmpty(); - _builder.append("} or {"); + _builder.append("find mayInput(problem, interpretaton, source, target);"); _builder.newLine(); _builder.append("\t"); - _builder.append("// tooManyExtraInputsOfTurnout unit propagation"); + _builder.append("neg find multipleMayInput(problem, interpretaton, target);"); _builder.newLine(); _builder.append("\t"); - _builder.append(commonParameterConstraints, "\t"); - _builder.newLineIfNotEmpty(); - _builder.append("\t"); - CharSequence _referInstanceOf_13 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MUST, "source"); - _builder.append(_referInstanceOf_13, "\t"); - _builder.newLineIfNotEmpty(); - _builder.append("\t"); - CharSequence _referInstanceOf_14 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "target"); - _builder.append(_referInstanceOf_14, "\t"); + CharSequence _referRelation_6 = generator.referRelation(Modes3UnitPropagationGenerator.this.connectedToRelation, "source", "target", Modality.MAY, fqnToPQuery); + _builder.append(_referRelation_6, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_15 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "extraInput"); - _builder.append(_referInstanceOf_15, "\t"); + _builder.append("neg "); + CharSequence _referRelation_7 = generator.referRelation(Modes3UnitPropagationGenerator.this.connectedToRelation, "source", "target", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation_7, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referPattern_2 = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(TurnoutOutput.instance().getFullyQualifiedName()), new String[] { "source", "target" }, Modality.MAY, false, false); - _builder.append(_referPattern_2, "\t"); + _builder.append("neg "); + CharSequence _referRelation_8 = generator.referRelation(Modes3UnitPropagationGenerator.this.straightRelation, "source", "target", Modality.MAY, fqnToPQuery); + _builder.append(_referRelation_8, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referPattern_3 = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(ExtraInputOfTurnout.instance().getFullyQualifiedName()), new String[] { "source", "extraInput" }, Modality.MUST, true, false); - _builder.append(_referPattern_3, "\t"); + _builder.append("neg "); + CharSequence _referRelation_9 = generator.referRelation(Modes3UnitPropagationGenerator.this.divergentRelation, "source", "target", Modality.MAY, fqnToPQuery); + _builder.append(_referRelation_9, "\t"); _builder.newLineIfNotEmpty(); - _builder.append("\t"); - _builder.append("target != extraInput;"); - _builder.newLine(); _builder.append("}"); _builder.newLine(); _builder.newLine(); _builder.append("pattern "); - _builder.append(Modes3UnitPropagationGenerator.MUST_NOT_CONNECTED_TO); + _builder.append(Modes3UnitPropagationGenerator.MUST_STRAIGHT); _builder.append("("); _builder.append(parameters); _builder.append(") {"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - _builder.append("find "); - _builder.append(Modes3UnitPropagationGenerator.MUST_NOT_CONNECTED_TO_HELPER, "\t"); - _builder.append("(problem, interpretation, source, target);"); + _builder.append(commonMustParameterConstraints, "\t"); _builder.newLineIfNotEmpty(); - _builder.append("} or {"); - _builder.newLine(); _builder.append("\t"); - _builder.append("find "); - _builder.append(Modes3UnitPropagationGenerator.MUST_NOT_CONNECTED_TO_HELPER, "\t"); - _builder.append("(problem, interpretation, target, source);"); - _builder.newLineIfNotEmpty(); - _builder.append("}"); - _builder.newLine(); - _builder.newLine(); - _builder.append("pattern "); - _builder.append(Modes3UnitPropagationGenerator.MUST_NOT_TURNOUT_OUTPUT); - _builder.append("("); - _builder.append(parameters); - _builder.append(") {"); + _builder.append("neg "); + CharSequence _referRelation_10 = generator.referRelation(Modes3UnitPropagationGenerator.this.straightRelation, "source", "_", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation_10, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - _builder.append("// outputReflexive unit propagation"); + _builder.append("neg find multipleMayStraight(problem, interpretation, source);"); _builder.newLine(); _builder.append("\t"); - _builder.append(commonParameterConstraints, "\t"); - _builder.newLineIfNotEmpty(); - _builder.append("\t"); - CharSequence _referInstanceOf_16 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MUST, "source"); - _builder.append(_referInstanceOf_16, "\t"); + CharSequence _referRelation_11 = generator.referRelation(Modes3UnitPropagationGenerator.this.straightRelation, "source", "target", Modality.MAY, fqnToPQuery); + _builder.append(_referRelation_11, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_17 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MUST, "target"); - _builder.append(_referInstanceOf_17, "\t"); + _builder.append("neg "); + CharSequence _referRelation_12 = generator.referRelation(Modes3UnitPropagationGenerator.this.straightRelation, "source", "target", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation_12, "\t"); _builder.newLineIfNotEmpty(); - _builder.append("\t"); - _builder.append("source == target;"); - _builder.newLine(); _builder.append("} or {"); _builder.newLine(); _builder.append("\t"); - _builder.append("// tooManyInputsOfSegment unit propagation"); - _builder.newLine(); - _builder.append("\t"); - _builder.append(commonParameterConstraints, "\t"); - _builder.newLineIfNotEmpty(); - _builder.append("\t"); - CharSequence _referInstanceOf_18 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MUST, "source"); - _builder.append(_referInstanceOf_18, "\t"); + _builder.append(commonMustParameterConstraints, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_19 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "target"); - _builder.append(_referInstanceOf_19, "\t"); + CharSequence _referInstanceOf_4 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MAY, "target"); + _builder.append(_referInstanceOf_4, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_20 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "input1"); - _builder.append(_referInstanceOf_20, "\t"); - _builder.newLineIfNotEmpty(); + _builder.append("find mayInput(problem, interpretaton, source, target);"); + _builder.newLine(); _builder.append("\t"); - CharSequence _referInstanceOf_21 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "input2"); - _builder.append(_referInstanceOf_21, "\t"); - _builder.newLineIfNotEmpty(); + _builder.append("neg find multipleMayInput(problem, interpretaton, target);"); + _builder.newLine(); _builder.append("\t"); _builder.append("neg "); - CharSequence _referInstanceOf_22 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MAY, "target"); - _builder.append(_referInstanceOf_22, "\t"); + CharSequence _referRelation_13 = generator.referRelation(Modes3UnitPropagationGenerator.this.connectedToRelation, "source", "target", Modality.MAY, fqnToPQuery); + _builder.append(_referRelation_13, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referPattern_4 = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(Output.instance().getFullyQualifiedName()), new String[] { "input1", "target" }, Modality.MUST, true, false); - _builder.append(_referPattern_4, "\t"); + CharSequence _referRelation_14 = generator.referRelation(Modes3UnitPropagationGenerator.this.straightRelation, "source", "target", Modality.MAY, fqnToPQuery); + _builder.append(_referRelation_14, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referPattern_5 = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(Output.instance().getFullyQualifiedName()), new String[] { "input2", "target" }, Modality.MUST, true, false); - _builder.append(_referPattern_5, "\t"); + _builder.append("neg "); + CharSequence _referRelation_15 = generator.referRelation(Modes3UnitPropagationGenerator.this.straightRelation, "source", "target", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation_15, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - _builder.append("input1 != input2;"); - _builder.newLine(); - _builder.append("\t"); - _builder.append("input1 != source;"); - _builder.newLine(); - _builder.append("\t"); - _builder.append("input2 != source;"); - _builder.newLine(); + _builder.append("neg "); + CharSequence _referRelation_16 = generator.referRelation(Modes3UnitPropagationGenerator.this.divergentRelation, "source", "target", Modality.MAY, fqnToPQuery); + _builder.append(_referRelation_16, "\t"); + _builder.newLineIfNotEmpty(); _builder.append("}"); _builder.newLine(); _builder.newLine(); _builder.append("pattern "); - _builder.append(Modes3UnitPropagationGenerator.MUST_NOT_STRAIGHT); + _builder.append(Modes3UnitPropagationGenerator.MUST_DIVERGENT); _builder.append("("); _builder.append(parameters); _builder.append(") {"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - _builder.append("find "); - _builder.append(Modes3UnitPropagationGenerator.MUST_NOT_TURNOUT_OUTPUT, "\t"); - _builder.append("(problem, interpretation, source, target);"); + _builder.append(commonMustParameterConstraints, "\t"); _builder.newLineIfNotEmpty(); - _builder.append("} or {"); - _builder.newLine(); _builder.append("\t"); - _builder.append("// turnoutOutputsAreSame unit propagation"); + _builder.append("neg "); + CharSequence _referRelation_17 = generator.referRelation(Modes3UnitPropagationGenerator.this.divergentRelation, "source", "_", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation_17, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("neg find multipleMayDivergent(problem, interpretation, source);"); _builder.newLine(); _builder.append("\t"); - _builder.append(commonParameterConstraints, "\t"); + CharSequence _referRelation_18 = generator.referRelation(Modes3UnitPropagationGenerator.this.divergentRelation, "source", "target", Modality.MAY, fqnToPQuery); + _builder.append(_referRelation_18, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_23 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MUST, "source"); - _builder.append(_referInstanceOf_23, "\t"); + _builder.append("neg "); + CharSequence _referRelation_19 = generator.referRelation(Modes3UnitPropagationGenerator.this.divergentRelation, "source", "target", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation_19, "\t"); _builder.newLineIfNotEmpty(); + _builder.append("} or {"); + _builder.newLine(); _builder.append("\t"); - CharSequence _referInstanceOf_24 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "target"); - _builder.append(_referInstanceOf_24, "\t"); + _builder.append(commonMustParameterConstraints, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referRelation_6 = generator.referRelation(Modes3UnitPropagationGenerator.this.divergentRelation, "source", "target", Modality.MUST, fqnToPQuery); - _builder.append(_referRelation_6, "\t"); + CharSequence _referInstanceOf_5 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MAY, "target"); + _builder.append(_referInstanceOf_5, "\t"); _builder.newLineIfNotEmpty(); - _builder.append("} or {"); + _builder.append("\t"); + _builder.append("find mayInput(problem, interpretaton, source, target);"); _builder.newLine(); _builder.append("\t"); - _builder.append("// turnoutConnectedToBothOutputs unit propagation"); + _builder.append("neg find multipleMayInput(problem, interpretaton, target);"); _builder.newLine(); _builder.append("\t"); - _builder.append(commonParameterConstraints, "\t"); + _builder.append("neg "); + CharSequence _referRelation_20 = generator.referRelation(Modes3UnitPropagationGenerator.this.connectedToRelation, "source", "target", Modality.MAY, fqnToPQuery); + _builder.append(_referRelation_20, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_25 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MUST, "source"); - _builder.append(_referInstanceOf_25, "\t"); + _builder.append("neg "); + CharSequence _referRelation_21 = generator.referRelation(Modes3UnitPropagationGenerator.this.straightRelation, "source", "target", Modality.MAY, fqnToPQuery); + _builder.append(_referRelation_21, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_26 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "target"); - _builder.append(_referInstanceOf_26, "\t"); + CharSequence _referRelation_22 = generator.referRelation(Modes3UnitPropagationGenerator.this.divergentRelation, "source", "target", Modality.MAY, fqnToPQuery); + _builder.append(_referRelation_22, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_27 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MUST, "divergent"); - _builder.append(_referInstanceOf_27, "\t"); + _builder.append("neg "); + CharSequence _referRelation_23 = generator.referRelation(Modes3UnitPropagationGenerator.this.divergentRelation, "source", "target", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation_23, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern turnoutOutput_must_to_true_by_straight("); + _builder.append(parameters); + _builder.append(", T : DefinedElement, S : DefinedElement) {"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referRelation_7 = generator.referRelation(Modes3UnitPropagationGenerator.this.connectedToRelation, "source", "target", Modality.MUST, fqnToPQuery); - _builder.append(_referRelation_7, "\t"); + _builder.append(commonMayParameterConstraints, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referRelation_8 = generator.referRelation(Modes3UnitPropagationGenerator.this.divergentRelation, "source", "divergent", Modality.MUST, fqnToPQuery); - _builder.append(_referRelation_8, "\t"); + CharSequence _referInstanceOf_6 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MAY, "source"); + _builder.append(_referInstanceOf_6, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referRelation_9 = generator.referRelation(Modes3UnitPropagationGenerator.this.connectedToRelation, "source", "divergent", Modality.MUST, fqnToPQuery); - _builder.append(_referRelation_9, "\t"); + CharSequence _referInstanceOf_7 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MAY, "target"); + _builder.append(_referInstanceOf_7, "\t"); _builder.newLineIfNotEmpty(); - _builder.append("} or {"); - _builder.newLine(); _builder.append("\t"); - _builder.append("// tooManyExtraInputsOfTurnout unit propagation"); + _builder.append("T == source;"); _builder.newLine(); _builder.append("\t"); - _builder.append(commonParameterConstraints, "\t"); + _builder.append("S == target;"); + _builder.newLine(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern turnoutOutput_must_to_true_by_divergent("); + _builder.append(parameters); + _builder.append(", T : DefinedElement, S : DefinedElement) {"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_28 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MUST, "source"); - _builder.append(_referInstanceOf_28, "\t"); + _builder.append(commonMayParameterConstraints, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_29 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "target"); - _builder.append(_referInstanceOf_29, "\t"); + CharSequence _referInstanceOf_8 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MAY, "source"); + _builder.append(_referInstanceOf_8, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_30 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "extraInput"); - _builder.append(_referInstanceOf_30, "\t"); + CharSequence _referInstanceOf_9 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MAY, "target"); + _builder.append(_referInstanceOf_9, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_31 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "potentialExtraInput"); - _builder.append(_referInstanceOf_31, "\t"); - _builder.newLineIfNotEmpty(); + _builder.append("T == source;"); + _builder.newLine(); _builder.append("\t"); - CharSequence _referPattern_6 = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(ExtraInputOfTurnout.instance().getFullyQualifiedName()), new String[] { "source", "extraInput" }, Modality.MUST, true, false); - _builder.append(_referPattern_6, "\t"); + _builder.append("S == target;"); + _builder.newLine(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern output_must_to_true_by_connectedTo("); + _builder.append(parameters); + _builder.append(", S1 : DefinedElement, S2 : DefinedElement) {"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referRelation_10 = generator.referRelation(Modes3UnitPropagationGenerator.this.connectedToRelation, "source", "potentialExtraInput", Modality.MUST, fqnToPQuery); - _builder.append(_referRelation_10, "\t"); + _builder.append(commonMayParameterConstraints, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - _builder.append("neg "); - CharSequence _referRelation_11 = generator.referRelation(Modes3UnitPropagationGenerator.this.divergentRelation, "source", "potentialExtraInput", Modality.MAY, fqnToPQuery); - _builder.append(_referRelation_11, "\t"); + CharSequence _referInstanceOf_10 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MAY, "source"); + _builder.append(_referInstanceOf_10, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - _builder.append("extraInput != potentialExtraInput;"); - _builder.newLine(); + CharSequence _referInstanceOf_11 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MAY, "target"); + _builder.append(_referInstanceOf_11, "\t"); + _builder.newLineIfNotEmpty(); _builder.append("\t"); - _builder.append("extraInput != target;"); + _builder.append("S1 == source;"); _builder.newLine(); _builder.append("\t"); - _builder.append("potentialExtraInput != target;"); + _builder.append("S2 == target;"); _builder.newLine(); _builder.append("}"); _builder.newLine(); _builder.newLine(); - _builder.append("pattern "); - _builder.append(Modes3UnitPropagationGenerator.MUST_NOT_DIVERGENT); - _builder.append("("); + _builder.append("pattern output_must_to_true_by_straight("); _builder.append(parameters); - _builder.append(") {"); + _builder.append(", S1 : DefinedElement, S2 : DefinedElement) {"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - _builder.append("find "); - _builder.append(Modes3UnitPropagationGenerator.MUST_NOT_TURNOUT_OUTPUT, "\t"); - _builder.append("(problem, interpretation, source, target);"); - _builder.newLineIfNotEmpty(); - _builder.append("} or {"); + _builder.append("find turnoutOutput_must_to_true_by_straight(problem, interpretation, source, target, S1, S2);"); _builder.newLine(); - _builder.append("\t"); - _builder.append("// turnoutOutputsAreSame unit propagation"); + _builder.append("}"); _builder.newLine(); - _builder.append("\t"); - _builder.append(commonParameterConstraints, "\t"); + _builder.newLine(); + _builder.append("pattern output_must_to_true_by_divergent("); + _builder.append(parameters); + _builder.append(", S1 : DefinedElement, S2 : DefinedElement) {"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_32 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MUST, "source"); - _builder.append(_referInstanceOf_32, "\t"); + _builder.append("find turnoutOutput_must_to_true_by_divergent(problem, interpretation, source, target, S1, S2);"); + _builder.newLine(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern adjacent_must_to_true_by_connectedTo("); + _builder.append(parameters); + _builder.append(", S1 : DefinedElement, S2 : DefinedElement) {"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_33 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "target"); - _builder.append(_referInstanceOf_33, "\t"); + _builder.append("find output_must_to_true_by_connectedTo(problem, interpretation, source, target, S1, S2);"); + _builder.newLine(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern adjacent_must_to_true_by_straight("); + _builder.append(parameters); + _builder.append(", S1 : DefinedElement, S2 : DefinedElement) {"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referRelation_12 = generator.referRelation(Modes3UnitPropagationGenerator.this.straightRelation, "source", "target", Modality.MUST, fqnToPQuery); - _builder.append(_referRelation_12, "\t"); + _builder.append("find output_must_to_true_by_straight(problem, interpretation, source, target, S1, S2);"); + _builder.newLine(); + _builder.append("} or {"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("find turnoutOutput_must_to_true_by_straight(problem, interpretation, source, target, S2, S1);"); + _builder.newLine(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern adjacent_must_to_true_by_divergent("); + _builder.append(parameters); + _builder.append(", S1 : DefinedElement, S2 : DefinedElement) {"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("find output_must_to_true_by_divergent(problem, interpretation, source, target, S1, S2);"); + _builder.newLine(); + _builder.append("} or {"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("find turnoutOutput_must_to_true_by_divergent(problem, interpretation, source, target, S2, S1);"); + _builder.newLine(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern connectedToReflexive_must_to_true_by_connectedTo("); + _builder.append(parameters); + _builder.append(", S : DefinedElement) {"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("find mustExist(problem, interpretation, source);"); + _builder.newLine(); + _builder.append("\t"); + CharSequence _referInstanceOf_12 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "source"); + _builder.append(_referInstanceOf_12, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("S == source;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("S == target;"); + _builder.newLine(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern outputReflexive_must_to_true_by_straight("); + _builder.append(parameters); + _builder.append(", T : DefinedElement) {"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("find turnoutOutput_must_to_true_by_straight(problem, interpretation, source, target, T, T);"); + _builder.newLine(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern outputReflexive_must_to_true_by_divergent("); + _builder.append(parameters); + _builder.append(", T : DefinedElement) {"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("find turnoutOutput_must_to_true_by_divergent(problem, interpretation, source, target, T, T);"); + _builder.newLine(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern turnoutOutputsAreSame_must_to_true_by_straight("); + _builder.append(parameters); + _builder.append(", T : DefinedElement) {"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append(commonMayParameterConstraints, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referInstanceOf_13 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MAY, "source"); + _builder.append(_referInstanceOf_13, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referInstanceOf_14 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MAY, "target"); + _builder.append(_referInstanceOf_14, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("T == source;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("S == target;"); + _builder.newLine(); + _builder.append("\t"); + CharSequence _referRelation_24 = generator.referRelation(Modes3UnitPropagationGenerator.this.divergentRelation, "T", "S", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation_24, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern turnoutOutputsAreSame_must_to_true_by_divergent("); + _builder.append(parameters); + _builder.append(", T : DefinedElement) {"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append(commonMayParameterConstraints, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referInstanceOf_15 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MAY, "source"); + _builder.append(_referInstanceOf_15, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referInstanceOf_16 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MAY, "target"); + _builder.append(_referInstanceOf_16, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("T == source;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("S == target;"); + _builder.newLine(); + _builder.append("\t"); + CharSequence _referRelation_25 = generator.referRelation(Modes3UnitPropagationGenerator.this.straightRelation, "T", "S", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation_25, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern tooManyInputsOfSegment_must_to_true_by_connectedTo("); + _builder.append(parameters); + _builder.append(", S : DefinedElement) {"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("find mustExist(problem, interpretation, S);"); + _builder.newLine(); + _builder.append("\t"); + CharSequence _referInstanceOf_17 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.simpleSegmentType, Modality.MUST, "S"); + _builder.append(_referInstanceOf_17, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("find output_must_to_true_by_connectedTo(problem, interpretation, source, target, I1, S);"); + _builder.newLine(); + _builder.append("\t"); + CharSequence _referPattern_1 = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(Output.instance().getFullyQualifiedName()), new String[] { "I2", "S" }, Modality.MUST, true, false); + _builder.append(_referPattern_1, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referPattern_2 = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(Output.instance().getFullyQualifiedName()), new String[] { "I3", "S" }, Modality.MUST, true, false); + _builder.append(_referPattern_2, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("I1 != I2;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("I1 != I3;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("I2 != I3;"); + _builder.newLine(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern tooManyInputsOfSegment_must_to_true_by_straight("); + _builder.append(parameters); + _builder.append(", S : DefinedElement) {"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("find mustExist(problem, interpretation, S);"); + _builder.newLine(); + _builder.append("\t"); + CharSequence _referInstanceOf_18 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.simpleSegmentType, Modality.MUST, "S"); + _builder.append(_referInstanceOf_18, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("find output_must_to_true_by_straight(problem, interpretation, source, target, I1, S);"); + _builder.newLine(); + _builder.append("\t"); + CharSequence _referPattern_3 = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(Output.instance().getFullyQualifiedName()), new String[] { "I2", "S" }, Modality.MUST, true, false); + _builder.append(_referPattern_3, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referPattern_4 = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(Output.instance().getFullyQualifiedName()), new String[] { "I3", "S" }, Modality.MUST, true, false); + _builder.append(_referPattern_4, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("I1 != I2;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("I1 != I3;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("I2 != I3;"); + _builder.newLine(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern tooManyInputsOfSegment_must_to_true_by_divergent("); + _builder.append(parameters); + _builder.append(", S : DefinedElement) {"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("find mustExist(problem, interpretation, S);"); + _builder.newLine(); + _builder.append("\t"); + CharSequence _referInstanceOf_19 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.simpleSegmentType, Modality.MUST, "S"); + _builder.append(_referInstanceOf_19, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("find output_must_to_true_by_divergent(problem, interpretation, source, target, I1, S);"); + _builder.newLine(); + _builder.append("\t"); + CharSequence _referPattern_5 = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(Output.instance().getFullyQualifiedName()), new String[] { "I2", "S" }, Modality.MUST, true, false); + _builder.append(_referPattern_5, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referPattern_6 = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(Output.instance().getFullyQualifiedName()), new String[] { "I3", "S" }, Modality.MUST, true, false); + _builder.append(_referPattern_6, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("I1 != I2;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("I1 != I3;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("I2 != I3;"); + _builder.newLine(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern turnoutConnectedToBothOutputs_must_to_true_by_connectedTo("); + _builder.append(parameters); + _builder.append(", T : DefinedElement) {"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append(commonMayParameterConstraints, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("find mustExist(problem, interpretation, Straight);"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("find mustExist(problem, interpretation, Divergent);"); + _builder.newLine(); + _builder.append("\t"); + CharSequence _referInstanceOf_20 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MAY, "source"); + _builder.append(_referInstanceOf_20, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referInstanceOf_21 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MAY, "target"); + _builder.append(_referInstanceOf_21, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referInstanceOf_22 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "Straight"); + _builder.append(_referInstanceOf_22, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referInstanceOf_23 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "Divergent"); + _builder.append(_referInstanceOf_23, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referRelation_26 = generator.referRelation(Modes3UnitPropagationGenerator.this.straightRelation, "T", "Straight", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation_26, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referRelation_27 = generator.referRelation(Modes3UnitPropagationGenerator.this.divergentRelation, "T", "Divergent", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation_27, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("T == source;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("Straight == target;"); + _builder.newLine(); + _builder.append("\t"); + CharSequence _referRelation_28 = generator.referRelation(Modes3UnitPropagationGenerator.this.connectedToRelation, "T", "Divergent", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation_28, "\t"); _builder.newLineIfNotEmpty(); _builder.append("} or {"); _builder.newLine(); _builder.append("\t"); - _builder.append("// turnoutConnectedToBothOutputs unit propagation"); + _builder.append(commonMayParameterConstraints, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("find mustExist(problem, interpretation, Straight);"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("find mustExist(problem, interpretation, Divergent);"); + _builder.newLine(); + _builder.append("\t"); + CharSequence _referInstanceOf_24 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MAY, "source"); + _builder.append(_referInstanceOf_24, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referInstanceOf_25 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MAY, "target"); + _builder.append(_referInstanceOf_25, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referInstanceOf_26 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "Straight"); + _builder.append(_referInstanceOf_26, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referInstanceOf_27 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "Divergent"); + _builder.append(_referInstanceOf_27, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referRelation_29 = generator.referRelation(Modes3UnitPropagationGenerator.this.straightRelation, "T", "Straight", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation_29, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referRelation_30 = generator.referRelation(Modes3UnitPropagationGenerator.this.divergentRelation, "T", "Divergent", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation_30, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referRelation_31 = generator.referRelation(Modes3UnitPropagationGenerator.this.connectedToRelation, "T", "Straight", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation_31, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("T == source;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("Straight == target;"); + _builder.newLine(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern turnoutConnectedToBothOutputs_must_to_true_by_straight("); + _builder.append(parameters); + _builder.append(", T : DefinedElement) {"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append(commonMayParameterConstraints, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("find mustExist(problem, interpretation, Straight);"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("find mustExist(problem, interpretation, Divergent);"); _builder.newLine(); _builder.append("\t"); - _builder.append(commonParameterConstraints, "\t"); + CharSequence _referInstanceOf_28 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MAY, "source"); + _builder.append(_referInstanceOf_28, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referInstanceOf_29 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MAY, "target"); + _builder.append(_referInstanceOf_29, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referInstanceOf_30 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "Straight"); + _builder.append(_referInstanceOf_30, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_34 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MUST, "source"); + CharSequence _referInstanceOf_31 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "Divergent"); + _builder.append(_referInstanceOf_31, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("T == source;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("Straight == target;"); + _builder.newLine(); + _builder.append("\t"); + CharSequence _referRelation_32 = generator.referRelation(Modes3UnitPropagationGenerator.this.divergentRelation, "T", "Divergent", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation_32, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referRelation_33 = generator.referRelation(Modes3UnitPropagationGenerator.this.connectedToRelation, "T", "Straight", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation_33, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referRelation_34 = generator.referRelation(Modes3UnitPropagationGenerator.this.connectedToRelation, "T", "Divergent", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation_34, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern turnoutConnectedToBothOutputs_must_to_true_by_divergent("); + _builder.append(parameters); + _builder.append(", T : DefinedElement) {"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append(commonMayParameterConstraints, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("find mustExist(problem, interpretation, Straight);"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("find mustExist(problem, interpretation, Divergent);"); + _builder.newLine(); + _builder.append("\t"); + CharSequence _referInstanceOf_32 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MAY, "source"); + _builder.append(_referInstanceOf_32, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referInstanceOf_33 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MAY, "target"); + _builder.append(_referInstanceOf_33, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referInstanceOf_34 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "Straight"); _builder.append(_referInstanceOf_34, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_35 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "target"); + CharSequence _referInstanceOf_35 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "Divergent"); _builder.append(_referInstanceOf_35, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_36 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MUST, "straight"); + CharSequence _referRelation_35 = generator.referRelation(Modes3UnitPropagationGenerator.this.straightRelation, "T", "Straight", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation_35, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("T == source;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("Divergent == target;"); + _builder.newLine(); + _builder.append("\t"); + CharSequence _referRelation_36 = generator.referRelation(Modes3UnitPropagationGenerator.this.connectedToRelation, "T", "Straight", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation_36, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referRelation_37 = generator.referRelation(Modes3UnitPropagationGenerator.this.connectedToRelation, "T", "Divergent", Modality.MUST, fqnToPQuery); + _builder.append(_referRelation_37, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern tooManyInputsOfTurnout_must_to_true_by_connectedTo("); + _builder.append(parameters); + _builder.append(", T : DefinedElement) {"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("find mustExist(problem, interpretation, S);"); + _builder.newLine(); + _builder.append("\t"); + CharSequence _referInstanceOf_36 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MUST, "S"); _builder.append(_referInstanceOf_36, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referRelation_13 = generator.referRelation(Modes3UnitPropagationGenerator.this.connectedToRelation, "source", "target", Modality.MUST, fqnToPQuery); - _builder.append(_referRelation_13, "\t"); + _builder.append("find adjacent_must_to_true_by_connectedTo(problem, interpretation, source, target, I1, S);"); + _builder.newLine(); + _builder.append("\t"); + CharSequence _referPattern_7 = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(Adjacent.instance().getFullyQualifiedName()), new String[] { "I2", "S" }, Modality.MUST, true, false); + _builder.append(_referPattern_7, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referRelation_14 = generator.referRelation(Modes3UnitPropagationGenerator.this.straightRelation, "source", "straight", Modality.MUST, fqnToPQuery); - _builder.append(_referRelation_14, "\t"); + CharSequence _referPattern_8 = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(Adjacent.instance().getFullyQualifiedName()), new String[] { "I3", "S" }, Modality.MUST, true, false); + _builder.append(_referPattern_8, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referRelation_15 = generator.referRelation(Modes3UnitPropagationGenerator.this.connectedToRelation, "source", "straight", Modality.MUST, fqnToPQuery); - _builder.append(_referRelation_15, "\t"); + CharSequence _referPattern_9 = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(Adjacent.instance().getFullyQualifiedName()), new String[] { "I4", "S" }, Modality.MUST, true, false); + _builder.append(_referPattern_9, "\t"); _builder.newLineIfNotEmpty(); - _builder.append("} or {"); + _builder.append("\t"); + _builder.append("I1 != I2;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("I1 != I3;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("I1 != I4;"); _builder.newLine(); _builder.append("\t"); - _builder.append("// tooManyExtraInputsOfTurnout unit propagation"); + _builder.append("I2 != I3;"); _builder.newLine(); _builder.append("\t"); - _builder.append(commonParameterConstraints, "\t"); + _builder.append("I2 != I4;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("I3 != I4;"); + _builder.newLine(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern tooManyInputsOfTurnout_must_to_true_by_straight("); + _builder.append(parameters); + _builder.append(", T : DefinedElement) {"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_37 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MUST, "source"); + _builder.append("find mustExist(problem, interpretation, S);"); + _builder.newLine(); + _builder.append("\t"); + CharSequence _referInstanceOf_37 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MUST, "S"); _builder.append(_referInstanceOf_37, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_38 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "target"); + _builder.append("find adjacent_must_to_true_by_straight(problem, interpretation, source, target, I1, S);"); + _builder.newLine(); + _builder.append("\t"); + CharSequence _referPattern_10 = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(Adjacent.instance().getFullyQualifiedName()), new String[] { "I2", "S" }, Modality.MUST, true, false); + _builder.append(_referPattern_10, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referPattern_11 = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(Adjacent.instance().getFullyQualifiedName()), new String[] { "I3", "S" }, Modality.MUST, true, false); + _builder.append(_referPattern_11, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + CharSequence _referPattern_12 = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(Adjacent.instance().getFullyQualifiedName()), new String[] { "I4", "S" }, Modality.MUST, true, false); + _builder.append(_referPattern_12, "\t"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("I1 != I2;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("I1 != I3;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("I1 != I4;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("I2 != I3;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("I2 != I4;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("I3 != I4;"); + _builder.newLine(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern tooManyInputsOfTurnout_must_to_true_by_divergent("); + _builder.append(parameters); + _builder.append(", T : DefinedElement) {"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("find mustExist(problem, interpretation, S);"); + _builder.newLine(); + _builder.append("\t"); + CharSequence _referInstanceOf_38 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.turnoutType, Modality.MUST, "S"); _builder.append(_referInstanceOf_38, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_39 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "extraInput"); - _builder.append(_referInstanceOf_39, "\t"); + _builder.append("find adjacent_must_to_true_by_divergent(problem, interpretation, source, target, I1, S);"); + _builder.newLine(); + _builder.append("\t"); + CharSequence _referPattern_13 = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(Adjacent.instance().getFullyQualifiedName()), new String[] { "I2", "S" }, Modality.MUST, true, false); + _builder.append(_referPattern_13, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referInstanceOf_40 = generator.getTypeIndexer().referInstanceOf(Modes3UnitPropagationGenerator.this.segmentType, Modality.MUST, "potentialExtraInput"); - _builder.append(_referInstanceOf_40, "\t"); + CharSequence _referPattern_14 = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(Adjacent.instance().getFullyQualifiedName()), new String[] { "I3", "S" }, Modality.MUST, true, false); + _builder.append(_referPattern_14, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referPattern_7 = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(ExtraInputOfTurnout.instance().getFullyQualifiedName()), new String[] { "source", "extraInput" }, Modality.MUST, true, false); - _builder.append(_referPattern_7, "\t"); + CharSequence _referPattern_15 = generator.getRelationDefinitionIndexer().referPattern(fqnToPQuery.get(Adjacent.instance().getFullyQualifiedName()), new String[] { "I4", "S" }, Modality.MUST, true, false); + _builder.append(_referPattern_15, "\t"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - CharSequence _referRelation_16 = generator.referRelation(Modes3UnitPropagationGenerator.this.connectedToRelation, "source", "potentialExtraInput", Modality.MUST, fqnToPQuery); - _builder.append(_referRelation_16, "\t"); + _builder.append("I1 != I2;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("I1 != I3;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("I1 != I4;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("I2 != I3;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("I2 != I4;"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("I3 != I4;"); + _builder.newLine(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern "); + _builder.append(Modes3UnitPropagationGenerator.MUST_NOT_CONNECTED_TO); + _builder.append("_helper("); + _builder.append(parameters); + _builder.append(") {"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - _builder.append("neg "); - CharSequence _referRelation_17 = generator.referRelation(Modes3UnitPropagationGenerator.this.straightRelation, "source", "potentialExtraInput", Modality.MAY, fqnToPQuery); - _builder.append(_referRelation_17, "\t"); + _builder.append("find connectedToReflexive_must_to_true_by_connectedTo(problem, interpretation, source, target, _);"); + _builder.newLine(); + _builder.append("} or {"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("find tooManyInputsOfSegment_must_to_true_by_connectedTo(problem, interpretation, source, target, _);"); + _builder.newLine(); + _builder.append("} or {"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("find turnoutConnectedToBothOutputs_must_to_true_by_connectedTo(problem, interpretation, source, target, _);"); + _builder.newLine(); + _builder.append("} or {"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("find tooManyInputsOfTurnout_must_to_true_by_connectedTo(problem, interpretation, source, target, _);"); + _builder.newLine(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern "); + _builder.append(Modes3UnitPropagationGenerator.MUST_NOT_CONNECTED_TO); + _builder.append("("); + _builder.append(parameters); + _builder.append(") {"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("find "); + _builder.append(Modes3UnitPropagationGenerator.MUST_NOT_CONNECTED_TO, "\t"); + _builder.append("_helper(problem, interpretation, source, target);"); + _builder.newLineIfNotEmpty(); + _builder.append("} or {"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("find "); + _builder.append(Modes3UnitPropagationGenerator.MUST_NOT_CONNECTED_TO, "\t"); + _builder.append("_helper(problem, interpretation, target, source);"); + _builder.newLineIfNotEmpty(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern "); + _builder.append(Modes3UnitPropagationGenerator.MUST_NOT_STRAIGHT); + _builder.append("("); + _builder.append(parameters); + _builder.append(") {"); _builder.newLineIfNotEmpty(); _builder.append("\t"); - _builder.append("extraInput != potentialExtraInput;"); + _builder.append("find outputReflexive_must_to_true_by_straight(problem, interpretation, source, target, _);"); + _builder.newLine(); + _builder.append("} or {"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("find turnoutOutputsAreSame_must_to_true_by_straight(problem, interpretation, source, target, _);"); + _builder.newLine(); + _builder.append("} or {"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("find tooManyInputsOfSegment_must_to_true_by_straight(problem, interpretation, source, target, _);"); + _builder.newLine(); + _builder.append("} or {"); _builder.newLine(); _builder.append("\t"); - _builder.append("extraInput != target;"); + _builder.append("find turnoutConnectedToBothOutputs_must_to_true_by_straight(problem, interpretation, source, target, _);"); + _builder.newLine(); + _builder.append("} or {"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("find tooManyInputsOfTurnout_must_to_true_by_straight(problem, interpretation, source, target, _);"); + _builder.newLine(); + _builder.append("}"); + _builder.newLine(); + _builder.newLine(); + _builder.append("pattern "); + _builder.append(Modes3UnitPropagationGenerator.MUST_NOT_DIVERGENT); + _builder.append("("); + _builder.append(parameters); + _builder.append(") {"); + _builder.newLineIfNotEmpty(); + _builder.append("\t"); + _builder.append("find outputReflexive_must_to_true_by_divergent(problem, interpretation, source, target, _);"); + _builder.newLine(); + _builder.append("} or {"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("find turnoutOutputsAreSame_must_to_true_by_divergent(problem, interpretation, source, target, _);"); + _builder.newLine(); + _builder.append("} or {"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("find tooManyInputsOfSegment_must_to_true_by_divergent(problem, interpretation, source, target, _);"); + _builder.newLine(); + _builder.append("} or {"); + _builder.newLine(); + _builder.append("\t"); + _builder.append("find turnoutConnectedToBothOutputs_must_to_true_by_divergent(problem, interpretation, source, target, _);"); + _builder.newLine(); + _builder.append("} or {"); _builder.newLine(); _builder.append("\t"); - _builder.append("potentialExtraInput != target;"); + _builder.append("find tooManyInputsOfTurnout_must_to_true_by_divergent(problem, interpretation, source, target, _);"); _builder.newLine(); _builder.append("}"); _builder.newLine(); } }; - _xblockexpression = _client_2; + _xblockexpression = _client_3; } return _xblockexpression; } diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph/plugin.xml b/Domains/hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph/plugin.xml index 331e2b61..d4ab204e 100644 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph/plugin.xml +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph/plugin.xml @@ -39,72 +39,4 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 431ae386..3bcd9116 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 @@ -49,6 +49,12 @@ class ModelGenerationStatistics { synchronized def addScopePropagationTime(long amount) { scopePropagationTime += amount } + + public var long mustRelationPropagationTime = 0 + + synchronized def addMustRelationPropagationTime(long amount) { + mustRelationPropagationTime += amount + } public var long preliminaryTypeAnalisisTime = 0 @@ -133,9 +139,11 @@ class ModelGenerationMethodProvider { val scopePropagator = createScopePropagator(scopePropagatorStrategy, emptySolution, hints, queries, statistics) scopePropagator.propagateAllScopeConstraints + val unitRulePropagator = refinementRuleProvider.createUnitPrulePropagator(logicProblem, emptySolution, + queries, scopePropagator, statistics) val objectRefinementRules = refinementRuleProvider.createObjectRefinementRules(logicProblem, emptySolution, - queries, scopePropagator, nameNewElements, statistics) - val relationRefinementRules = refinementRuleProvider.createRelationRefinementRules(queries, scopePropagator, + queries, unitRulePropagator, nameNewElements, statistics) + val relationRefinementRules = refinementRuleProvider.createRelationRefinementRules(queries, unitRulePropagator, statistics) val unfinishedMultiplicities = goalConstraintProvider.getUnfinishedMultiplicityQueries(logicProblem, queries, @@ -158,7 +166,7 @@ class ModelGenerationMethodProvider { val currentUnitPropagationPreconditions = queries.getCurrentUnitPropagationPreconditionPatterns val queriesToPrepare = ImmutableSet.builder.addAll(queries.refineObjectQueries.values).addAll( - queries.refineTypeQueries.values).addAll(queries.refinerelationQueries.values).addAll(queries. + queries.refineTypeQueries.values).addAll(queries.refineRelationQueries.values).addAll(queries. multiplicityConstraintQueries.values.flatMap[allQueries]).addAll(queries.unfinishedWFQueries.values).addAll( queries.invalidWFQueries.values).addAll(queries.mustUnitPropagationPreconditionPatterns.values).addAll( queries.currentUnitPropagationPreconditionPatterns.values).add(queries.hasElementInContainmentQuery).build 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 index 8c21ca1d..31f98e36 100644 --- 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 @@ -3,8 +3,10 @@ package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternGenerator import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation +import java.util.Map import org.eclipse.viatra.query.runtime.api.IPatternMatch import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery interface LinearTypeExpressionBuilderFactory { def ViatraQueryMatcher createMatcher(String queryName) @@ -24,7 +26,7 @@ interface RelationConstraintUpdater { } interface LinearTypeConstraintHint { - def CharSequence getAdditionalPatterns(PatternGenerator patternGenerator) + def CharSequence getAdditionalPatterns(PatternGenerator patternGenerator, Map fqnToPQuery) def RelationConstraintUpdater createConstraintUpdater(LinearTypeExpressionBuilderFactory builderFactory) } diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ScopePropagator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ScopePropagator.xtend index 93b83577..cacba3c6 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ScopePropagator.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ScopePropagator.xtend @@ -19,6 +19,8 @@ class ScopePropagator { val Map type2Scope @Accessors(PROTECTED_GETTER) val Map> superScopes @Accessors(PROTECTED_GETTER) val Map> subScopes + + @Accessors(PUBLIC_GETTER) var scopePropagationNeeded = false new(PartialInterpretation p, ModelGenerationStatistics statistics) { partialInterpretation = p @@ -64,7 +66,8 @@ class ScopePropagator { copyScopeBoundsToHeuristic() } - def propagateAllScopeConstraints() { + def void propagateAllScopeConstraints() { + scopePropagationNeeded = false if (!valid) { return } @@ -93,6 +96,7 @@ class ScopePropagator { if (isPrimitive) { return } + scopePropagationNeeded = true // println('''Adding to «(t as PartialComplexTypeInterpretation).interpretationOf.name»''') val targetScope = type2Scope.get(t) if (targetScope !== null) { @@ -117,6 +121,12 @@ class ScopePropagator { // this.partialInterpretation.scopes.forEach[println(''' «(it.targetTypeInterpretation as PartialComplexTypeInterpretation).interpretationOf.name»: «it.minNewElements»-«it.maxNewElements»''')] // println('''All constraints are propagated upon increasing «(t as PartialComplexTypeInterpretation).interpretationOf.name»''') } + + def addedToRelation(Relation r) { + if (isPropagationNeededAfterAdditionToRelation(r)) { + scopePropagationNeeded = true + } + } protected def setScopesInvalid() { partialInterpretation.minNewElements = Integer.MAX_VALUE @@ -127,7 +137,7 @@ class ScopePropagator { } } - def isPropagationNeededAfterAdditionToRelation(Relation r) { + protected def isPropagationNeededAfterAdditionToRelation(Relation r) { false } 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 a3efcf76..edf92343 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 @@ -369,13 +369,13 @@ class PatternGenerator { ////////// // 4.3 Relation refinement ////////// - «relationRefinementGenerator.generateRefineReference(problem)» + «relationRefinementGenerator.generateRefineReference(problem, unitPropagationPatternGenerators)» ////////// // 5 Hints ////////// «FOR hint : hints» - «hint.getAdditionalPatterns(this)» + «hint.getAdditionalPatterns(this, fqn2PQuery)» «ENDFOR» «FOR generator : unitPropagationPatternGenerators» «generator.getAdditionalPatterns(this, fqn2PQuery)» 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 21fd1989..2e786286 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 @@ -38,7 +38,8 @@ import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.* public IQuerySpecification> hasElementInContainmentQuery public Map>> refineObjectQueries public Map>> refineTypeQueries - public Map, IQuerySpecification>> refinerelationQueries + public Map, IQuerySpecification>> refineRelationQueries + public Map, IQuerySpecification>> mustRelationPropagationQueries public Map>> mustUnitPropagationPreconditionPatterns public Map>> currentUnitPropagationPreconditionPatterns public Map modalRelationQueries @@ -70,7 +71,6 @@ class UnifinishedMultiplicityQueries { } class PatternProvider { - val TypeAnalysis typeAnalysis = new TypeAnalysis def generateQueries(LogicProblem problem, PartialInterpretation emptySolution, ModelGenerationStatistics statistics, @@ -98,7 +98,8 @@ class PatternProvider { val generatedQueries = parseUtil.parse(patternGeneratorResult.patternText) val runtimeQueries = calclulateRuntimeQueries(patternGenerator, problem, emptySolution, typeAnalysisResult, patternGeneratorResult.constraint2MustPreconditionName, - patternGeneratorResult.constraint2CurrentPreconditionName, relationConstraints, generatedQueries) + patternGeneratorResult.constraint2CurrentPreconditionName, relationConstraints, + unitPropagationPatternGenerators, generatedQueries) return runtimeQueries } @@ -110,6 +111,7 @@ class PatternProvider { HashMap mustUnitPropagationTrace, HashMap currentUnitPropagationTrace, RelationConstraints relationConstraints, + Collection unitPropagationPatternGenerators, Map>> queries ) { val Map>> invalidWFQueries = patternGenerator. @@ -136,6 +138,8 @@ class PatternProvider { ] val Map, IQuerySpecification>> refineRelationQueries = patternGenerator. relationRefinementGenerator.getRefineRelationQueries(problem).mapValues[it.lookup(queries)] + val Map, IQuerySpecification>> mustRelationPropagationQueries = patternGenerator. + relationRefinementGenerator.getMustPropagationQueries(problem, unitPropagationPatternGenerators).mapValues[it.lookup(queries)] val Map>> mustUnitPropagationPreconditionPatterns = mustUnitPropagationTrace. mapValues[it.lookup(queries)] val Map>> currentUnitPropagationPreconditionPatterns = currentUnitPropagationTrace. @@ -158,6 +162,7 @@ class PatternProvider { refineObjectsQueries, refineTypeQueries, refineRelationQueries, + mustRelationPropagationQueries, mustUnitPropagationPreconditionPatterns, currentUnitPropagationPreconditionPatterns, modalRelationQueries, diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/RelationDeclarationIndexer.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/RelationDeclarationIndexer.xtend index 29d3eb61..23ba3cad 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/RelationDeclarationIndexer.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/RelationDeclarationIndexer.xtend @@ -113,7 +113,7 @@ class RelationDeclarationIndexer { // 2. Circle in the containment hierarchy neg «base.containmentIndexer.referTransitiveMustContains("source","target")» «ENDIF» - «IF mustNotRelations.empty» + «IF !mustNotRelations.empty» // ![] unit propagation relations «FOR mustNotRelation : mustNotRelations» neg find «mustNotRelation»(problem, interpretation, source, target); 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 783cd36b..6f5f2402 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 @@ -1,10 +1,17 @@ package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns +import com.google.common.collect.ImmutableList +import com.google.common.collect.ImmutableMap +import com.google.common.collect.ImmutableSet import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Relation import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RelationDeclaration import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality +import java.util.Collection import java.util.LinkedList +import java.util.Map +import java.util.Set +import org.eclipse.xtend2.lib.StringConcatenationClient class RelationRefinementGenerator { PatternGenerator base; @@ -13,53 +20,61 @@ class RelationRefinementGenerator { this.base = base } - def CharSequence generateRefineReference(LogicProblem p) ''' - «FOR relationRefinement : this.getRelationRefinements(p)» - pattern «relationRefinementQueryName(relationRefinement.key,relationRefinement.value)»( - problem:LogicProblem, interpretation:PartialInterpretation, - relationIterpretation:PartialRelationInterpretation«IF relationRefinement.value !== null», oppositeInterpretation:PartialRelationInterpretation«ENDIF», - from: DefinedElement, to: DefinedElement) - { - find interpretation(problem,interpretation); - PartialInterpretation.partialrelationinterpretation(interpretation,relationIterpretation); - PartialRelationInterpretation.interpretationOf.name(relationIterpretation,"«relationRefinement.key.name»"); - «IF relationRefinement.value !== null» - PartialInterpretation.partialrelationinterpretation(interpretation,oppositeInterpretation); - PartialRelationInterpretation.interpretationOf.name(oppositeInterpretation,"«relationRefinement.value.name»"); + def CharSequence generateRefineReference(LogicProblem p, + Collection unitPropagationPatternGenerators) { + val mustRelations = getMustRelations(unitPropagationPatternGenerators) + + ''' + «FOR relationRefinement : this.getRelationRefinements(p)» + pattern «relationRefinementQueryName(relationRefinement.key,relationRefinement.value)»( + problem:LogicProblem, interpretation:PartialInterpretation, + relationIterpretation:PartialRelationInterpretation«IF relationRefinement.value !== null», oppositeInterpretation:PartialRelationInterpretation«ENDIF», + from: DefinedElement, to: DefinedElement) + { + find interpretation(problem,interpretation); + PartialInterpretation.partialrelationinterpretation(interpretation,relationIterpretation); + PartialRelationInterpretation.interpretationOf.name(relationIterpretation,"«relationRefinement.key.name»"); + «IF relationRefinement.value !== null» + PartialInterpretation.partialrelationinterpretation(interpretation,oppositeInterpretation); + PartialRelationInterpretation.interpretationOf.name(oppositeInterpretation,"«relationRefinement.value.name»"); + «ENDIF» + find mustExist(problem, interpretation, from); + find mustExist(problem, interpretation, to); + «base.typeIndexer.referInstanceOfByReference(relationRefinement.key.parameters.get(0), Modality::MUST,"from")» + «base.typeIndexer.referInstanceOfByReference(relationRefinement.key.parameters.get(1), Modality::MUST,"to")» + «base.relationDeclarationIndexer.referRelation(relationRefinement.key,"from","to",Modality.MAY)» + neg «base.relationDeclarationIndexer.referRelation(relationRefinement.key,"from","to",Modality.MUST)» + } + + «IF isMustPropagationQueryNeeded(relationRefinement.key, relationRefinement.value, mustRelations)» + pattern «mustPropagationQueryName(relationRefinement.key)»( + problem:LogicProblem, interpretation:PartialInterpretation, + relationIterpretation:PartialRelationInterpretation«IF relationRefinement.value !== null», oppositeInterpretation:PartialRelationInterpretation«ENDIF», + from: DefinedElement, to: DefinedElement) + «FOR body : getMustPropagationBodies(relationRefinement.key, relationRefinement.value, mustRelations) SEPARATOR " or "» + { + «referRefinementQuery(relationRefinement.key, relationRefinement.value, "relationIterpretation", "oppositeInterpretation", "from", "to")» + «body» + } + «ENDFOR» «ENDIF» - find mustExist(problem, interpretation, from); - find mustExist(problem, interpretation, to); - «base.typeIndexer.referInstanceOfByReference(relationRefinement.key.parameters.get(0), Modality::MUST,"from")» - «base.typeIndexer.referInstanceOfByReference(relationRefinement.key.parameters.get(1), Modality::MUST,"to")» - «base.relationDeclarationIndexer.referRelation(relationRefinement.key,"from","to",Modality.MAY)» - neg «base.relationDeclarationIndexer.referRelation(relationRefinement.key,"from","to",Modality.MUST)» - } - «ENDFOR» - ''' + «ENDFOR» + ''' + } def String relationRefinementQueryName(RelationDeclaration relation, Relation inverseRelation) { '''«IF inverseRelation !== null»refineRelation_«base.canonizeName(relation.name)»_and_«base.canonizeName(inverseRelation.name)»«ELSE»refineRelation_«base.canonizeName(relation.name)»«ENDIF»''' } + def String mustPropagationQueryName(RelationDeclaration relation) { + '''mustPropagation_«base.canonizeName(relation.name)»''' + } + def referRefinementQuery(RelationDeclaration relation, Relation inverseRelation, String relInterpretationName, String inverseInterpretationName, String sourceName, String targetName) '''find «this.relationRefinementQueryName(relation,inverseRelation)»(problem, interpretation, «relInterpretationName», «IF inverseRelation !== null»«inverseInterpretationName», «ENDIF»«sourceName», «targetName»);''' def getRefineRelationQueries(LogicProblem p) { -// val containmentRelations = p.containmentHierarchies.map[containmentRelations].flatten.toSet -// p.relations.filter(RelationDeclaration).filter[!containmentRelations.contains(it)].toInvertedMap['''refineRelation_«base.canonizeName(it.name)»'''] - /* - * val res = new LinkedHashMap - * for(relation: getRelationRefinements(p)) { - * if(inverseRelations.containsKey(relation)) { - * val name = '''refineRelation_«base.canonizeName(relation.name)»_and_«base.canonizeName(inverseRelations.get(relation).name)»''' - * res.put(relation -> inverseRelations.get(relation),name) - * } else { - * val name = '''refineRelation_«base.canonizeName(relation.name)»''' - * res.put(relation -> null,name) - * } - * } - return res*/ getRelationRefinements(p).toInvertedMap[relationRefinementQueryName(it.key, it.value)] } @@ -83,4 +98,54 @@ class RelationRefinementGenerator { } return list } + + def getMustPropagationQueries(LogicProblem p, + Collection unitPropagationPatternGenerators) { + val refinements = getRelationRefinements(p) + val mustRelations = getMustRelations(unitPropagationPatternGenerators) + refinements.filter[isMustPropagationQueryNeeded(key, value, mustRelations)].toInvertedMap [ + mustPropagationQueryName(key) + ] + } + + private def getMustRelations(Collection unitPropagationPatternGenerators) { + ImmutableMap.copyOf(unitPropagationPatternGenerators.flatMap[mustPatterns.entrySet].groupBy[key].mapValues [ + ImmutableSet.copyOf(map[value]) + ]) + } + + private def isMustPropagationQueryNeeded(Relation relation, Relation inverseRelation, + Map> mustRelations) { + val mustSet = mustRelations.get(relation) + if (mustSet !== null && !mustSet.empty) { + return true + } + if (inverseRelation !== null) { + val inverseMustSet = mustRelations.get(inverseRelation) + if (inverseMustSet !== null && !inverseMustSet.empty) { + return true + } + } + false + } + + private def getMustPropagationBodies(Relation relation, Relation inverseRelation, + Map> mustRelations) { + val builder = ImmutableList.builder() + val mustSet = mustRelations.get(relation) + if (mustSet !== null) { + for (refinementQuery : mustSet) { + builder.add('''find «refinementQuery»(problem, interpretation, from, to);''') + } + } + if (inverseRelation !== null && inverseRelation != relation) { + val inverseMustSet = mustRelations.get(inverseRelation) + if (inverseMustSet !== null) { + for (refinementQuery : inverseMustSet) { + builder.add('''find «refinementQuery»(problem, interpretation, to, from);''') + } + } + } + builder.build + } } 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 699b095d..dca10baf 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/rules/RefinementRuleProvider.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/rules/RefinementRuleProvider.xtend @@ -1,5 +1,6 @@ package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules +import com.google.common.collect.ImmutableList import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.InverseRelationAssertion import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.LowerMultiplicityAssertion import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.BoolTypeReference @@ -29,12 +30,14 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.par import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationFactory import java.lang.reflect.Field import java.util.HashMap +import java.util.Iterator import java.util.LinkedHashMap import java.util.LinkedList import java.util.List import java.util.Map import org.eclipse.viatra.query.runtime.api.AdvancedViatraQueryEngine import org.eclipse.viatra.query.runtime.api.GenericPatternMatch +import org.eclipse.viatra.query.runtime.api.IPatternMatch import org.eclipse.viatra.query.runtime.api.IQuerySpecification import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher @@ -43,6 +46,7 @@ import org.eclipse.viatra.query.runtime.rete.matcher.ReteBackendFactory import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRule import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRuleFactory import org.eclipse.xtend.lib.annotations.Data +import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor import org.eclipse.xtext.xbase.lib.Functions.Function0 class RefinementRuleProvider { @@ -50,57 +54,55 @@ class RefinementRuleProvider { val extension PartialinterpretationFactory factory2 = PartialinterpretationFactory.eINSTANCE val extension LogiclanguageFactory factory3 = LogiclanguageFactory.eINSTANCE - var AdvancedViatraQueryEngine queryEngine - var Field delayMessageDelivery - def canonizeName(String name) { return name.replace(' ', '_') } + def createUnitPrulePropagator(LogicProblem p, PartialInterpretation i, GeneratedPatterns patterns, + ScopePropagator scopePropagator, ModelGenerationStatistics statistics) { + new UnitRulePropagator(p, i, this, scopePropagator, patterns.mustRelationPropagationQueries, statistics) + } + def LinkedHashMap>> createObjectRefinementRules( LogicProblem p, PartialInterpretation i, GeneratedPatterns patterns, - ScopePropagator scopePropagator, + UnitRulePropagator unitRulePropagator, boolean nameNewElement, ModelGenerationStatistics statistics ) { val res = new LinkedHashMap val recursiveObjectCreation = recursiveObjectCreation(p, i) - queryEngine = ViatraQueryEngine.on(new EMFScope(i)) as AdvancedViatraQueryEngine - delayMessageDelivery = queryEngine.class.getDeclaredField("delayMessageDelivery") - delayMessageDelivery.accessible = true for (LHSEntry : patterns.refineObjectQueries.entrySet) { val containmentRelation = LHSEntry.key.containmentRelation val inverseRelation = LHSEntry.key.inverseContainment val type = LHSEntry.key.newType val lhs = LHSEntry.value as IQuerySpecification> val rule = createObjectCreationRule(p, containmentRelation, inverseRelation, type, - recursiveObjectCreation.get(type), lhs, nameNewElement, scopePropagator, statistics) + recursiveObjectCreation.get(type), lhs, nameNewElement, unitRulePropagator, statistics) res.put(LHSEntry.key, rule) } return res } def private createObjectCreationRule(LogicProblem p, Relation containmentRelation, Relation inverseRelation, - Type type, List recursiceObjectCreations, + Type type, List recursiveObjectCreations, IQuerySpecification> lhs, boolean nameNewElement, - ScopePropagator scopePropagator, ModelGenerationStatistics statistics) { + UnitRulePropagator unitRulePropagator, ModelGenerationStatistics statistics) { val name = '''addObject_«type.name.canonizeName»«IF containmentRelation!==null»_by_«containmentRelation.name.canonizeName»«ENDIF»''' val ruleBuilder = factory.createRule(lhs).name(name) if (containmentRelation !== null) { if (inverseRelation !== null) { ruleBuilder.action [ match | statistics.incrementTransformationCount -// println(name) +// println(name) + val startTime = System.nanoTime // val problem = match.get(0) as LogicProblem val interpretation = match.get(1) as PartialInterpretation val relationInterpretation = match.get(2) as PartialRelationInterpretation val inverseRelationInterpretation = match.get(3) as PartialRelationInterpretation val typeInterpretation = match.get(4) as PartialComplexTypeInterpretation val container = match.get(5) as DefinedElement - - val startTime = System.nanoTime createObjectActionWithContainmentAndInverse( nameNewElement, interpretation, @@ -109,29 +111,24 @@ class RefinementRuleProvider { relationInterpretation, inverseRelationInterpretation, [createDefinedElement], - recursiceObjectCreations, - scopePropagator + recursiveObjectCreations, + unitRulePropagator ) statistics.addExecutionTime(System.nanoTime - startTime) - flushQueryEngine(scopePropagator) - - // Scope propagation - val propagatorStartTime = System.nanoTime - scopePropagator.propagateAllScopeConstraints() - statistics.addScopePropagationTime(System.nanoTime - propagatorStartTime) + unitRulePropagator.propagate ] } else { ruleBuilder.action [ match | statistics.incrementTransformationCount // println(name) + val startTime = System.nanoTime // val problem = match.get(0) as LogicProblem val interpretation = match.get(1) as PartialInterpretation val relationInterpretation = match.get(2) as PartialRelationInterpretation val typeInterpretation = match.get(3) as PartialComplexTypeInterpretation val container = match.get(4) as DefinedElement - val startTime = System.nanoTime createObjectActionWithContainment( nameNewElement, interpretation, @@ -139,44 +136,34 @@ class RefinementRuleProvider { container, relationInterpretation, [createDefinedElement], - recursiceObjectCreations, - scopePropagator + recursiveObjectCreations, + unitRulePropagator ) statistics.addExecutionTime(System.nanoTime - startTime) - flushQueryEngine(scopePropagator) - - // Scope propagation - val propagatorStartTime = System.nanoTime - scopePropagator.propagateAllScopeConstraints() - statistics.addScopePropagationTime(System.nanoTime - propagatorStartTime) + unitRulePropagator.propagate ] } } else { ruleBuilder.action [ match | statistics.incrementTransformationCount // println(name) + val startTime = System.nanoTime // val problem = match.get(0) as LogicProblem val interpretation = match.get(1) as PartialInterpretation val typeInterpretation = match.get(2) as PartialComplexTypeInterpretation - val startTime = System.nanoTime createObjectAction( nameNewElement, interpretation, typeInterpretation, [createDefinedElement], - recursiceObjectCreations, - scopePropagator + recursiveObjectCreations, + unitRulePropagator ) statistics.addExecutionTime(System.nanoTime - startTime) - flushQueryEngine(scopePropagator) - - // Scope propagation - val propagatorStartTime = System.nanoTime - scopePropagator.propagateAllScopeConstraints() - statistics.addScopePropagationTime(System.nanoTime - propagatorStartTime) + unitRulePropagator.propagate ] } return ruleBuilder.build @@ -342,14 +329,14 @@ class RefinementRuleProvider { [createStringElement] } - def createRelationRefinementRules(GeneratedPatterns patterns, ScopePropagator scopePropagator, + def createRelationRefinementRules(GeneratedPatterns patterns, UnitRulePropagator unitRulePropagator, ModelGenerationStatistics statistics) { val res = new LinkedHashMap - for (LHSEntry : patterns.refinerelationQueries.entrySet) { + for (LHSEntry : patterns.refineRelationQueries.entrySet) { val declaration = LHSEntry.key.key val inverseReference = LHSEntry.key.value val lhs = LHSEntry.value as IQuerySpecification> - val rule = createRelationRefinementRule(declaration, inverseReference, lhs, scopePropagator, statistics) + val rule = createRelationRefinementRule(declaration, inverseReference, lhs, unitRulePropagator, statistics) res.put(LHSEntry.key, rule) } return res @@ -357,57 +344,29 @@ class RefinementRuleProvider { def private BatchTransformationRule> createRelationRefinementRule( RelationDeclaration declaration, Relation inverseRelation, - IQuerySpecification> lhs, ScopePropagator scopePropagator, + IQuerySpecification> lhs, UnitRulePropagator unitRulePropagator, ModelGenerationStatistics statistics) { val name = '''addRelation_«declaration.name.canonizeName»«IF inverseRelation !== null»_and_«inverseRelation.name.canonizeName»«ENDIF»''' val ruleBuilder = factory.createRule(lhs).name(name) if (inverseRelation === null) { ruleBuilder.action [ match | statistics.incrementTransformationCount - // println(name) - // val problem = match.get(0) as LogicProblem - // val interpretation = match.get(1) as PartialInterpretation - val relationInterpretation = match.get(2) as PartialRelationInterpretation - val src = match.get(3) as DefinedElement - val trg = match.get(4) as DefinedElement - val startTime = System.nanoTime - createRelationLinkAction(src, trg, relationInterpretation) + createRelationLinkAction(match, unitRulePropagator) statistics.addExecutionTime(System.nanoTime - startTime) - // Scope propagation - if (scopePropagator.isPropagationNeededAfterAdditionToRelation(declaration)) { - flushQueryEngine(scopePropagator) - - val propagatorStartTime = System.nanoTime - scopePropagator.propagateAllScopeConstraints() - statistics.addScopePropagationTime(System.nanoTime - propagatorStartTime) - } + unitRulePropagator.propagate ] } else { ruleBuilder.action [ match | statistics.incrementTransformationCount // println(name) - // val problem = match.get(0) as LogicProblem - // val interpretation = match.get(1) as PartialInterpretation - val relationInterpretation = match.get(2) as PartialRelationInterpretation - val inverseInterpretation = match.get(3) as PartialRelationInterpretation - val src = match.get(4) as DefinedElement - val trg = match.get(5) as DefinedElement - val startTime = System.nanoTime - createRelationLinkWithInverse(src, trg, relationInterpretation, inverseInterpretation) + createRelationLinkWithInverse(match, unitRulePropagator) statistics.addExecutionTime(System.nanoTime - startTime) - // Scope propagation - if (scopePropagator.isPropagationNeededAfterAdditionToRelation(declaration)) { - flushQueryEngine(scopePropagator) - - val propagatorStartTime = System.nanoTime - scopePropagator.propagateAllScopeConstraints() - statistics.addScopePropagationTime(System.nanoTime - propagatorStartTime) - } + unitRulePropagator.propagate ] } @@ -418,7 +377,7 @@ class RefinementRuleProvider { // Actions // /////////////////////// protected def void createObjectAction(boolean nameNewElement, ObjectCreationInterpretationData data, - DefinedElement container, ScopePropagator scopePropagator) { + DefinedElement container, UnitRulePropagator unitRulePropagator) { if (data.containerInterpretation !== null) { if (data.containerInverseInterpretation !== null) { createObjectActionWithContainmentAndInverse( @@ -430,7 +389,7 @@ class RefinementRuleProvider { data.containerInverseInterpretation, data.constructor, data.recursiveConstructors, - scopePropagator + unitRulePropagator ) } else { createObjectActionWithContainment( @@ -441,7 +400,7 @@ class RefinementRuleProvider { data.containerInterpretation, data.constructor, data.recursiveConstructors, - scopePropagator + unitRulePropagator ) } } else { @@ -451,7 +410,7 @@ class RefinementRuleProvider { data.typeInterpretation, data.constructor, data.recursiveConstructors, - scopePropagator + unitRulePropagator ) } @@ -466,7 +425,7 @@ class RefinementRuleProvider { PartialRelationInterpretation inverseRelationInterpretation, Function0 constructor, List recursiceObjectCreations, - ScopePropagator scopePropagator + UnitRulePropagator unitRulePropagator ) { val newElement = constructor.apply if (nameNewElement) { @@ -486,14 +445,16 @@ class RefinementRuleProvider { inverseRelationInterpretation.relationlinks += newLink2 // Scope propagation - scopePropagator.decrementTypeScope(typeInterpretation) + unitRulePropagator.decrementTypeScope(typeInterpretation) + unitRulePropagator.addedToRelation(relationInterpretation.interpretationOf) + unitRulePropagator.addedToRelation(inverseRelationInterpretation.interpretationOf) // Existence interpretation.newElements += newElement // Do recursive object creation for (newConstructor : recursiceObjectCreations) { - createObjectAction(nameNewElement, newConstructor, newElement, scopePropagator) + createObjectAction(nameNewElement, newConstructor, newElement, unitRulePropagator) } return newElement @@ -507,7 +468,7 @@ class RefinementRuleProvider { PartialRelationInterpretation relationInterpretation, Function0 constructor, List recursiceObjectCreations, - ScopePropagator scopePropagator + UnitRulePropagator unitRulePropagator ) { val newElement = constructor.apply if (nameNewElement) { @@ -522,16 +483,17 @@ class RefinementRuleProvider { // ContainmentRelation val newLink = factory2.createBinaryElementRelationLink => [it.param1 = container it.param2 = newElement] relationInterpretation.relationlinks += newLink + unitRulePropagator.addedToRelation(relationInterpretation.interpretationOf) // Scope propagation - scopePropagator.decrementTypeScope(typeInterpretation) + unitRulePropagator.decrementTypeScope(typeInterpretation) // Existence interpretation.newElements += newElement // Do recursive object creation for (newConstructor : recursiceObjectCreations) { - createObjectAction(nameNewElement, newConstructor, newElement, scopePropagator) + createObjectAction(nameNewElement, newConstructor, newElement, unitRulePropagator) } return newElement @@ -539,7 +501,7 @@ class RefinementRuleProvider { protected def createObjectAction(boolean nameNewElement, PartialInterpretation interpretation, PartialTypeInterpratation typeInterpretation, Function0 constructor, - List recursiceObjectCreations, ScopePropagator scopePropagator) { + List recursiceObjectCreations, UnitRulePropagator unitRulePropagator) { val newElement = constructor.apply if (nameNewElement) { newElement.name = '''new «interpretation.newElements.size»''' @@ -552,38 +514,220 @@ class RefinementRuleProvider { } // Scope propagation - scopePropagator.decrementTypeScope(typeInterpretation) + unitRulePropagator.decrementTypeScope(typeInterpretation) // Existence interpretation.newElements += newElement // Do recursive object creation for (newConstructor : recursiceObjectCreations) { - createObjectAction(nameNewElement, newConstructor, newElement, scopePropagator) + createObjectAction(nameNewElement, newConstructor, newElement, unitRulePropagator) } return newElement } - protected def boolean createRelationLinkAction(DefinedElement src, DefinedElement trg, - PartialRelationInterpretation relationInterpretation) { + protected def createRelationLinkAction(IPatternMatch match, UnitRulePropagator unitRulePropagator) { + // val problem = match.get(0) as LogicProblem + // val interpretation = match.get(1) as PartialInterpretation + val relationInterpretation = match.get(2) as PartialRelationInterpretation + val src = match.get(3) as DefinedElement + val trg = match.get(4) as DefinedElement + createRelationLinkAction(src, trg, relationInterpretation, unitRulePropagator) + } + + protected def void createRelationLinkAction(DefinedElement src, DefinedElement trg, + PartialRelationInterpretation relationInterpretation, UnitRulePropagator unitRulePropagator) { val link = createBinaryElementRelationLink => [it.param1 = src it.param2 = trg] relationInterpretation.relationlinks += link + unitRulePropagator.addedToRelation(relationInterpretation.interpretationOf) } - protected def boolean createRelationLinkWithInverse(DefinedElement src, DefinedElement trg, - PartialRelationInterpretation relationInterpretation, PartialRelationInterpretation inverseInterpretation) { + protected def void createRelationLinkWithInverse(IPatternMatch match, UnitRulePropagator unitRulePropagator) { + // val problem = match.get(0) as LogicProblem + // val interpretation = match.get(1) as PartialInterpretation + val relationInterpretation = match.get(2) as PartialRelationInterpretation + val inverseInterpretation = match.get(3) as PartialRelationInterpretation + val src = match.get(4) as DefinedElement + val trg = match.get(5) as DefinedElement + createRelationLinkWithInverse(src, trg, relationInterpretation, inverseInterpretation, unitRulePropagator) + } + + protected def void createRelationLinkWithInverse(DefinedElement src, DefinedElement trg, + PartialRelationInterpretation relationInterpretation, PartialRelationInterpretation inverseInterpretation, + UnitRulePropagator unitRulePropagator) { val link = createBinaryElementRelationLink => [it.param1 = src it.param2 = trg] relationInterpretation.relationlinks += link val inverseLink = createBinaryElementRelationLink => [it.param1 = trg it.param2 = src] inverseInterpretation.relationlinks += inverseLink + unitRulePropagator.addedToRelation(relationInterpretation.interpretationOf) + unitRulePropagator.addedToRelation(inverseInterpretation.interpretationOf) } - protected def flushQueryEngine(ScopePropagator scopePropagator) { - if (scopePropagator.queryEngineFlushRequiredBeforePropagation && queryEngine.updatePropagationDelayed) { - delayMessageDelivery.setBoolean(queryEngine, false) - queryEngine.getQueryBackend(ReteBackendFactory.INSTANCE).flushUpdates - delayMessageDelivery.setBoolean(queryEngine, true) + static class UnitRulePropagator { + val LogicProblem p + val PartialInterpretation i + val RefinementRuleProvider refinementRuleProvider + var AdvancedViatraQueryEngine queryEngine + var Field delayMessageDelivery + val ScopePropagator scopePropagator + val List> propagators + val ModelGenerationStatistics statistics + + new(LogicProblem p, PartialInterpretation i, RefinementRuleProvider refinementRuleProvider, + ScopePropagator scopePropagator, + Map, IQuerySpecification>> mustRelationPropagationQueries, + ModelGenerationStatistics statistics) { + this.p = p + this.i = i + this.refinementRuleProvider = refinementRuleProvider + queryEngine = ViatraQueryEngine.on(new EMFScope(i)) as AdvancedViatraQueryEngine + delayMessageDelivery = queryEngine.class.getDeclaredField("delayMessageDelivery") + delayMessageDelivery.accessible = true + this.scopePropagator = scopePropagator + propagators = ImmutableList.copyOf(mustRelationPropagationQueries.entrySet.map [ entry | + val matcher = queryEngine.getMatcher(entry.value) + getPropagator(entry.key.key, entry.key.value, matcher) + ]) + this.statistics = statistics + } + + def decrementTypeScope(PartialTypeInterpratation partialTypeInterpratation) { + scopePropagator.decrementTypeScope(partialTypeInterpratation) + } + + def addedToRelation(Relation r) { + scopePropagator.addedToRelation(r) + } + + def propagate() { + var boolean changed + do { + val scopeChanged = propagateScope() + val mustChanged = propagateMustRelations() + changed = scopeChanged || mustChanged + } while (changed) + } + + protected def flushQueryEngine() { + if (queryEngine.updatePropagationDelayed) { + delayMessageDelivery.setBoolean(queryEngine, false) + queryEngine.getQueryBackend(ReteBackendFactory.INSTANCE).flushUpdates + delayMessageDelivery.setBoolean(queryEngine, true) + } + } + + protected def propagateScope() { + if (scopePropagator.scopePropagationNeeded) { + if (scopePropagator.queryEngineFlushRequiredBeforePropagation) { + flushQueryEngine() + } + val propagatorStartTime = System.nanoTime + scopePropagator.propagateAllScopeConstraints() + statistics.addScopePropagationTime(System.nanoTime - propagatorStartTime) + true + } else { + false + } + } + + protected def propagateMustRelations() { + if (propagators.empty) { + return false + } + flushQueryEngine() + val propagatorStartTime = System.nanoTime + var changed = false + for (propagator : propagators) { + changed = propagator.propagate(p, i, refinementRuleProvider, this) || changed + } + statistics.addMustRelationPropagationTime(System.nanoTime - propagatorStartTime) + changed + } + + private static def getPropagator(Relation relation, Relation inverseRelation, + ViatraQueryMatcher matcher) { + if (inverseRelation === null) { + new MustRelationPropagator(matcher) + } else if (relation == inverseRelation) { + new MustRelationPropagatorWithSelfInverse(matcher) + } else { + new MustRelationPropagatorWithInverse(matcher) + } + } + + @FinalFieldsConstructor + private static abstract class AbstractMustRelationPropagator { + val ViatraQueryMatcher matcher + + def propagate(LogicProblem p, PartialInterpretation i, RefinementRuleProvider refinementRuleProvider, + UnitRulePropagator unitRulePropagator) { + val iterator = getIterator(p, i) + if (!iterator.hasNext) { + return false + } + iterate(iterator, refinementRuleProvider, unitRulePropagator) + true + } + + def iterate(Iterator iterator, RefinementRuleProvider refinementRuleProvider, + UnitRulePropagator unitRulePropagator) { + while (iterator.hasNext) { + doPropagate(iterator.next, refinementRuleProvider, unitRulePropagator) + } + } + + protected def getIterator(LogicProblem p, PartialInterpretation i) { + val partialMatch = matcher.newEmptyMatch + partialMatch.set(0, p) + partialMatch.set(1, i) + matcher.streamAllMatches(partialMatch).iterator + } + + protected def void doPropagate(T match, RefinementRuleProvider refinementRuleProvider, + UnitRulePropagator unitRulePropagator) + } + + private static class MustRelationPropagator extends AbstractMustRelationPropagator { + new(ViatraQueryMatcher matcher) { + super(matcher) + } + + override protected doPropagate(T match, RefinementRuleProvider refinementRuleProvider, + UnitRulePropagator unitRulePropagator) { + refinementRuleProvider.createRelationLinkAction(match, unitRulePropagator) + } + } + + private static class MustRelationPropagatorWithInverse extends AbstractMustRelationPropagator { + new(ViatraQueryMatcher matcher) { + super(matcher) + } + + override protected doPropagate(T match, RefinementRuleProvider refinementRuleProvider, + UnitRulePropagator unitRulePropagator) { + refinementRuleProvider.createRelationLinkWithInverse(match, unitRulePropagator) + } + } + + private static class MustRelationPropagatorWithSelfInverse extends MustRelationPropagatorWithInverse { + new(ViatraQueryMatcher matcher) { + super(matcher) + } + + override iterate(Iterator iterator, RefinementRuleProvider refinementRuleProvider, + UnitRulePropagator unitRulePropagator) { + val pairs = newHashSet + while (iterator.hasNext) { + val match = iterator.next + val src = match.get(4) as DefinedElement + val trg = match.get(5) as DefinedElement + if (!pairs.contains(trg -> src)) { + pairs.add(src -> trg) + doPropagate(match, refinementRuleProvider, unitRulePropagator) + } + } + } } } } 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 67d25208..8e05665c 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 @@ -228,6 +228,10 @@ class ViatraReasoner extends LogicReasoner { it.name = "ScopePropagationTime" it.value = (method.statistics.scopePropagationTime / 1000000) as int ] + it.entries += createIntStatisticEntry => [ + it.name = "MustRelationPropagationTime" + it.value = (method.statistics.mustRelationPropagationTime / 1000000) as int + ] it.entries += createIntStatisticEntry => [ it.name = "TypeAnalysisTime" it.value = (method.statistics.preliminaryTypeAnalisisTime / 1000000) as int 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 a2de1abc..4800f71d 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 @@ -307,7 +307,6 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { public List times = new LinkedList(); private void saveTimes() { - long statecoderTime = ((NeighbourhoodBasedPartialInterpretationStateCoder)this.context.getStateCoder()).getStatecoderRuntime()/1000000; long forwardTime = context.getDesignSpaceManager().getForwardTime()/1000000; long backtrackingTime = context.getDesignSpaceManager().getBacktrackingTime()/1000000; long activationSelection = this.activationSelector.getRuntime()/1000000; @@ -317,8 +316,7 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { long numericalSolverSolving = this.numericSolver.getSolverSolvingProblem()/1000000; long numericalSolverInterpreting = this.numericSolver.getSolverSolution()/1000000; this.times.add( - "(TransformationExecutionTime"+method.getStatistics().transformationExecutionTime/1000000+ - "|StateCoderTime:"+statecoderTime+ + "(TransformationExecutionTime"+method.getStatistics().transformationExecutionTime/1000000+ "|ForwardTime:"+forwardTime+ "|Backtrackingtime:"+backtrackingTime+ "|GlobalConstraintEvaluationTime:"+(globalConstraintEvaluationTime/1000000)+ diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/FileSystemHint.xtend b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/FileSystemHint.xtend index 8d6523b1..300f8b51 100644 --- a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/FileSystemHint.xtend +++ b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/FileSystemHint.xtend @@ -4,6 +4,8 @@ import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeExpressionBuilderFactory import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternGenerator +import java.util.Map +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery class FileSystemHint extends Ecore2LogicTraceBasedHint { static val REMAINING_CONTENTS_ROOT = "hint_root" @@ -12,7 +14,7 @@ class FileSystemHint extends Ecore2LogicTraceBasedHint { super(ecore2Logic, trace) } - override getAdditionalPatterns(PatternGenerator it) ''' + override getAdditionalPatterns(PatternGenerator it, Map fqnToPQuery) ''' pattern «REMAINING_CONTENTS_ROOT»(problem:LogicProblem, interpretation:PartialInterpretation, remainingContents:java Integer) { find interpretation(problem, interpretation); remainingContents == sum find remainingContents_root_reference_Dir_helper(problem, interpretation, _, #_) diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SGraphHint.xtend b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SGraphHint.xtend index 97ce4ee6..9a84f777 100644 --- a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SGraphHint.xtend +++ b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SGraphHint.xtend @@ -4,13 +4,15 @@ import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeExpressionBuilderFactory import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternGenerator +import java.util.Map +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery class SGraphHint extends Ecore2LogicTraceBasedHint { new(Ecore2Logic ecore2Logic, Ecore2Logic_Trace trace) { super(ecore2Logic, trace) } - override getAdditionalPatterns(extension PatternGenerator patternGenerator) { + override getAdditionalPatterns(extension PatternGenerator patternGenerator, Map fqnToPQuery) { "" } diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SatelliteHint.xtend b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SatelliteHint.xtend index ef5b779e..28954d60 100644 --- a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SatelliteHint.xtend +++ b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SatelliteHint.xtend @@ -5,6 +5,8 @@ import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeExpressionBuilderFactory import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternGenerator +import java.util.Map +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery class SatelliteHint extends Ecore2LogicTraceBasedHint { static val INTERFEROMETY_PAYLOAD = "hint_interferometryPayload" @@ -14,7 +16,7 @@ class SatelliteHint extends Ecore2LogicTraceBasedHint { super(ecore2Logic, trace) } - override getAdditionalPatterns(PatternGenerator it) ''' + override getAdditionalPatterns(PatternGenerator it, Map fqnToPQuery) ''' pattern «INTERFEROMETY_PAYLOAD»(problem:LogicProblem, interpretation:PartialInterpretation, object:DefinedElement) { find interpretation(problem, interpretation); find mustExist(problem, interpretation, object); diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SimpleRun.xtend b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SimpleRun.xtend index b65826ad..5e2d0920 100644 --- a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SimpleRun.xtend +++ b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SimpleRun.xtend @@ -1,9 +1,8 @@ package hu.bme.mit.inf.dslreasoner.run import functionalarchitecture.FunctionalarchitecturePackage +import hu.bme.mit.inf.dslreasoner.domains.alloyexamples.Filesystem.Model import hu.bme.mit.inf.dslreasoner.domains.transima.fam.FamPatterns -import hu.bme.mit.inf.dslreasoner.domains.transima.fam.Model -import hu.bme.mit.inf.dslreasoner.domains.transima.fam.Type import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2LogicConfiguration import hu.bme.mit.inf.dslreasoner.ecore2logic.EcoreMetamodelDescriptor @@ -15,7 +14,6 @@ import hu.bme.mit.inf.dslreasoner.logic2ecore.Logic2Ecore import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2Logic import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2LogicConfiguration import hu.bme.mit.inf.dslreasoner.viatra2logic.ViatraQuerySetDescriptor -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic.InstanceModel2Logic import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretation2Gml @@ -121,8 +119,6 @@ class SimpleRun { val patterns = i.specifications.toList val wfPatterns = patterns.filter[it.allAnnotations.exists[it.name== "Constraint"]].toSet val derivedFeatures = new LinkedHashMap - derivedFeatures.put(Type.instance,metamodel.attributes.filter[it.name == "type"].head) - derivedFeatures.put(Model.instance,metamodel.references.filter[it.name == "model"].head) val res = new ViatraQuerySetDescriptor( patterns, wfPatterns, -- cgit v1.2.3-70-g09d2 From f06427cd7375551582461f91b3458339a8227f9b Mon Sep 17 00:00:00 2001 From: Kristóf Marussy Date: Mon, 2 Nov 2020 02:02:40 +0100 Subject: Optimizing generator with linear objective functions --- .../.ApplicationConfigurationIdeModule.xtendbin | Bin 1700 -> 1700 bytes .../ide/.ApplicationConfigurationIdeSetup.xtendbin | Bin 2525 -> 2525 bytes .../.SolverSemanticHighlightCalculator.xtendbin | Bin 5333 -> 5333 bytes .../.SolverSemanticTextAttributeProvider.xtendbin | Bin 4902 -> 4902 bytes .../solver/language/ui/syntaxcoloring/.gitignore | 4 + .../validation/.SolverLanguageValidator.xtendbin | Bin 1716 -> 1716 bytes .../viatra/solver/language/validation/.gitignore | 2 + ....SolverLanguageTokenDefInjectingParser.xtendbin | Bin 2741 -> 2741 bytes .../viatra/solver/language/parser/antlr/.gitignore | 2 + ...nguageSyntheticTokenSyntacticSequencer.xtendbin | Bin 2757 -> 2757 bytes .../viatra/solver/language/serializer/.gitignore | 2 + .../META-INF/MANIFEST.MF | 3 +- Domains/ca.mcgill.rtgmrt.example.modes3/plugin.xml | 18 + .../src/modes3/queries/Modes3Queries.vql | 197 ++++- .../src/modes3/run/CloseTrainsObjectiveHint.xtend | 201 +++++ .../src/modes3/run/EndOfSidingObjectiveHint.xtend | 139 ++++ .../run/MisalignedTurnoutObjectiveHint.xtend | 140 ++++ .../src/modes3/run/Modes3ModelGenerator.xtend | 189 ++++- .../modes3/run/TrainLocationsObjectiveHint.xtend | 85 +++ .../vql-gen/modes3/queries/.gitignore | 45 ++ .../vql-gen/modes3/queries/EndOfSiding_step_2.java | 564 ++++++++++++++ .../vql-gen/modes3/queries/EndOfSiding_step_3.java | 717 +++++++++++++++++ .../vql-gen/modes3/queries/EndOfSiding_step_4.java | 847 +++++++++++++++++++++ .../vql-gen/modes3/queries/EndOfSiding_step_5.java | 841 ++++++++++++++++++++ .../vql-gen/modes3/queries/Modes3Queries.java | 198 +++++ .../modes3/queries/MultipleConnectedTo.java | 565 ++++++++++++++ .../modes3/queries/TooManyInputsOfSegment.java | 12 - .../modes3/queries/TrainLocations_step_2.java | 564 ++++++++++++++ .../modes3/queries/TrainLocations_step_3.java | 713 +++++++++++++++++ .../modes3/run/.CloseTrainsObjectiveHint.xtendbin | Bin 0 -> 8218 bytes .../modes3/run/.EndOfSidingObjectiveHint.xtendbin | Bin 0 -> 7190 bytes .../run/.MisalignedTurnoutObjectiveHint.xtendbin | Bin 0 -> 7395 bytes .../modes3/run/.Modes3ModelGenerator.xtendbin | Bin 15038 -> 18637 bytes .../modes3/run/.Modes3TypeScopeHint.xtendbin | Bin 7179 -> 6927 bytes .../run/.Modes3UnitPropagationGenerator.xtendbin | Bin 11735 -> 11284 bytes .../run/.TrainLocationsObjectiveHint.xtendbin | Bin 0 -> 6269 bytes .../xtend-gen/modes3/run/.gitignore | 10 + .../modes3/run/CloseTrainsObjectiveHint.java | 279 +++++++ .../modes3/run/EndOfSidingObjectiveHint.java | 193 +++++ .../modes3/run/MisalignedTurnoutObjectiveHint.java | 195 +++++ .../xtend-gen/modes3/run/Modes3ModelGenerator.java | 305 ++++++-- .../modes3/run/TrainLocationsObjectiveHint.java | 117 +++ .../META-INF/MANIFEST.MF | 1 - .../META-INF/MANIFEST.MF | 3 +- .../ModelGenerationMethodProvider.xtend | 226 ------ .../logic2viatra/ModelGenerationStatistics.xtend | 47 ++ .../logic2viatra/TypeInferenceMethod.xtend | 44 ++ .../ExtendedLinearExpressionBuilderFactory.xtend | 140 ++++ ...ExtendedPolyhedronScopePropagatorStrategy.xtend | 63 ++ .../cardinality/PolyhedronScopePropagator.xtend | 54 +- .../PolyhedronScopePropagatorStrategy.xtend | 92 +++ .../cardinality/PolyhedronSolver.xtend | 13 +- .../META-INF/MANIFEST.MF | 1 + ...odelGenerationMethodBasedGlobalConstraint.xtend | 1 - .../reasoner/ModelGenerationMethodProvider.xtend | 201 +++++ .../viatrasolver/reasoner/ViatraReasoner.xtend | 102 +-- .../reasoner/ViatraReasonerConfiguration.xtend | 4 +- .../dse/BestFirstStrategyForModelGeneration.java | 7 +- .../viatrasolver/reasoner/dse/NumericSolver.xtend | 2 +- .../dse/PartialModelAsLogicInterpretation.xtend | 3 +- .../viatrasolver/reasoner/dse/SolutionCopier.xtend | 8 +- .../reasoner/dse/ViatraReasonerSolutionSaver.xtend | 112 ++- .../optimization/CostElementMatchers.xtend | 137 ++++ .../reasoner/optimization/CostObjectiveHint.xtend | 68 ++ .../optimization/IObjectiveBoundsProvider.xtend | 8 + .../optimization/ThreeValuedCostObjective.xtend | 99 ++- .../ThreeValuedCostObjectiveProvider.xtend | 205 +++++ .../case.study.familyTree.run/bin/.gitignore | 1 + .../bin/queries/.gitignore | 4 + .../src-gen/queries/.gitignore | 4 + .../xtend-gen/converter/.UML2TGF.xtendbin | Bin 6885 -> 6885 bytes .../run/FileSystemInconsistencyDetector.xtend | 4 +- .../mit/inf/dslreasoner/run/MetamodelLoader.xtend | 2 +- .../run/SGraphInconsistencyDetector.xtend | 2 +- 74 files changed, 8297 insertions(+), 508 deletions(-) create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/CloseTrainsObjectiveHint.xtend create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/EndOfSidingObjectiveHint.xtend create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/MisalignedTurnoutObjectiveHint.xtend create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/TrainLocationsObjectiveHint.xtend create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_2.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_3.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_4.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_5.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/MultipleConnectedTo.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TrainLocations_step_2.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TrainLocations_step_3.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.CloseTrainsObjectiveHint.xtendbin create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.EndOfSidingObjectiveHint.xtendbin create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.MisalignedTurnoutObjectiveHint.xtendbin create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.TrainLocationsObjectiveHint.xtendbin create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/CloseTrainsObjectiveHint.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/EndOfSidingObjectiveHint.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/MisalignedTurnoutObjectiveHint.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/TrainLocationsObjectiveHint.java delete mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationMethodProvider.xtend create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationStatistics.xtend create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/TypeInferenceMethod.xtend create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ExtendedLinearExpressionBuilderFactory.xtend create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ExtendedPolyhedronScopePropagatorStrategy.xtend create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagatorStrategy.xtend create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ModelGenerationMethodProvider.xtend create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/CostElementMatchers.xtend create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/CostObjectiveHint.xtend create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/IObjectiveBoundsProvider.xtend create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/ThreeValuedCostObjectiveProvider.xtend create mode 100644 Tests/MODELS2020-CaseStudies/case.study.familyTree.run/bin/.gitignore (limited to 'Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbin') diff --git a/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeModule.xtendbin b/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeModule.xtendbin index e697e27d..81ae9937 100644 Binary files a/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeModule.xtendbin and b/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeModule.xtendbin differ diff --git a/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeSetup.xtendbin b/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeSetup.xtendbin index ddbe1979..10371590 100644 Binary files a/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeSetup.xtendbin and b/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeSetup.xtendbin differ diff --git a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticHighlightCalculator.xtendbin b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticHighlightCalculator.xtendbin index e1e21292..49fafab3 100644 Binary files a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticHighlightCalculator.xtendbin and b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticHighlightCalculator.xtendbin differ diff --git a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticTextAttributeProvider.xtendbin b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticTextAttributeProvider.xtendbin index b967ea7c..968ecef8 100644 Binary files a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticTextAttributeProvider.xtendbin and b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticTextAttributeProvider.xtendbin differ diff --git a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.gitignore b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.gitignore index 1764b462..61ce5bef 100644 --- a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.gitignore +++ b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.gitignore @@ -1,2 +1,6 @@ /.SolverSemanticHighlightCalculator.java._trace /.SolverSemanticTextAttributeProvider.java._trace +/.SolverSemanticHighlightCalculator.xtendbin +/.SolverSemanticTextAttributeProvider.xtendbin +/SolverSemanticHighlightCalculator.java +/SolverSemanticTextAttributeProvider.java diff --git a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.SolverLanguageValidator.xtendbin b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.SolverLanguageValidator.xtendbin index 2c271c98..afb2c8de 100644 Binary files a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.SolverLanguageValidator.xtendbin and b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.SolverLanguageValidator.xtendbin differ diff --git a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.gitignore b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.gitignore index f1cb387a..565d4b27 100644 --- a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.gitignore +++ b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.gitignore @@ -1 +1,3 @@ /.SolverLanguageValidator.java._trace +/.SolverLanguageValidator.xtendbin +/SolverLanguageValidator.java diff --git a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.SolverLanguageTokenDefInjectingParser.xtendbin b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.SolverLanguageTokenDefInjectingParser.xtendbin index 40f87b4c..c1d5cb5e 100644 Binary files a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.SolverLanguageTokenDefInjectingParser.xtendbin and b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.SolverLanguageTokenDefInjectingParser.xtendbin differ diff --git a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.gitignore b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.gitignore index 9cf14147..5fbb81c3 100644 --- a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.gitignore +++ b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.gitignore @@ -5,3 +5,5 @@ /.SolverLanguageSyntheticTokenParser.java._trace /.SolverLanguageTokenSource.java._trace /.SolverLanguageTokenDefInjectingParser.java._trace +/.SolverLanguageTokenDefInjectingParser.xtendbin +/SolverLanguageTokenDefInjectingParser.java diff --git a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.SolverLanguageSyntheticTokenSyntacticSequencer.xtendbin b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.SolverLanguageSyntheticTokenSyntacticSequencer.xtendbin index d0715440..7fb5f085 100644 Binary files a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.SolverLanguageSyntheticTokenSyntacticSequencer.xtendbin and b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.SolverLanguageSyntheticTokenSyntacticSequencer.xtendbin differ diff --git a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.gitignore b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.gitignore index b8132d70..1f04090d 100644 --- a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.gitignore +++ b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.gitignore @@ -1 +1,3 @@ /.SolverLanguageSyntheticTokenSyntacticSequencer.java._trace +/.SolverLanguageSyntheticTokenSyntacticSequencer.xtendbin +/SolverLanguageSyntheticTokenSyntacticSequencer.java diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/META-INF/MANIFEST.MF b/Domains/ca.mcgill.rtgmrt.example.modes3/META-INF/MANIFEST.MF index 96bd2113..8f900199 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/META-INF/MANIFEST.MF +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/META-INF/MANIFEST.MF @@ -28,7 +28,8 @@ Require-Bundle: org.eclipse.viatra.query.runtime, hu.bme.mit.inf.dslreasoner.ecore2logic;bundle-version="1.0.0", org.eclipse.emf.ecore.xmi;bundle-version="2.16.0", hu.bme.mit.inf.dslreasoner.visualisation;bundle-version="1.0.0", - org.eclipse.viatra.query.patternlanguage.emf;bundle-version="2.4.0" + org.eclipse.viatra.query.patternlanguage.emf;bundle-version="2.4.0", + org.eclipse.viatra.dse;bundle-version="0.24.0" Import-Package: org.apache.log4j Automatic-Module-Name: ca.mcgill.rtgmrt.example.modes3 Bundle-ActivationPolicy: lazy diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/plugin.xml b/Domains/ca.mcgill.rtgmrt.example.modes3/plugin.xml index a105a729..f7d32541 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/plugin.xml +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/plugin.xml @@ -21,6 +21,24 @@ + + + + + + + + + + + + + + + + + + diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql index b8841928..d22bdd8b 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql @@ -40,12 +40,6 @@ pattern output(S1 : Segment, S2 : Segment) { find turnoutOutput(S1, S2); } -//@Constraint(message = "noInputOfSegment", severity = "error", key = { S }) -//pattern noInputOfSegment(S : Segment) { -// neg find turnout(S); -// neg find output(_, S); -//} - @Constraint(message = "tooManyInputsOfSegment", severity = "error", key = { S }) pattern tooManyInputsOfSegment(S : SimpleSegment) { find output(I1, S); @@ -108,3 +102,194 @@ pattern reachable(S1 : Segment, S2 : Segment) { pattern unreachable(S1 : Segment, S2 : Segment) { neg find reachable(S1, S2); } + +// +// closeTrains +// + +pattern closeTrains_step_2(in train : Train) { +// frame->t1 = model->trains[i0]; +// frame->start = frame->t1->location; +// if(frame->start != 0){ +// ... +// } +// + OUTER FOR LOOP COUNTER INCREMENT + Train(train); +} + +pattern closeTrains_step_3(in train : Train, in start : Segment) { +// int loop_bound1 = frame->start->connected_to_count; +// for (int i1 = 0; i1 < loop_bound1; i1++) { LOOP COUNTER INCREMENT IS NOT INCLUDED HERE +// ... +// } + Train.location(train, start); +} + +pattern closeTrains_step_4(in train : Train, in start : Segment, in middle : Segment) { +// frame->middle = frame->start->connected_to[i1]; +// int loop_bound2 = frame->middle->connected_to_count; + +// for (int i2 = 0; i2 < loop_bound2; i2++) { LOOP COUNTER INCREMENT IS NOT INCLUDED HERE +// ... +// } +// + OUTER FOR LOOP COUNTER INCREMENT + Train.location(train, start); + Segment.connectedTo(start, middle); +} + +pattern closeTrains_step_5(in train : Train, in start : Segment, in middle : Segment, in end : Segment) { +// frame->end = frame->middle->connected_to[i2]; +// if (frame->start != frame->end) { +// ... +// } +// + OUTER FOR LOOP COUNTER INCREMENT + Train.location(train, start); + Segment.connectedTo(start, middle); + Segment.connectedTo(middle, end); +} + +pattern closeTrains_step_6(in train : Train, in start : Segment, in middle : Segment, in end : Segment) { +// frame->t2 = frame->end->train; +// if (frame->t2 != 0) { +// ... +// } + Train.location(train, start); + Segment.connectedTo(start, middle); + Segment.connectedTo(middle, end); + start != end; +} + +pattern closeTrains_step_7(in train : Train, in start : Segment, in middle : Segment, in end : Segment, in otherTrain : Train) { +// results->matches[match_cntr].start = frame->start; +// results->matches[match_cntr++].end = frame->end; + Train.location(train, start); + Segment.connectedTo(start, middle); + Segment.connectedTo(middle, end); + start != end; + Segment.occupiedBy(end, otherTrain); +} + +// +// trainLocations +// + +pattern trainLocations_step_2(in train : Train) { +// frame->train = model->trains[i0]; +// frame->location = frame->train->location; +// if (frame->location != NULL) { +// ... +// } + + Train(train); +} + +pattern trainLocations_step_3(in train : Train, in location : Segment) { +// results->matches[match_cntr].location = frame->location; +// results->matches[match_cntr++].train = frame->train; + Train(train); + Train.location(train, location); +} + +// +// misalignedTurnout +// + +pattern misalignedTurnout_step_2(in turnout : Turnout) { +// frame->turnout = model->turnouts[i0]; +// frame->location = frame->turnout->straight; +// if (frame->location != NULL) { +// ... +// } + Turnout(turnout); +} + +pattern misalignedTurnout_step_3(in turnout : Turnout, in location : Segment) { +// Segment *disconnected = ((Segment *)frame->turnout); +// if (disconnected->connected_to[0] != frame->location && +// disconnected->connected_to[1] != frame->location) { +// ... +// } + Turnout(turnout); + Turnout.straight(turnout, location); +} + +pattern misalignedTurnout_step_4(in turnout : Turnout, in location : Segment) { +// frame->train = frame->location->train; +// if (frame->train != NULL) { +// ... +// } + Turnout(turnout); + Turnout.straight(turnout, location); + neg find connectedSegmentsDirected(turnout, location); +} + +pattern misalignedTurnout_step_5(in turnout : Turnout, in location : Segment, in train : Train) { +// results->matches[match_cntr].start = frame->start; +// results->matches[match_cntr++].end = frame->end; + Turnout(turnout); + Turnout.straight(turnout, location); + neg find connectedSegmentsDirected(turnout, location); + Segment.occupiedBy(location, train); +} + +pattern connectedSegmentsDirected(s1 : Segment, s2 : Segment) { + Segment.connectedTo(s1, s2); +} + +// +// endOfSiding +// + +pattern endOfSiding_step_2(in train : Train) { +// frame->train = model->trains[i0]; +// frame->location = frame->train->location; +// if (frame->location != NULL) { +// ... +// } + + Train(train); +} + +pattern endOfSiding_step_3(in train : Train, in location : Segment) { +// int loop_bound1 = frame->location->connected_to_count; +// for (int i1 = 0; i1 < loop_bound1; i1++) { +// ... +// } + Train(train); + Train.location(train, location); +} + +pattern endOfSiding_step_4(in train : Train, in location : Segment, in end : Segment) { +// frame->end = frame->location->connected_to[i1]; +// if (frame->end != NULL && +// frame->end->connected_to[1] == frame->location && +// frame->end->connected_to[0] == NULL) { +// ... +// } +// if (frame->end != NULL && +// frame->end->connected_to[0] == frame->location && +// frame->end->connected_to[1] == NULL) { +// ... +// } + Train(train); + Train.location(train, location); + Segment.connectedTo(location, end); +} + +pattern endOfSiding_step_5(in train : Train, in location : Segment, in end : Segment) { +// results->matches[match_cntr].location = frame->location; +// results->matches[match_cntr++].train = frame->train; +// ...OR... +// results->matches[match_cntr].location = frame->location; +// results->matches[match_cntr++].train = frame->train; + Train(train); + Train.location(train, location); + Segment.connectedTo(location, end); + neg find multipleConnectedTo(end); +} + +pattern multipleConnectedTo(s : Segment) { + Segment.connectedTo(s, n1); + Segment.connectedTo(s, n2); + n1 != n2; +} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/CloseTrainsObjectiveHint.xtend b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/CloseTrainsObjectiveHint.xtend new file mode 100644 index 00000000..519a228a --- /dev/null +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/CloseTrainsObjectiveHint.xtend @@ -0,0 +1,201 @@ +package modes3.run + +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint +import java.util.Collection +import java.util.Map +import modes3.Modes3Package +import modes3.queries.CloseTrains_step_2 +import modes3.queries.CloseTrains_step_3 +import modes3.queries.CloseTrains_step_4 +import modes3.queries.CloseTrains_step_5 +import modes3.queries.CloseTrains_step_6 +import modes3.queries.CloseTrains_step_7 + +class CloseTrainsObjectiveHint extends CostObjectiveHint { + val Type segmentType + val Type trainType + + new(extension Ecore2Logic ecore2Logic, Ecore2Logic_Trace ecore2LogicTrace) { + extension val Modes3Package = Modes3Package.eINSTANCE + segmentType = ecore2LogicTrace.TypeofEClass(segment) + trainType = ecore2LogicTrace.TypeofEClass(train) + } + + override isExact() { + true + } + + override createPolyhedronExtensionOperator(Map costElementMatchers) { + val step2 = costElementMatchers.get(CloseTrains_step_2.instance.fullyQualifiedName) + val step3 = costElementMatchers.get(CloseTrains_step_3.instance.fullyQualifiedName) + val step4 = costElementMatchers.get(CloseTrains_step_4.instance.fullyQualifiedName) + val step5 = costElementMatchers.get(CloseTrains_step_5.instance.fullyQualifiedName) + val step6 = costElementMatchers.get(CloseTrains_step_6.instance.fullyQualifiedName) + val step7 = costElementMatchers.get(CloseTrains_step_7.instance.fullyQualifiedName); + + [ + val objectiveBuilder = createBuilder + + for (m : step2.matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step2.weight, dimension) + dimension.tightenLowerBound(0) + if (m.multi) { + createBuilder.add(1, dimension).add(-1, trainType).build.assertEqualsTo(0) + } else { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + + val step3Matches = step3.matches + for (m : step3Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step3.weight, dimension) + dimension.tightenLowerBound(0) + if (!m.multi) { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + for (pair : step3Matches.groupBy[step2.projectMayMatch(match, 2)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + multiplicityBuilder.add(-1, pair.key) + multiplicityBuilder.build.assertEqualsTo(0) + } + boundLimit(step3Matches, 2, trainType, 1) + boundLimit(step3Matches, 3, segmentType, 1) + + val step4Matches = step4.matches + for (m : step4Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step4.weight, dimension) + dimension.tightenLowerBound(0) + if (!m.multi) { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + for (pair : step4Matches.groupBy[step3.projectMayMatch(match, 2, 3)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + multiplicityBuilder.add(-2, pair.key) + multiplicityBuilder.build.tightenUpperBound(0) + } + boundLimit(step4Matches, 2, trainType, 2) + boundLimit(step4Matches, 3, segmentType, 2) + boundLimit(step4Matches, 4, segmentType, 2) + + val step5Matches = step5.matches + for (m : step5Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step5.weight, dimension) + dimension.tightenLowerBound(0) + if (!m.multi) { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + for (pair : step5Matches.groupBy[step4.projectMayMatch(match, 2, 3, 4)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + multiplicityBuilder.add(-2, pair.key) + multiplicityBuilder.build.tightenUpperBound(0) + } + boundLimit(step5Matches, 2, trainType, 4) + boundLimit(step5Matches, 3, segmentType, 4) + boundLimit(step5Matches, 4, segmentType, 4) + boundLimit(step5Matches, 5, segmentType, 4) + + val step6Matches = step6.matches + for (m : step6Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step6.weight, dimension) + dimension.tightenLowerBound(0) + if (m.multi) { + if (m.match.get(3) == m.match.get(5)) { + createBuilder.add(2, m.match).add(-1, step5.projectMayMatch(m.match, 2, 3, 4, 5)).build. + assertEqualsTo(0) + } else { + createBuilder.add(1, m.match).add(-1, step5.projectMayMatch(m.match, 2, 3, 4, 5)).build. + assertEqualsTo(0) + } + } else { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + boundLimit(step6Matches, 2, trainType, 2) + boundLimit(step6Matches, 3, segmentType, 2) + boundLimit(step6Matches, 4, segmentType, 2) + boundLimit(step6Matches, 5, segmentType, 2) + + val step7Matches = step7.matches + for (m : step7Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step7.weight, dimension) + dimension.tightenLowerBound(0) + if (!m.multi) { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + for (pair : step7Matches.groupBy[step6.projectMayMatch(match, 2, 3, 4, 5)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + multiplicityBuilder.add(-1, pair.key) + multiplicityBuilder.build.tightenUpperBound(0) + } + boundLimit(step7Matches, 2, trainType, 2) + boundLimit(step7Matches, 3, segmentType, 2) + boundLimit(step7Matches, 4, segmentType, 2) + boundLimit(step7Matches, 5, segmentType, 2) + boundLimit(step7Matches, 6, trainType, 2) + + objectiveBuilder.buildWithBounds + ] + } + + private static def boundLimit(extension ExtendedLinearExpressionBuilderFactory factory, + Collection matches, int index, Type type, int count) { + for (pair : matches.groupBy[match.get(index)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + if (CostElementMatchers.isMulti(pair.key)) { + multiplicityBuilder.add(-count, type) + multiplicityBuilder.build.tightenUpperBound(0) + } else { + multiplicityBuilder.build.tightenUpperBound(count) + } + } + } +} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/EndOfSidingObjectiveHint.xtend b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/EndOfSidingObjectiveHint.xtend new file mode 100644 index 00000000..f7e23a57 --- /dev/null +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/EndOfSidingObjectiveHint.xtend @@ -0,0 +1,139 @@ +package modes3.run + +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint +import java.util.Collection +import java.util.Map +import modes3.Modes3Package +import modes3.queries.EndOfSiding_step_2 +import modes3.queries.EndOfSiding_step_3 +import modes3.queries.EndOfSiding_step_4 +import modes3.queries.EndOfSiding_step_5 + +class EndOfSidingObjectiveHint extends CostObjectiveHint { + val Type segmentType + val Type trainType + + new(extension Ecore2Logic ecore2Logic, Ecore2Logic_Trace ecore2LogicTrace) { + extension val Modes3Package = Modes3Package.eINSTANCE + segmentType = ecore2LogicTrace.TypeofEClass(segment) + trainType = ecore2LogicTrace.TypeofEClass(train) + } + + override isExact() { + true +// false + } + + override createPolyhedronExtensionOperator(Map costElementMatchers) { + val step2 = costElementMatchers.get(EndOfSiding_step_2.instance.fullyQualifiedName) + val step3 = costElementMatchers.get(EndOfSiding_step_3.instance.fullyQualifiedName) + val step4 = costElementMatchers.get(EndOfSiding_step_4.instance.fullyQualifiedName) + val step5 = costElementMatchers.get(EndOfSiding_step_5.instance.fullyQualifiedName); + + [ + val objectiveBuilder = createBuilder + + for (m : step2.matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step2.weight, dimension) + dimension.tightenLowerBound(0) + if (m.multi) { + createBuilder.add(1, dimension).add(-1, trainType).build.assertEqualsTo(0) + } else { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + + val step3Matches = step3.matches + for (m : step3Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step3.weight, dimension) + dimension.tightenLowerBound(0) + if (!m.multi) { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + for (pair : step3Matches.groupBy[step2.projectMayMatch(match, 2)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + multiplicityBuilder.add(-1, pair.key) + multiplicityBuilder.build.assertEqualsTo(0) + } + boundLimit(step3Matches, 2, trainType, 1) + boundLimit(step3Matches, 3, segmentType, 1) + + val step4Matches = step4.matches + for (m : step4Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step4.weight, dimension) + dimension.tightenLowerBound(0) + if (!m.multi) { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + for (pair : step4Matches.groupBy[step3.projectMayMatch(match, 2, 3)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + multiplicityBuilder.add(-2, pair.key) + multiplicityBuilder.build.tightenUpperBound(0) + } + boundLimit(step4Matches, 2, trainType, 2) + boundLimit(step4Matches, 3, segmentType, 2) + boundLimit(step4Matches, 4, segmentType, 2) + + val step5Matches = step5.matches + for (m : step5Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step5.weight, dimension) + dimension.tightenLowerBound(0) + if (!m.multi) { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + createBuilder.add(1, m.match).add(-1, step4.projectMayMatch(m.match, 2, 3, 4)).build.tightenUpperBound(0) + } + boundLimit(step5Matches, 2, trainType, 1) + boundLimit(step5Matches, 3, segmentType, 2) + boundLimit(step5Matches, 4, segmentType, 1) + + objectiveBuilder.buildWithBounds + ] + } + + private static def boundLimit(extension ExtendedLinearExpressionBuilderFactory factory, + Collection matches, int index, Type type, int count) { + for (pair : matches.groupBy[match.get(index)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + if (CostElementMatchers.isMulti(pair.key)) { + multiplicityBuilder.add(-count, type) + multiplicityBuilder.build.tightenUpperBound(0) + } else { + multiplicityBuilder.build.tightenUpperBound(count) + } + } + } +} \ No newline at end of file diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/MisalignedTurnoutObjectiveHint.xtend b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/MisalignedTurnoutObjectiveHint.xtend new file mode 100644 index 00000000..cb014dea --- /dev/null +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/MisalignedTurnoutObjectiveHint.xtend @@ -0,0 +1,140 @@ +package modes3.run + +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint +import java.util.Collection +import java.util.Map +import modes3.Modes3Package +import modes3.queries.MisalignedTurnout_step_2 +import modes3.queries.MisalignedTurnout_step_3 +import modes3.queries.MisalignedTurnout_step_4 +import modes3.queries.MisalignedTurnout_step_5 + +class MisalignedTurnoutObjectiveHint extends CostObjectiveHint { + val Type segmentType + val Type turnoutType + val Type trainType + + new(extension Ecore2Logic ecore2Logic, Ecore2Logic_Trace ecore2LogicTrace) { + extension val Modes3Package = Modes3Package.eINSTANCE + segmentType = ecore2LogicTrace.TypeofEClass(segment) + turnoutType = ecore2LogicTrace.TypeofEClass(turnout) + trainType = ecore2LogicTrace.TypeofEClass(train) + } + + override isExact() { + true +// false + } + + override createPolyhedronExtensionOperator(Map costElementMatchers) { + val step2 = costElementMatchers.get(MisalignedTurnout_step_2.instance.fullyQualifiedName) + val step3 = costElementMatchers.get(MisalignedTurnout_step_3.instance.fullyQualifiedName) + val step4 = costElementMatchers.get(MisalignedTurnout_step_4.instance.fullyQualifiedName) + val step5 = costElementMatchers.get(MisalignedTurnout_step_5.instance.fullyQualifiedName); + + [ + val objectiveBuilder = createBuilder + + for (m : step2.matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step2.weight, dimension) + dimension.tightenLowerBound(0) + if (m.multi) { + createBuilder.add(1, dimension).add(-1, turnoutType).build.assertEqualsTo(0) + } else { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + + val step3Matches = step3.matches + for (m : step3Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step3.weight, dimension) + dimension.tightenLowerBound(0) + if (!m.multi) { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + for (pair : step3Matches.groupBy[step2.projectMayMatch(match, 2)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + multiplicityBuilder.add(-1, pair.key) + multiplicityBuilder.build.tightenUpperBound(0) + } + boundLimit(step3Matches, 2, turnoutType, 1) + boundLimit(step3Matches, 3, segmentType, 2) + + val step4Matches = step4.matches + for (m : step4Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step4.weight, dimension) + dimension.tightenLowerBound(0) + if (!m.multi) { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + createBuilder.add(1, m.match).add(-1, step3.projectMayMatch(m.match, 2, 3)).build.tightenUpperBound(0) + } + boundLimit(step4Matches, 2, turnoutType, 1) + boundLimit(step4Matches, 3, segmentType, 2) + + val step5Matches = step5.matches + for (m : step5Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step5.weight, dimension) + dimension.tightenLowerBound(0) + if (!m.multi) { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + for (pair : step5Matches.groupBy[step4.projectMayMatch(match, 2, 3)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + multiplicityBuilder.add(-1, pair.key) + multiplicityBuilder.build.tightenUpperBound(0) + } + boundLimit(step5Matches, 2, turnoutType, 1) + boundLimit(step5Matches, 3, segmentType, 2) + boundLimit(step5Matches, 4, trainType, 2) + + objectiveBuilder.buildWithBounds + ] + } + + private static def boundLimit(extension ExtendedLinearExpressionBuilderFactory factory, + Collection matches, int index, Type type, int count) { + for (pair : matches.groupBy[match.get(index)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + if (CostElementMatchers.isMulti(pair.key)) { + multiplicityBuilder.add(-count, type) + multiplicityBuilder.build.tightenUpperBound(0) + } else { + multiplicityBuilder.build.tightenUpperBound(count) + } + } + } +} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/Modes3ModelGenerator.xtend b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/Modes3ModelGenerator.xtend index fac7c496..613cb3e4 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/Modes3ModelGenerator.xtend +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/Modes3ModelGenerator.xtend @@ -5,6 +5,7 @@ import com.google.common.collect.ImmutableSet import hu.bme.mit.inf.dslreasoner.ecore2logic.EReferenceMapper_RelationsOverTypes_Trace import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2LogicConfiguration +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace import hu.bme.mit.inf.dslreasoner.ecore2logic.EcoreMetamodelDescriptor import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.Ecore2logicannotationsFactory import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.Ecore2logicannotationsPackage @@ -14,6 +15,7 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.LogiclanguagePackage import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeDefinition import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicproblemPackage import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult +import hu.bme.mit.inf.dslreasoner.logic2ecore.Logic2Ecore import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2Logic import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2LogicConfiguration import hu.bme.mit.inf.dslreasoner.viatra2logic.ViatraQuerySetDescriptor @@ -25,18 +27,38 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePro import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic.InstanceModel2Logic import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.BinaryElementRelationLink import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialComplexTypeInterpretation -import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationPackage import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretation2Gml +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.CostObjectiveConfiguration +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.CostObjectiveElementConfiguration import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.StateCoderStrategy import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasoner import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.PartialModelAsLogicInterpretation +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveKind +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveThreshold import hu.bme.mit.inf.dslreasoner.visualisation.pi2graphviz.GraphvizVisualiser import hu.bme.mit.inf.dslreasoner.workspace.FileSystemWorkspace import java.util.List import modes3.Modes3Factory import modes3.Modes3Package +import modes3.queries.CloseTrains_step_2 +import modes3.queries.CloseTrains_step_3 +import modes3.queries.CloseTrains_step_4 +import modes3.queries.CloseTrains_step_5 +import modes3.queries.CloseTrains_step_6 +import modes3.queries.CloseTrains_step_7 +import modes3.queries.EndOfSiding_step_2 +import modes3.queries.EndOfSiding_step_3 +import modes3.queries.EndOfSiding_step_4 +import modes3.queries.EndOfSiding_step_5 +import modes3.queries.MisalignedTurnout_step_2 +import modes3.queries.MisalignedTurnout_step_3 +import modes3.queries.MisalignedTurnout_step_4 +import modes3.queries.MisalignedTurnout_step_5 import modes3.queries.Modes3Queries +import modes3.queries.TrainLocations_step_2 +import modes3.queries.TrainLocations_step_3 import org.eclipse.emf.ecore.EClass import org.eclipse.emf.ecore.EObject import org.eclipse.emf.ecore.resource.Resource @@ -92,17 +114,21 @@ class Modes3ModelGenerator { minNewElements = modelSize maxNewElements = modelSize minNewElementsByType => [ -// put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.turnout), 5) +// put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.train), modelSize / 5) +// put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.turnout), modelSize / 5) +// put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.simpleSegment), 3 * modelSize / 5) ] maxNewElementsByType => [ - put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.train), 5) - put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.turnout), 5) + put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.train), modelSize / 5) + put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.turnout), modelSize / 5) + put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.simpleSegment), 3 * modelSize / 5) ] ] solutionScope => [ numberOfRequiredSolutions = 1 ] - scopeWeight = 5 + costObjectives += getObjective(ecore2Logic, metamodelLogic.trace) + scopeWeight = 6 nameNewElements = false typeInferenceMethod = TypeInferenceMethod.PreliminaryAnalysis stateCoderStrategy = StateCoderStrategy.PairwiseNeighbourhood @@ -121,47 +147,60 @@ class Modes3ModelGenerator { val solution = solver.solve(logic.output, config, workspace) if (solution instanceof ModelResult) { println("Saving generated solutions") - val representations = solution.representation - for (representationIndex : 0 ..< representations.size) { - val representation = representations.get(representationIndex) + val logic2Ecore = new Logic2Ecore(ecore2Logic) + val interpretations = solver.getInterpretations(solution) + for (representationIndex : 0 ..< interpretations.size) { + val interpretation = interpretations.get(representationIndex) val representationNumber = representationIndex + 1 - if (representation instanceof PartialInterpretation) { + if (interpretation instanceof PartialModelAsLogicInterpretation) { + val representation = interpretation.partialInterpretation workspace.writeModel(representation, '''solution«representationNumber».partialinterpretation''') val partialInterpretation2GML = new PartialInterpretation2Gml val gml = partialInterpretation2GML.transform(representation) workspace.writeText('''solution«representationNumber».gml''', gml) + val model = logic2Ecore.transformInterpretation(interpretation, metamodelLogic.trace) + val iterator = model.eAllContents + var int id = 0 + while (iterator.hasNext) { + val obj = iterator.next + val idFeature = obj.eClass.EAllAttributes.findFirst[name == 'id'] + if (idFeature !== null) { + obj.eSet(idFeature, id) + id++ + } + } + workspace.writeModel(model, '''solution«representationNumber».modes3''') if (representation.newElements.size < 160) { - if (representation instanceof PartialInterpretation) { - val rootType = (representation.problem.types.findFirst [ - name == "Modes3ModelRoot class DefinedPart" - ] as TypeDefinition) - val rootIntepretation = representation.partialtypeinterpratation.filter( - PartialComplexTypeInterpretation).findFirst [ - interpretationOf.name == "Modes3ModelRoot class" + val rootType = (representation.problem.types.findFirst [ + name == "Modes3ModelRoot class DefinedPart" + ] as TypeDefinition) + val rootIntepretation = representation.partialtypeinterpratation.filter( + PartialComplexTypeInterpretation).findFirst [ + interpretationOf.name == "Modes3ModelRoot class" + ] + rootIntepretation.elements.removeAll(rootType.elements) + representation.problem.elements.removeAll(rootType.elements) + for (relationInterpretation : representation.partialrelationinterpretation) { + relationInterpretation.relationlinks.removeIf [ link | + if (link instanceof BinaryElementRelationLink) { + rootType.elements.contains(link.param1) || + rootType.elements.contains(link.param2) + } else { + false + } ] - rootIntepretation.elements.removeAll(rootType.elements) - representation.problem.elements.removeAll(rootType.elements) - for (relationInterpretation : representation.partialrelationinterpretation) { - relationInterpretation.relationlinks.removeIf [ link | - if (link instanceof BinaryElementRelationLink) { - rootType.elements.contains(link.param1) || rootType.elements.contains(link.param2) - } else { - false - } - ] - } - rootType.elements.clear } + rootType.elements.clear val visualiser = new GraphvizVisualiser val visualisation = visualiser.visualiseConcretization(representation) visualisation.writeToFile(workspace, '''solution«representationNumber».png''') } } else { - workspace.writeText('''solution«representationNumber».txt''', representation.toString) + workspace.writeText('''solution«representationNumber».txt''', interpretation.toString) } } } else { - println("Failed to solver problem") + println("Failed to solve problem") val partial = logic.output workspace.writeModel(partial, "solution.partialinterpretation") } @@ -198,6 +237,94 @@ class Modes3ModelGenerator { ) } + def getObjective(Ecore2Logic ecore2Logic, Ecore2Logic_Trace ecore2LogicTrace) { + new CostObjectiveConfiguration => [ + switch (monitoringQuery) { + case closeTrains: { + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = CloseTrains_step_2.instance.fullyQualifiedName + weight = 14 + 53 + 11 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = CloseTrains_step_3.instance.fullyQualifiedName + weight = 21 + 14 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = CloseTrains_step_4.instance.fullyQualifiedName + weight = 14 + 44 + 14 + 9 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = CloseTrains_step_5.instance.fullyQualifiedName + weight = 14 + 41 + 11 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = CloseTrains_step_6.instance.fullyQualifiedName + weight = 27 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = CloseTrains_step_7.instance.fullyQualifiedName + weight = 48 + ] + hint = new CloseTrainsObjectiveHint(ecore2Logic, ecore2LogicTrace) + } + case trainLocations: { + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = TrainLocations_step_2.instance.fullyQualifiedName + weight = 14 + 53 + 11 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = TrainLocations_step_3.instance.fullyQualifiedName + weight = 48 + ] + hint = new TrainLocationsObjectiveHint(ecore2Logic, ecore2LogicTrace) + } + case misalignedTurnout: { + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = MisalignedTurnout_step_2.instance.fullyQualifiedName + weight = 14 + 53 + 11 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = MisalignedTurnout_step_3.instance.fullyQualifiedName + weight = 108 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = MisalignedTurnout_step_4.instance.fullyQualifiedName + weight = 27 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = MisalignedTurnout_step_5.instance.fullyQualifiedName + weight = 48 + ] + hint = new MisalignedTurnoutObjectiveHint(ecore2Logic, ecore2LogicTrace) + } + case endOfSiding: { + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = EndOfSiding_step_2.instance.fullyQualifiedName + weight = 14 + 53 + 11 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = EndOfSiding_step_3.instance.fullyQualifiedName + weight = 21 + 14 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = EndOfSiding_step_4.instance.fullyQualifiedName + weight = 14 + 35 + 21 + 15 + 14 + 21 + 15 + 11 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = EndOfSiding_step_5.instance.fullyQualifiedName + weight = 48 + ] + hint = new EndOfSidingObjectiveHint(ecore2Logic, ecore2LogicTrace) + } + default: + throw new IllegalArgumentException("Unknown monitoring query: " + monitoringQuery) + } + kind = ObjectiveKind.HIGHER_IS_BETTER + threshold = ObjectiveThreshold.NO_THRESHOLD + findExtremum = true + ] + } + def static init() { EMFPatternLanguageStandaloneSetup.doSetup ViatraQueryEngineOptions.setSystemDefaultBackends(ReteBackendFactory.INSTANCE, ReteBackendFactory.INSTANCE, @@ -223,6 +350,8 @@ class Modes3ModelGenerator { private static enum MonitoringQuery { closeTrains, + trainLocations, + endOfSiding, misalignedTurnout } } diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/TrainLocationsObjectiveHint.xtend b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/TrainLocationsObjectiveHint.xtend new file mode 100644 index 00000000..cc2d7925 --- /dev/null +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/TrainLocationsObjectiveHint.xtend @@ -0,0 +1,85 @@ +package modes3.run + +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint +import java.util.Collection +import java.util.Map +import modes3.Modes3Package +import modes3.queries.TrainLocations_step_2 +import modes3.queries.TrainLocations_step_3 + +class TrainLocationsObjectiveHint extends CostObjectiveHint { + val Type segmentType + val Type trainType + + new(extension Ecore2Logic ecore2Logic, Ecore2Logic_Trace ecore2LogicTrace) { + extension val Modes3Package = Modes3Package.eINSTANCE + segmentType = ecore2LogicTrace.TypeofEClass(segment) + trainType = ecore2LogicTrace.TypeofEClass(train) + } + + override isExact() { + true + } + + override createPolyhedronExtensionOperator(Map costElementMatchers) { + val step2 = costElementMatchers.get(TrainLocations_step_2.instance.fullyQualifiedName) + val step3 = costElementMatchers.get(TrainLocations_step_3.instance.fullyQualifiedName); + + [ + val objectiveBuilder = createBuilder + + for (m : step2.matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step2.weight, dimension) + dimension.tightenLowerBound(0) + if (m.multi) { + createBuilder.add(1, dimension).add(-1, trainType).build.assertEqualsTo(0) + } else { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + + val step3Matches = step3.matches + for (m : step3Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step3.weight, dimension) + dimension.tightenLowerBound(0) + if (!m.multi) { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + boundLimit(step3Matches, 2, trainType, 1) + boundLimit(step3Matches, 3, segmentType, 1) + + objectiveBuilder.buildWithBounds + ] + } + + private static def boundLimit(extension ExtendedLinearExpressionBuilderFactory factory, + Collection matches, int index, Type type, int count) { + for (pair : matches.groupBy[match.get(index)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + if (CostElementMatchers.isMulti(pair.key)) { + multiplicityBuilder.add(-count, type) + multiplicityBuilder.build.tightenUpperBound(0) + } else { + multiplicityBuilder.build.tightenUpperBound(count) + } + } + } +} \ No newline at end of file diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/.gitignore b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/.gitignore index b3e38571..a84c2906 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/.gitignore +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/.gitignore @@ -31,3 +31,48 @@ /.TooManyNonStraightInputsOfTurnout.java._trace /.InputsOfTurnout.java._trace /.TooFewInputsOfTurnout.java._trace +/.CloseTrains_step_2.java._trace +/.CloseTrains_step_3.java._trace +/.CloseTrains_step_4.java._trace +/.CloseTrains_step_5.java._trace +/.CloseTrains_step_6.java._trace +/.CloseTrains_step_7.java._trace +/.MisalignedTurnout_step_2.java._trace +/.MisalignedTurnout_step_3.java._trace +/.MisalignedTurnout_step_4.java._trace +/.MisalignedTurnout_step_5.java._trace +/.ConnectedSegmentsDirected.java._trace +/Adjacent.java +/CloseTrains_step_2.java +/CloseTrains_step_3.java +/CloseTrains_step_4.java +/CloseTrains_step_5.java +/CloseTrains_step_6.java +/CloseTrains_step_7.java +/ConnectedSegmentsDirected.java +/ConnectedTo.java +/ConnectedToNotSymmetric.java +/ConnectedToReflexive.java +/InputsOfTurnout.java +/MisalignedTurnout_step_2.java +/MisalignedTurnout_step_3.java +/MisalignedTurnout_step_4.java +/MisalignedTurnout_step_5.java +/Modes3Queries.java +/Output.java +/OutputReflexive.java +/Reachable.java +/TooFewInputsOfTurnout.java +/TooManyInputsOfSegment.java +/TooManyInputsOfTurnout.java +/TurnoutConnectedToBothOutputs.java +/TurnoutOutput.java +/TurnoutOutputsAreSame.java +/Unreachable.java +/.TrainLocations_step_2.java._trace +/.TrainLocations_step_3.java._trace +/.EndOfSiding_step_2.java._trace +/.EndOfSiding_step_3.java._trace +/.EndOfSiding_step_4.java._trace +/.EndOfSiding_step_5.java._trace +/.MultipleConnectedTo.java._trace diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_2.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_2.java new file mode 100644 index 00000000..a8f68dca --- /dev/null +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_2.java @@ -0,0 +1,564 @@ +/** + * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql + */ +package modes3.queries; + +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import modes3.Train; +import org.apache.log4j.Logger; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.viatra.query.runtime.api.IPatternMatch; +import org.eclipse.viatra.query.runtime.api.IQuerySpecification; +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification; +import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher; +import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch; +import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey; +import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint; +import org.eclipse.viatra.query.runtime.matchers.psystem.PBody; +import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples; +import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil; + +/** + * A pattern-specific query specification that can instantiate Matcher in a type-safe way. + * + *

Original source: + *

+ *         //
+ *         // endOfSiding
+ *         //
+ *         
+ *         pattern endOfSiding_step_2(in train : Train) {
+ *         //   frame-{@literal >}train = model-{@literal >}trains[i0];
+ *         //   frame-{@literal >}location = frame-{@literal >}train-{@literal >}location;
+ *         //   if (frame-{@literal >}location != NULL) {
+ *         //     ...
+ *         //   }
+ *         
+ *         	Train(train);
+ *         }
+ * 
+ * + * @see Matcher + * @see Match + * + */ +@SuppressWarnings("all") +public final class EndOfSiding_step_2 extends BaseGeneratedEMFQuerySpecification { + /** + * Pattern-specific match representation of the modes3.queries.endOfSiding_step_2 pattern, + * to be used in conjunction with {@link Matcher}. + * + *

Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned. + * Each instance is a (possibly partial) substitution of pattern parameters, + * usable to represent a match of the pattern in the result of a query, + * or to specify the bound (fixed) input parameters when issuing a query. + * + * @see Matcher + * + */ + public static abstract class Match extends BasePatternMatch { + private Train fTrain; + + private static List parameterNames = makeImmutableList("train"); + + private Match(final Train pTrain) { + this.fTrain = pTrain; + } + + @Override + public Object get(final String parameterName) { + switch(parameterName) { + case "train": return this.fTrain; + default: return null; + } + } + + @Override + public Object get(final int index) { + switch(index) { + case 0: return this.fTrain; + default: return null; + } + } + + public Train getTrain() { + return this.fTrain; + } + + @Override + public boolean set(final String parameterName, final Object newValue) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + if ("train".equals(parameterName) ) { + this.fTrain = (Train) newValue; + return true; + } + return false; + } + + public void setTrain(final Train pTrain) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fTrain = pTrain; + } + + @Override + public String patternName() { + return "modes3.queries.endOfSiding_step_2"; + } + + @Override + public List parameterNames() { + return EndOfSiding_step_2.Match.parameterNames; + } + + @Override + public Object[] toArray() { + return new Object[]{fTrain}; + } + + @Override + public EndOfSiding_step_2.Match toImmutable() { + return isMutable() ? newMatch(fTrain) : this; + } + + @Override + public String prettyPrint() { + StringBuilder result = new StringBuilder(); + result.append("\"train\"=" + prettyPrintValue(fTrain)); + return result.toString(); + } + + @Override + public int hashCode() { + return Objects.hash(fTrain); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) { + return false; + } + if ((obj instanceof EndOfSiding_step_2.Match)) { + EndOfSiding_step_2.Match other = (EndOfSiding_step_2.Match) obj; + return Objects.equals(fTrain, other.fTrain); + } else { + // this should be infrequent + if (!(obj instanceof IPatternMatch)) { + return false; + } + IPatternMatch otherSig = (IPatternMatch) obj; + return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray()); + } + } + + @Override + public EndOfSiding_step_2 specification() { + return EndOfSiding_step_2.instance(); + } + + /** + * Returns an empty, mutable match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @return the empty match. + * + */ + public static EndOfSiding_step_2.Match newEmptyMatch() { + return new Mutable(null); + } + + /** + * Returns a mutable (partial) match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return the new, mutable (partial) match object. + * + */ + public static EndOfSiding_step_2.Match newMutableMatch(final Train pTrain) { + return new Mutable(pTrain); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return the (partial) match object. + * + */ + public static EndOfSiding_step_2.Match newMatch(final Train pTrain) { + return new Immutable(pTrain); + } + + private static final class Mutable extends EndOfSiding_step_2.Match { + Mutable(final Train pTrain) { + super(pTrain); + } + + @Override + public boolean isMutable() { + return true; + } + } + + private static final class Immutable extends EndOfSiding_step_2.Match { + Immutable(final Train pTrain) { + super(pTrain); + } + + @Override + public boolean isMutable() { + return false; + } + } + } + + /** + * Generated pattern matcher API of the modes3.queries.endOfSiding_step_2 pattern, + * providing pattern-specific query methods. + * + *

Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)}, + * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}. + * + *

Matches of the pattern will be represented as {@link Match}. + * + *

Original source: + *

+   * //
+   * // endOfSiding
+   * //
+   * 
+   * pattern endOfSiding_step_2(in train : Train) {
+   * //   frame-{@literal >}train = model-{@literal >}trains[i0];
+   * //   frame-{@literal >}location = frame-{@literal >}train-{@literal >}location;
+   * //   if (frame-{@literal >}location != NULL) {
+   * //     ...
+   * //   }
+   * 
+   * 	Train(train);
+   * }
+   * 
+ * + * @see Match + * @see EndOfSiding_step_2 + * + */ + public static class Matcher extends BaseMatcher { + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + public static EndOfSiding_step_2.Matcher on(final ViatraQueryEngine engine) { + // check if matcher already exists + Matcher matcher = engine.getExistingMatcher(querySpecification()); + if (matcher == null) { + matcher = (Matcher)engine.getMatcher(querySpecification()); + } + return matcher; + } + + /** + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * @return an initialized matcher + * @noreference This method is for internal matcher initialization by the framework, do not call it manually. + * + */ + public static EndOfSiding_step_2.Matcher create() { + return new Matcher(); + } + + private static final int POSITION_TRAIN = 0; + + private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(EndOfSiding_step_2.Matcher.class); + + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + private Matcher() { + super(querySpecification()); + } + + /** + * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return matches represented as a Match object. + * + */ + public Collection getAllMatches(final Train pTrain) { + return rawStreamAllMatches(new Object[]{pTrain}).collect(Collectors.toSet()); + } + + /** + * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return a stream of matches represented as a Match object. + * + */ + public Stream streamAllMatches(final Train pTrain) { + return rawStreamAllMatches(new Object[]{pTrain}); + } + + /** + * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return a match represented as a Match object, or null if no match is found. + * + */ + public Optional getOneArbitraryMatch(final Train pTrain) { + return rawGetOneArbitraryMatch(new Object[]{pTrain}); + } + + /** + * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, + * under any possible substitution of the unspecified parameters (if any). + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return true if the input is a valid (partial) match of the pattern. + * + */ + public boolean hasMatch(final Train pTrain) { + return rawHasMatch(new Object[]{pTrain}); + } + + /** + * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return the number of pattern matches found. + * + */ + public int countMatches(final Train pTrain) { + return rawCountMatches(new Object[]{pTrain}); + } + + /** + * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param processor the action that will process the selected match. + * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked + * + */ + public boolean forOneArbitraryMatch(final Train pTrain, final Consumer processor) { + return rawForOneArbitraryMatch(new Object[]{pTrain}, processor); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return the (partial) match object. + * + */ + public EndOfSiding_step_2.Match newMatch(final Train pTrain) { + return EndOfSiding_step_2.Match.newMatch(pTrain); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOftrain(final Object[] parameters) { + return rawStreamAllValues(POSITION_TRAIN, parameters).map(Train.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()); + } + + @Override + protected EndOfSiding_step_2.Match tupleToMatch(final Tuple t) { + try { + return EndOfSiding_step_2.Match.newMatch((Train) t.get(POSITION_TRAIN)); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in tuple not properly typed!",e); + return null; + } + } + + @Override + protected EndOfSiding_step_2.Match arrayToMatch(final Object[] match) { + try { + return EndOfSiding_step_2.Match.newMatch((Train) match[POSITION_TRAIN]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + @Override + protected EndOfSiding_step_2.Match arrayToMatchMutable(final Object[] match) { + try { + return EndOfSiding_step_2.Match.newMutableMatch((Train) match[POSITION_TRAIN]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + /** + * @return the singleton instance of the query specification of this pattern + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static IQuerySpecification querySpecification() { + return EndOfSiding_step_2.instance(); + } + } + + private EndOfSiding_step_2() { + super(GeneratedPQuery.INSTANCE); + } + + /** + * @return the singleton instance of the query specification + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static EndOfSiding_step_2 instance() { + try{ + return LazyHolder.INSTANCE; + } catch (ExceptionInInitializerError err) { + throw processInitializerError(err); + } + } + + @Override + protected EndOfSiding_step_2.Matcher instantiate(final ViatraQueryEngine engine) { + return EndOfSiding_step_2.Matcher.on(engine); + } + + @Override + public EndOfSiding_step_2.Matcher instantiate() { + return EndOfSiding_step_2.Matcher.create(); + } + + @Override + public EndOfSiding_step_2.Match newEmptyMatch() { + return EndOfSiding_step_2.Match.newEmptyMatch(); + } + + @Override + public EndOfSiding_step_2.Match newMatch(final Object... parameters) { + return EndOfSiding_step_2.Match.newMatch((modes3.Train) parameters[0]); + } + + /** + * Inner class allowing the singleton instance of {@link EndOfSiding_step_2} to be created + * not at the class load time of the outer class, + * but rather at the first call to {@link EndOfSiding_step_2#instance()}. + * + *

This workaround is required e.g. to support recursion. + * + */ + private static class LazyHolder { + private static final EndOfSiding_step_2 INSTANCE = new EndOfSiding_step_2(); + + /** + * Statically initializes the query specification after the field {@link #INSTANCE} is assigned. + * This initialization order is required to support indirect recursion. + * + *

The static initializer is defined using a helper field to work around limitations of the code generator. + * + */ + private static final Object STATIC_INITIALIZER = ensureInitialized(); + + public static Object ensureInitialized() { + INSTANCE.ensureInitializedInternal(); + return null; + } + } + + private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { + private static final EndOfSiding_step_2.GeneratedPQuery INSTANCE = new GeneratedPQuery(); + + private final PParameter parameter_train = new PParameter("train", "modes3.Train", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Train")), PParameterDirection.INOUT); + + private final List parameters = Arrays.asList(parameter_train); + + private GeneratedPQuery() { + super(PVisibility.PUBLIC); + } + + @Override + public String getFullyQualifiedName() { + return "modes3.queries.endOfSiding_step_2"; + } + + @Override + public List getParameterNames() { + return Arrays.asList("train"); + } + + @Override + public List getParameters() { + return parameters; + } + + @Override + public Set doGetContainedBodies() { + setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED)); + Set bodies = new LinkedHashSet<>(); + { + PBody body = new PBody(this); + PVariable var_train = body.getOrCreateVariableByName("train"); + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + body.setSymbolicParameters(Arrays.asList( + new ExportedParameter(body, var_train, parameter_train) + )); + // // frame->train = model->trains[i0];// frame->location = frame->train->location;// if (frame->location != NULL) {// ...// } Train(train) + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + bodies.add(body); + } + return bodies; + } + } +} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_3.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_3.java new file mode 100644 index 00000000..16b28a9f --- /dev/null +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_3.java @@ -0,0 +1,717 @@ +/** + * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql + */ +package modes3.queries; + +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import modes3.Segment; +import modes3.Train; +import org.apache.log4j.Logger; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.viatra.query.runtime.api.IPatternMatch; +import org.eclipse.viatra.query.runtime.api.IQuerySpecification; +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification; +import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher; +import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch; +import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey; +import org.eclipse.viatra.query.runtime.emf.types.EStructuralFeatureInstancesKey; +import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint; +import org.eclipse.viatra.query.runtime.matchers.psystem.PBody; +import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Equality; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples; +import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil; + +/** + * A pattern-specific query specification that can instantiate Matcher in a type-safe way. + * + *

Original source: + *

+ *         pattern endOfSiding_step_3(in train : Train, in location : Segment) {
+ *         //     int loop_bound1 = frame-{@literal >}location-{@literal >}connected_to_count;
+ *         //     for (int i1 = 0; i1 {@literal <} loop_bound1; i1++) {
+ *         //       ...
+ *         //     }
+ *         	Train(train);
+ *             Train.location(train, location);
+ *         }
+ * 
+ * + * @see Matcher + * @see Match + * + */ +@SuppressWarnings("all") +public final class EndOfSiding_step_3 extends BaseGeneratedEMFQuerySpecification { + /** + * Pattern-specific match representation of the modes3.queries.endOfSiding_step_3 pattern, + * to be used in conjunction with {@link Matcher}. + * + *

Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned. + * Each instance is a (possibly partial) substitution of pattern parameters, + * usable to represent a match of the pattern in the result of a query, + * or to specify the bound (fixed) input parameters when issuing a query. + * + * @see Matcher + * + */ + public static abstract class Match extends BasePatternMatch { + private Train fTrain; + + private Segment fLocation; + + private static List parameterNames = makeImmutableList("train", "location"); + + private Match(final Train pTrain, final Segment pLocation) { + this.fTrain = pTrain; + this.fLocation = pLocation; + } + + @Override + public Object get(final String parameterName) { + switch(parameterName) { + case "train": return this.fTrain; + case "location": return this.fLocation; + default: return null; + } + } + + @Override + public Object get(final int index) { + switch(index) { + case 0: return this.fTrain; + case 1: return this.fLocation; + default: return null; + } + } + + public Train getTrain() { + return this.fTrain; + } + + public Segment getLocation() { + return this.fLocation; + } + + @Override + public boolean set(final String parameterName, final Object newValue) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + if ("train".equals(parameterName) ) { + this.fTrain = (Train) newValue; + return true; + } + if ("location".equals(parameterName) ) { + this.fLocation = (Segment) newValue; + return true; + } + return false; + } + + public void setTrain(final Train pTrain) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fTrain = pTrain; + } + + public void setLocation(final Segment pLocation) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fLocation = pLocation; + } + + @Override + public String patternName() { + return "modes3.queries.endOfSiding_step_3"; + } + + @Override + public List parameterNames() { + return EndOfSiding_step_3.Match.parameterNames; + } + + @Override + public Object[] toArray() { + return new Object[]{fTrain, fLocation}; + } + + @Override + public EndOfSiding_step_3.Match toImmutable() { + return isMutable() ? newMatch(fTrain, fLocation) : this; + } + + @Override + public String prettyPrint() { + StringBuilder result = new StringBuilder(); + result.append("\"train\"=" + prettyPrintValue(fTrain) + ", "); + result.append("\"location\"=" + prettyPrintValue(fLocation)); + return result.toString(); + } + + @Override + public int hashCode() { + return Objects.hash(fTrain, fLocation); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) { + return false; + } + if ((obj instanceof EndOfSiding_step_3.Match)) { + EndOfSiding_step_3.Match other = (EndOfSiding_step_3.Match) obj; + return Objects.equals(fTrain, other.fTrain) && Objects.equals(fLocation, other.fLocation); + } else { + // this should be infrequent + if (!(obj instanceof IPatternMatch)) { + return false; + } + IPatternMatch otherSig = (IPatternMatch) obj; + return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray()); + } + } + + @Override + public EndOfSiding_step_3 specification() { + return EndOfSiding_step_3.instance(); + } + + /** + * Returns an empty, mutable match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @return the empty match. + * + */ + public static EndOfSiding_step_3.Match newEmptyMatch() { + return new Mutable(null, null); + } + + /** + * Returns a mutable (partial) match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return the new, mutable (partial) match object. + * + */ + public static EndOfSiding_step_3.Match newMutableMatch(final Train pTrain, final Segment pLocation) { + return new Mutable(pTrain, pLocation); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return the (partial) match object. + * + */ + public static EndOfSiding_step_3.Match newMatch(final Train pTrain, final Segment pLocation) { + return new Immutable(pTrain, pLocation); + } + + private static final class Mutable extends EndOfSiding_step_3.Match { + Mutable(final Train pTrain, final Segment pLocation) { + super(pTrain, pLocation); + } + + @Override + public boolean isMutable() { + return true; + } + } + + private static final class Immutable extends EndOfSiding_step_3.Match { + Immutable(final Train pTrain, final Segment pLocation) { + super(pTrain, pLocation); + } + + @Override + public boolean isMutable() { + return false; + } + } + } + + /** + * Generated pattern matcher API of the modes3.queries.endOfSiding_step_3 pattern, + * providing pattern-specific query methods. + * + *

Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)}, + * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}. + * + *

Matches of the pattern will be represented as {@link Match}. + * + *

Original source: + *

+   * pattern endOfSiding_step_3(in train : Train, in location : Segment) {
+   * //     int loop_bound1 = frame-{@literal >}location-{@literal >}connected_to_count;
+   * //     for (int i1 = 0; i1 {@literal <} loop_bound1; i1++) {
+   * //       ...
+   * //     }
+   * 	Train(train);
+   *     Train.location(train, location);
+   * }
+   * 
+ * + * @see Match + * @see EndOfSiding_step_3 + * + */ + public static class Matcher extends BaseMatcher { + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + public static EndOfSiding_step_3.Matcher on(final ViatraQueryEngine engine) { + // check if matcher already exists + Matcher matcher = engine.getExistingMatcher(querySpecification()); + if (matcher == null) { + matcher = (Matcher)engine.getMatcher(querySpecification()); + } + return matcher; + } + + /** + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * @return an initialized matcher + * @noreference This method is for internal matcher initialization by the framework, do not call it manually. + * + */ + public static EndOfSiding_step_3.Matcher create() { + return new Matcher(); + } + + private static final int POSITION_TRAIN = 0; + + private static final int POSITION_LOCATION = 1; + + private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(EndOfSiding_step_3.Matcher.class); + + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + private Matcher() { + super(querySpecification()); + } + + /** + * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return matches represented as a Match object. + * + */ + public Collection getAllMatches(final Train pTrain, final Segment pLocation) { + return rawStreamAllMatches(new Object[]{pTrain, pLocation}).collect(Collectors.toSet()); + } + + /** + * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return a stream of matches represented as a Match object. + * + */ + public Stream streamAllMatches(final Train pTrain, final Segment pLocation) { + return rawStreamAllMatches(new Object[]{pTrain, pLocation}); + } + + /** + * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return a match represented as a Match object, or null if no match is found. + * + */ + public Optional getOneArbitraryMatch(final Train pTrain, final Segment pLocation) { + return rawGetOneArbitraryMatch(new Object[]{pTrain, pLocation}); + } + + /** + * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, + * under any possible substitution of the unspecified parameters (if any). + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return true if the input is a valid (partial) match of the pattern. + * + */ + public boolean hasMatch(final Train pTrain, final Segment pLocation) { + return rawHasMatch(new Object[]{pTrain, pLocation}); + } + + /** + * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return the number of pattern matches found. + * + */ + public int countMatches(final Train pTrain, final Segment pLocation) { + return rawCountMatches(new Object[]{pTrain, pLocation}); + } + + /** + * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param processor the action that will process the selected match. + * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked + * + */ + public boolean forOneArbitraryMatch(final Train pTrain, final Segment pLocation, final Consumer processor) { + return rawForOneArbitraryMatch(new Object[]{pTrain, pLocation}, processor); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return the (partial) match object. + * + */ + public EndOfSiding_step_3.Match newMatch(final Train pTrain, final Segment pLocation) { + return EndOfSiding_step_3.Match.newMatch(pTrain, pLocation); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOftrain(final Object[] parameters) { + return rawStreamAllValues(POSITION_TRAIN, parameters).map(Train.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()); + } + + /** + * Retrieve the set of values that occur in matches for train. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain(final EndOfSiding_step_3.Match partialMatch) { + return rawStreamAllValuesOftrain(partialMatch.toArray()); + } + + /** + * Retrieve the set of values that occur in matches for train. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain(final Segment pLocation) { + return rawStreamAllValuesOftrain(new Object[]{null, pLocation}); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain(final EndOfSiding_step_3.Match partialMatch) { + return rawStreamAllValuesOftrain(partialMatch.toArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain(final Segment pLocation) { + return rawStreamAllValuesOftrain(new Object[]{null, pLocation}).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOflocation(final Object[] parameters) { + return rawStreamAllValues(POSITION_LOCATION, parameters).map(Segment.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation() { + return rawStreamAllValuesOflocation(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation() { + return rawStreamAllValuesOflocation(emptyArray()); + } + + /** + * Retrieve the set of values that occur in matches for location. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation(final EndOfSiding_step_3.Match partialMatch) { + return rawStreamAllValuesOflocation(partialMatch.toArray()); + } + + /** + * Retrieve the set of values that occur in matches for location. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation(final Train pTrain) { + return rawStreamAllValuesOflocation(new Object[]{pTrain, null}); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation(final EndOfSiding_step_3.Match partialMatch) { + return rawStreamAllValuesOflocation(partialMatch.toArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation(final Train pTrain) { + return rawStreamAllValuesOflocation(new Object[]{pTrain, null}).collect(Collectors.toSet()); + } + + @Override + protected EndOfSiding_step_3.Match tupleToMatch(final Tuple t) { + try { + return EndOfSiding_step_3.Match.newMatch((Train) t.get(POSITION_TRAIN), (Segment) t.get(POSITION_LOCATION)); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in tuple not properly typed!",e); + return null; + } + } + + @Override + protected EndOfSiding_step_3.Match arrayToMatch(final Object[] match) { + try { + return EndOfSiding_step_3.Match.newMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + @Override + protected EndOfSiding_step_3.Match arrayToMatchMutable(final Object[] match) { + try { + return EndOfSiding_step_3.Match.newMutableMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + /** + * @return the singleton instance of the query specification of this pattern + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static IQuerySpecification querySpecification() { + return EndOfSiding_step_3.instance(); + } + } + + private EndOfSiding_step_3() { + super(GeneratedPQuery.INSTANCE); + } + + /** + * @return the singleton instance of the query specification + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static EndOfSiding_step_3 instance() { + try{ + return LazyHolder.INSTANCE; + } catch (ExceptionInInitializerError err) { + throw processInitializerError(err); + } + } + + @Override + protected EndOfSiding_step_3.Matcher instantiate(final ViatraQueryEngine engine) { + return EndOfSiding_step_3.Matcher.on(engine); + } + + @Override + public EndOfSiding_step_3.Matcher instantiate() { + return EndOfSiding_step_3.Matcher.create(); + } + + @Override + public EndOfSiding_step_3.Match newEmptyMatch() { + return EndOfSiding_step_3.Match.newEmptyMatch(); + } + + @Override + public EndOfSiding_step_3.Match newMatch(final Object... parameters) { + return EndOfSiding_step_3.Match.newMatch((modes3.Train) parameters[0], (modes3.Segment) parameters[1]); + } + + /** + * Inner class allowing the singleton instance of {@link EndOfSiding_step_3} to be created + * not at the class load time of the outer class, + * but rather at the first call to {@link EndOfSiding_step_3#instance()}. + * + *

This workaround is required e.g. to support recursion. + * + */ + private static class LazyHolder { + private static final EndOfSiding_step_3 INSTANCE = new EndOfSiding_step_3(); + + /** + * Statically initializes the query specification after the field {@link #INSTANCE} is assigned. + * This initialization order is required to support indirect recursion. + * + *

The static initializer is defined using a helper field to work around limitations of the code generator. + * + */ + private static final Object STATIC_INITIALIZER = ensureInitialized(); + + public static Object ensureInitialized() { + INSTANCE.ensureInitializedInternal(); + return null; + } + } + + private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { + private static final EndOfSiding_step_3.GeneratedPQuery INSTANCE = new GeneratedPQuery(); + + private final PParameter parameter_train = new PParameter("train", "modes3.Train", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Train")), PParameterDirection.INOUT); + + private final PParameter parameter_location = new PParameter("location", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT); + + private final List parameters = Arrays.asList(parameter_train, parameter_location); + + private GeneratedPQuery() { + super(PVisibility.PUBLIC); + } + + @Override + public String getFullyQualifiedName() { + return "modes3.queries.endOfSiding_step_3"; + } + + @Override + public List getParameterNames() { + return Arrays.asList("train","location"); + } + + @Override + public List getParameters() { + return parameters; + } + + @Override + public Set doGetContainedBodies() { + setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED)); + Set bodies = new LinkedHashSet<>(); + { + PBody body = new PBody(this); + PVariable var_train = body.getOrCreateVariableByName("train"); + PVariable var_location = body.getOrCreateVariableByName("location"); + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + new TypeConstraint(body, Tuples.flatTupleOf(var_location), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + body.setSymbolicParameters(Arrays.asList( + new ExportedParameter(body, var_train, parameter_train), + new ExportedParameter(body, var_location, parameter_location) + )); + // // int loop_bound1 = frame->location->connected_to_count;// for (int i1 = 0; i1 < loop_bound1; i1++) {// ...// } Train(train) + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + // Train.location(train, location) + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + PVariable var__virtual_0_ = body.getOrCreateVariableByName(".virtual{0}"); + new TypeConstraint(body, Tuples.flatTupleOf(var_train, var__virtual_0_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train", "location"))); + new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_0_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + new Equality(body, var__virtual_0_, var_location); + bodies.add(body); + } + return bodies; + } + } +} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_4.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_4.java new file mode 100644 index 00000000..73df8514 --- /dev/null +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_4.java @@ -0,0 +1,847 @@ +/** + * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql + */ +package modes3.queries; + +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import modes3.Segment; +import modes3.Train; +import org.apache.log4j.Logger; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.viatra.query.runtime.api.IPatternMatch; +import org.eclipse.viatra.query.runtime.api.IQuerySpecification; +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification; +import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher; +import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch; +import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey; +import org.eclipse.viatra.query.runtime.emf.types.EStructuralFeatureInstancesKey; +import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint; +import org.eclipse.viatra.query.runtime.matchers.psystem.PBody; +import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Equality; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples; +import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil; + +/** + * A pattern-specific query specification that can instantiate Matcher in a type-safe way. + * + *

Original source: + *

+ *         pattern endOfSiding_step_4(in train : Train, in location : Segment, in end : Segment) {
+ *         //       frame-{@literal >}end = frame-{@literal >}location-{@literal >}connected_to[i1];
+ *         //       if (frame-{@literal >}end != NULL &&
+ *         //			 frame-{@literal >}end-{@literal >}connected_to[1] == frame-{@literal >}location &&
+ *         //           frame-{@literal >}end-{@literal >}connected_to[0] == NULL) {
+ *         //         ...
+ *         //       } 
+ *         //     	 if (frame-{@literal >}end != NULL &&
+ *         //			 frame-{@literal >}end-{@literal >}connected_to[0] == frame-{@literal >}location &&
+ *         //           frame-{@literal >}end-{@literal >}connected_to[1] == NULL) {
+ *         //         ...
+ *         //       }
+ *         	Train(train);
+ *             Train.location(train, location);
+ *             Segment.connectedTo(location, end);
+ *         }
+ * 
+ * + * @see Matcher + * @see Match + * + */ +@SuppressWarnings("all") +public final class EndOfSiding_step_4 extends BaseGeneratedEMFQuerySpecification { + /** + * Pattern-specific match representation of the modes3.queries.endOfSiding_step_4 pattern, + * to be used in conjunction with {@link Matcher}. + * + *

Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned. + * Each instance is a (possibly partial) substitution of pattern parameters, + * usable to represent a match of the pattern in the result of a query, + * or to specify the bound (fixed) input parameters when issuing a query. + * + * @see Matcher + * + */ + public static abstract class Match extends BasePatternMatch { + private Train fTrain; + + private Segment fLocation; + + private Segment fEnd; + + private static List parameterNames = makeImmutableList("train", "location", "end"); + + private Match(final Train pTrain, final Segment pLocation, final Segment pEnd) { + this.fTrain = pTrain; + this.fLocation = pLocation; + this.fEnd = pEnd; + } + + @Override + public Object get(final String parameterName) { + switch(parameterName) { + case "train": return this.fTrain; + case "location": return this.fLocation; + case "end": return this.fEnd; + default: return null; + } + } + + @Override + public Object get(final int index) { + switch(index) { + case 0: return this.fTrain; + case 1: return this.fLocation; + case 2: return this.fEnd; + default: return null; + } + } + + public Train getTrain() { + return this.fTrain; + } + + public Segment getLocation() { + return this.fLocation; + } + + public Segment getEnd() { + return this.fEnd; + } + + @Override + public boolean set(final String parameterName, final Object newValue) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + if ("train".equals(parameterName) ) { + this.fTrain = (Train) newValue; + return true; + } + if ("location".equals(parameterName) ) { + this.fLocation = (Segment) newValue; + return true; + } + if ("end".equals(parameterName) ) { + this.fEnd = (Segment) newValue; + return true; + } + return false; + } + + public void setTrain(final Train pTrain) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fTrain = pTrain; + } + + public void setLocation(final Segment pLocation) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fLocation = pLocation; + } + + public void setEnd(final Segment pEnd) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fEnd = pEnd; + } + + @Override + public String patternName() { + return "modes3.queries.endOfSiding_step_4"; + } + + @Override + public List parameterNames() { + return EndOfSiding_step_4.Match.parameterNames; + } + + @Override + public Object[] toArray() { + return new Object[]{fTrain, fLocation, fEnd}; + } + + @Override + public EndOfSiding_step_4.Match toImmutable() { + return isMutable() ? newMatch(fTrain, fLocation, fEnd) : this; + } + + @Override + public String prettyPrint() { + StringBuilder result = new StringBuilder(); + result.append("\"train\"=" + prettyPrintValue(fTrain) + ", "); + result.append("\"location\"=" + prettyPrintValue(fLocation) + ", "); + result.append("\"end\"=" + prettyPrintValue(fEnd)); + return result.toString(); + } + + @Override + public int hashCode() { + return Objects.hash(fTrain, fLocation, fEnd); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) { + return false; + } + if ((obj instanceof EndOfSiding_step_4.Match)) { + EndOfSiding_step_4.Match other = (EndOfSiding_step_4.Match) obj; + return Objects.equals(fTrain, other.fTrain) && Objects.equals(fLocation, other.fLocation) && Objects.equals(fEnd, other.fEnd); + } else { + // this should be infrequent + if (!(obj instanceof IPatternMatch)) { + return false; + } + IPatternMatch otherSig = (IPatternMatch) obj; + return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray()); + } + } + + @Override + public EndOfSiding_step_4 specification() { + return EndOfSiding_step_4.instance(); + } + + /** + * Returns an empty, mutable match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @return the empty match. + * + */ + public static EndOfSiding_step_4.Match newEmptyMatch() { + return new Mutable(null, null, null); + } + + /** + * Returns a mutable (partial) match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return the new, mutable (partial) match object. + * + */ + public static EndOfSiding_step_4.Match newMutableMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return new Mutable(pTrain, pLocation, pEnd); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return the (partial) match object. + * + */ + public static EndOfSiding_step_4.Match newMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return new Immutable(pTrain, pLocation, pEnd); + } + + private static final class Mutable extends EndOfSiding_step_4.Match { + Mutable(final Train pTrain, final Segment pLocation, final Segment pEnd) { + super(pTrain, pLocation, pEnd); + } + + @Override + public boolean isMutable() { + return true; + } + } + + private static final class Immutable extends EndOfSiding_step_4.Match { + Immutable(final Train pTrain, final Segment pLocation, final Segment pEnd) { + super(pTrain, pLocation, pEnd); + } + + @Override + public boolean isMutable() { + return false; + } + } + } + + /** + * Generated pattern matcher API of the modes3.queries.endOfSiding_step_4 pattern, + * providing pattern-specific query methods. + * + *

Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)}, + * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}. + * + *

Matches of the pattern will be represented as {@link Match}. + * + *

Original source: + *

+   * pattern endOfSiding_step_4(in train : Train, in location : Segment, in end : Segment) {
+   * //       frame-{@literal >}end = frame-{@literal >}location-{@literal >}connected_to[i1];
+   * //       if (frame-{@literal >}end != NULL &&
+   * //			 frame-{@literal >}end-{@literal >}connected_to[1] == frame-{@literal >}location &&
+   * //           frame-{@literal >}end-{@literal >}connected_to[0] == NULL) {
+   * //         ...
+   * //       } 
+   * //     	 if (frame-{@literal >}end != NULL &&
+   * //			 frame-{@literal >}end-{@literal >}connected_to[0] == frame-{@literal >}location &&
+   * //           frame-{@literal >}end-{@literal >}connected_to[1] == NULL) {
+   * //         ...
+   * //       }
+   * 	Train(train);
+   *     Train.location(train, location);
+   *     Segment.connectedTo(location, end);
+   * }
+   * 
+ * + * @see Match + * @see EndOfSiding_step_4 + * + */ + public static class Matcher extends BaseMatcher { + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + public static EndOfSiding_step_4.Matcher on(final ViatraQueryEngine engine) { + // check if matcher already exists + Matcher matcher = engine.getExistingMatcher(querySpecification()); + if (matcher == null) { + matcher = (Matcher)engine.getMatcher(querySpecification()); + } + return matcher; + } + + /** + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * @return an initialized matcher + * @noreference This method is for internal matcher initialization by the framework, do not call it manually. + * + */ + public static EndOfSiding_step_4.Matcher create() { + return new Matcher(); + } + + private static final int POSITION_TRAIN = 0; + + private static final int POSITION_LOCATION = 1; + + private static final int POSITION_END = 2; + + private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(EndOfSiding_step_4.Matcher.class); + + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + private Matcher() { + super(querySpecification()); + } + + /** + * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return matches represented as a Match object. + * + */ + public Collection getAllMatches(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return rawStreamAllMatches(new Object[]{pTrain, pLocation, pEnd}).collect(Collectors.toSet()); + } + + /** + * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return a stream of matches represented as a Match object. + * + */ + public Stream streamAllMatches(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return rawStreamAllMatches(new Object[]{pTrain, pLocation, pEnd}); + } + + /** + * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return a match represented as a Match object, or null if no match is found. + * + */ + public Optional getOneArbitraryMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return rawGetOneArbitraryMatch(new Object[]{pTrain, pLocation, pEnd}); + } + + /** + * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, + * under any possible substitution of the unspecified parameters (if any). + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return true if the input is a valid (partial) match of the pattern. + * + */ + public boolean hasMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return rawHasMatch(new Object[]{pTrain, pLocation, pEnd}); + } + + /** + * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return the number of pattern matches found. + * + */ + public int countMatches(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return rawCountMatches(new Object[]{pTrain, pLocation, pEnd}); + } + + /** + * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @param processor the action that will process the selected match. + * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked + * + */ + public boolean forOneArbitraryMatch(final Train pTrain, final Segment pLocation, final Segment pEnd, final Consumer processor) { + return rawForOneArbitraryMatch(new Object[]{pTrain, pLocation, pEnd}, processor); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return the (partial) match object. + * + */ + public EndOfSiding_step_4.Match newMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return EndOfSiding_step_4.Match.newMatch(pTrain, pLocation, pEnd); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOftrain(final Object[] parameters) { + return rawStreamAllValues(POSITION_TRAIN, parameters).map(Train.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()); + } + + /** + * Retrieve the set of values that occur in matches for train. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain(final EndOfSiding_step_4.Match partialMatch) { + return rawStreamAllValuesOftrain(partialMatch.toArray()); + } + + /** + * Retrieve the set of values that occur in matches for train. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain(final Segment pLocation, final Segment pEnd) { + return rawStreamAllValuesOftrain(new Object[]{null, pLocation, pEnd}); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain(final EndOfSiding_step_4.Match partialMatch) { + return rawStreamAllValuesOftrain(partialMatch.toArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain(final Segment pLocation, final Segment pEnd) { + return rawStreamAllValuesOftrain(new Object[]{null, pLocation, pEnd}).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOflocation(final Object[] parameters) { + return rawStreamAllValues(POSITION_LOCATION, parameters).map(Segment.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation() { + return rawStreamAllValuesOflocation(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation() { + return rawStreamAllValuesOflocation(emptyArray()); + } + + /** + * Retrieve the set of values that occur in matches for location. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation(final EndOfSiding_step_4.Match partialMatch) { + return rawStreamAllValuesOflocation(partialMatch.toArray()); + } + + /** + * Retrieve the set of values that occur in matches for location. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation(final Train pTrain, final Segment pEnd) { + return rawStreamAllValuesOflocation(new Object[]{pTrain, null, pEnd}); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation(final EndOfSiding_step_4.Match partialMatch) { + return rawStreamAllValuesOflocation(partialMatch.toArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation(final Train pTrain, final Segment pEnd) { + return rawStreamAllValuesOflocation(new Object[]{pTrain, null, pEnd}).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for end. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOfend(final Object[] parameters) { + return rawStreamAllValues(POSITION_END, parameters).map(Segment.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for end. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOfend() { + return rawStreamAllValuesOfend(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for end. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOfend() { + return rawStreamAllValuesOfend(emptyArray()); + } + + /** + * Retrieve the set of values that occur in matches for end. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOfend(final EndOfSiding_step_4.Match partialMatch) { + return rawStreamAllValuesOfend(partialMatch.toArray()); + } + + /** + * Retrieve the set of values that occur in matches for end. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOfend(final Train pTrain, final Segment pLocation) { + return rawStreamAllValuesOfend(new Object[]{pTrain, pLocation, null}); + } + + /** + * Retrieve the set of values that occur in matches for end. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOfend(final EndOfSiding_step_4.Match partialMatch) { + return rawStreamAllValuesOfend(partialMatch.toArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for end. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOfend(final Train pTrain, final Segment pLocation) { + return rawStreamAllValuesOfend(new Object[]{pTrain, pLocation, null}).collect(Collectors.toSet()); + } + + @Override + protected EndOfSiding_step_4.Match tupleToMatch(final Tuple t) { + try { + return EndOfSiding_step_4.Match.newMatch((Train) t.get(POSITION_TRAIN), (Segment) t.get(POSITION_LOCATION), (Segment) t.get(POSITION_END)); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in tuple not properly typed!",e); + return null; + } + } + + @Override + protected EndOfSiding_step_4.Match arrayToMatch(final Object[] match) { + try { + return EndOfSiding_step_4.Match.newMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION], (Segment) match[POSITION_END]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + @Override + protected EndOfSiding_step_4.Match arrayToMatchMutable(final Object[] match) { + try { + return EndOfSiding_step_4.Match.newMutableMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION], (Segment) match[POSITION_END]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + /** + * @return the singleton instance of the query specification of this pattern + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static IQuerySpecification querySpecification() { + return EndOfSiding_step_4.instance(); + } + } + + private EndOfSiding_step_4() { + super(GeneratedPQuery.INSTANCE); + } + + /** + * @return the singleton instance of the query specification + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static EndOfSiding_step_4 instance() { + try{ + return LazyHolder.INSTANCE; + } catch (ExceptionInInitializerError err) { + throw processInitializerError(err); + } + } + + @Override + protected EndOfSiding_step_4.Matcher instantiate(final ViatraQueryEngine engine) { + return EndOfSiding_step_4.Matcher.on(engine); + } + + @Override + public EndOfSiding_step_4.Matcher instantiate() { + return EndOfSiding_step_4.Matcher.create(); + } + + @Override + public EndOfSiding_step_4.Match newEmptyMatch() { + return EndOfSiding_step_4.Match.newEmptyMatch(); + } + + @Override + public EndOfSiding_step_4.Match newMatch(final Object... parameters) { + return EndOfSiding_step_4.Match.newMatch((modes3.Train) parameters[0], (modes3.Segment) parameters[1], (modes3.Segment) parameters[2]); + } + + /** + * Inner class allowing the singleton instance of {@link EndOfSiding_step_4} to be created + * not at the class load time of the outer class, + * but rather at the first call to {@link EndOfSiding_step_4#instance()}. + * + *

This workaround is required e.g. to support recursion. + * + */ + private static class LazyHolder { + private static final EndOfSiding_step_4 INSTANCE = new EndOfSiding_step_4(); + + /** + * Statically initializes the query specification after the field {@link #INSTANCE} is assigned. + * This initialization order is required to support indirect recursion. + * + *

The static initializer is defined using a helper field to work around limitations of the code generator. + * + */ + private static final Object STATIC_INITIALIZER = ensureInitialized(); + + public static Object ensureInitialized() { + INSTANCE.ensureInitializedInternal(); + return null; + } + } + + private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { + private static final EndOfSiding_step_4.GeneratedPQuery INSTANCE = new GeneratedPQuery(); + + private final PParameter parameter_train = new PParameter("train", "modes3.Train", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Train")), PParameterDirection.INOUT); + + private final PParameter parameter_location = new PParameter("location", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT); + + private final PParameter parameter_end = new PParameter("end", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT); + + private final List parameters = Arrays.asList(parameter_train, parameter_location, parameter_end); + + private GeneratedPQuery() { + super(PVisibility.PUBLIC); + } + + @Override + public String getFullyQualifiedName() { + return "modes3.queries.endOfSiding_step_4"; + } + + @Override + public List getParameterNames() { + return Arrays.asList("train","location","end"); + } + + @Override + public List getParameters() { + return parameters; + } + + @Override + public Set doGetContainedBodies() { + setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED)); + Set bodies = new LinkedHashSet<>(); + { + PBody body = new PBody(this); + PVariable var_train = body.getOrCreateVariableByName("train"); + PVariable var_location = body.getOrCreateVariableByName("location"); + PVariable var_end = body.getOrCreateVariableByName("end"); + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + new TypeConstraint(body, Tuples.flatTupleOf(var_location), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + new TypeConstraint(body, Tuples.flatTupleOf(var_end), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + body.setSymbolicParameters(Arrays.asList( + new ExportedParameter(body, var_train, parameter_train), + new ExportedParameter(body, var_location, parameter_location), + new ExportedParameter(body, var_end, parameter_end) + )); + // // frame->end = frame->location->connected_to[i1];// if (frame->end != NULL &&// frame->end->connected_to[1] == frame->location &&// frame->end->connected_to[0] == NULL) {// ...// } // if (frame->end != NULL &&// frame->end->connected_to[0] == frame->location &&// frame->end->connected_to[1] == NULL) {// ...// } Train(train) + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + // Train.location(train, location) + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + PVariable var__virtual_0_ = body.getOrCreateVariableByName(".virtual{0}"); + new TypeConstraint(body, Tuples.flatTupleOf(var_train, var__virtual_0_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train", "location"))); + new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_0_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + new Equality(body, var__virtual_0_, var_location); + // Segment.connectedTo(location, end) + new TypeConstraint(body, Tuples.flatTupleOf(var_location), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + PVariable var__virtual_1_ = body.getOrCreateVariableByName(".virtual{1}"); + new TypeConstraint(body, Tuples.flatTupleOf(var_location, var__virtual_1_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment", "connectedTo"))); + new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_1_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + new Equality(body, var__virtual_1_, var_end); + bodies.add(body); + } + return bodies; + } + } +} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_5.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_5.java new file mode 100644 index 00000000..48a2697d --- /dev/null +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_5.java @@ -0,0 +1,841 @@ +/** + * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql + */ +package modes3.queries; + +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import modes3.Segment; +import modes3.Train; +import modes3.queries.MultipleConnectedTo; +import org.apache.log4j.Logger; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.viatra.query.runtime.api.IPatternMatch; +import org.eclipse.viatra.query.runtime.api.IQuerySpecification; +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification; +import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher; +import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch; +import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey; +import org.eclipse.viatra.query.runtime.emf.types.EStructuralFeatureInstancesKey; +import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint; +import org.eclipse.viatra.query.runtime.matchers.psystem.PBody; +import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Equality; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.NegativePatternCall; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples; +import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil; + +/** + * A pattern-specific query specification that can instantiate Matcher in a type-safe way. + * + *

Original source: + *

+ *         pattern endOfSiding_step_5(in train : Train, in location : Segment, in end : Segment) {
+ *         //         results-{@literal >}matches[match_cntr].location = frame-{@literal >}location;
+ *         //         results-{@literal >}matches[match_cntr++].train = frame-{@literal >}train;
+ *         //         ...OR...
+ *         //         results-{@literal >}matches[match_cntr].location = frame-{@literal >}location;
+ *         //         results-{@literal >}matches[match_cntr++].train = frame-{@literal >}train;
+ *         	Train(train);
+ *             Train.location(train, location);
+ *             Segment.connectedTo(location, end);
+ *         	neg find multipleConnectedTo(end);
+ *         }
+ * 
+ * + * @see Matcher + * @see Match + * + */ +@SuppressWarnings("all") +public final class EndOfSiding_step_5 extends BaseGeneratedEMFQuerySpecification { + /** + * Pattern-specific match representation of the modes3.queries.endOfSiding_step_5 pattern, + * to be used in conjunction with {@link Matcher}. + * + *

Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned. + * Each instance is a (possibly partial) substitution of pattern parameters, + * usable to represent a match of the pattern in the result of a query, + * or to specify the bound (fixed) input parameters when issuing a query. + * + * @see Matcher + * + */ + public static abstract class Match extends BasePatternMatch { + private Train fTrain; + + private Segment fLocation; + + private Segment fEnd; + + private static List parameterNames = makeImmutableList("train", "location", "end"); + + private Match(final Train pTrain, final Segment pLocation, final Segment pEnd) { + this.fTrain = pTrain; + this.fLocation = pLocation; + this.fEnd = pEnd; + } + + @Override + public Object get(final String parameterName) { + switch(parameterName) { + case "train": return this.fTrain; + case "location": return this.fLocation; + case "end": return this.fEnd; + default: return null; + } + } + + @Override + public Object get(final int index) { + switch(index) { + case 0: return this.fTrain; + case 1: return this.fLocation; + case 2: return this.fEnd; + default: return null; + } + } + + public Train getTrain() { + return this.fTrain; + } + + public Segment getLocation() { + return this.fLocation; + } + + public Segment getEnd() { + return this.fEnd; + } + + @Override + public boolean set(final String parameterName, final Object newValue) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + if ("train".equals(parameterName) ) { + this.fTrain = (Train) newValue; + return true; + } + if ("location".equals(parameterName) ) { + this.fLocation = (Segment) newValue; + return true; + } + if ("end".equals(parameterName) ) { + this.fEnd = (Segment) newValue; + return true; + } + return false; + } + + public void setTrain(final Train pTrain) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fTrain = pTrain; + } + + public void setLocation(final Segment pLocation) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fLocation = pLocation; + } + + public void setEnd(final Segment pEnd) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fEnd = pEnd; + } + + @Override + public String patternName() { + return "modes3.queries.endOfSiding_step_5"; + } + + @Override + public List parameterNames() { + return EndOfSiding_step_5.Match.parameterNames; + } + + @Override + public Object[] toArray() { + return new Object[]{fTrain, fLocation, fEnd}; + } + + @Override + public EndOfSiding_step_5.Match toImmutable() { + return isMutable() ? newMatch(fTrain, fLocation, fEnd) : this; + } + + @Override + public String prettyPrint() { + StringBuilder result = new StringBuilder(); + result.append("\"train\"=" + prettyPrintValue(fTrain) + ", "); + result.append("\"location\"=" + prettyPrintValue(fLocation) + ", "); + result.append("\"end\"=" + prettyPrintValue(fEnd)); + return result.toString(); + } + + @Override + public int hashCode() { + return Objects.hash(fTrain, fLocation, fEnd); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) { + return false; + } + if ((obj instanceof EndOfSiding_step_5.Match)) { + EndOfSiding_step_5.Match other = (EndOfSiding_step_5.Match) obj; + return Objects.equals(fTrain, other.fTrain) && Objects.equals(fLocation, other.fLocation) && Objects.equals(fEnd, other.fEnd); + } else { + // this should be infrequent + if (!(obj instanceof IPatternMatch)) { + return false; + } + IPatternMatch otherSig = (IPatternMatch) obj; + return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray()); + } + } + + @Override + public EndOfSiding_step_5 specification() { + return EndOfSiding_step_5.instance(); + } + + /** + * Returns an empty, mutable match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @return the empty match. + * + */ + public static EndOfSiding_step_5.Match newEmptyMatch() { + return new Mutable(null, null, null); + } + + /** + * Returns a mutable (partial) match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return the new, mutable (partial) match object. + * + */ + public static EndOfSiding_step_5.Match newMutableMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return new Mutable(pTrain, pLocation, pEnd); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return the (partial) match object. + * + */ + public static EndOfSiding_step_5.Match newMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return new Immutable(pTrain, pLocation, pEnd); + } + + private static final class Mutable extends EndOfSiding_step_5.Match { + Mutable(final Train pTrain, final Segment pLocation, final Segment pEnd) { + super(pTrain, pLocation, pEnd); + } + + @Override + public boolean isMutable() { + return true; + } + } + + private static final class Immutable extends EndOfSiding_step_5.Match { + Immutable(final Train pTrain, final Segment pLocation, final Segment pEnd) { + super(pTrain, pLocation, pEnd); + } + + @Override + public boolean isMutable() { + return false; + } + } + } + + /** + * Generated pattern matcher API of the modes3.queries.endOfSiding_step_5 pattern, + * providing pattern-specific query methods. + * + *

Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)}, + * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}. + * + *

Matches of the pattern will be represented as {@link Match}. + * + *

Original source: + *

+   * pattern endOfSiding_step_5(in train : Train, in location : Segment, in end : Segment) {
+   * //         results-{@literal >}matches[match_cntr].location = frame-{@literal >}location;
+   * //         results-{@literal >}matches[match_cntr++].train = frame-{@literal >}train;
+   * //         ...OR...
+   * //         results-{@literal >}matches[match_cntr].location = frame-{@literal >}location;
+   * //         results-{@literal >}matches[match_cntr++].train = frame-{@literal >}train;
+   * 	Train(train);
+   *     Train.location(train, location);
+   *     Segment.connectedTo(location, end);
+   * 	neg find multipleConnectedTo(end);
+   * }
+   * 
+ * + * @see Match + * @see EndOfSiding_step_5 + * + */ + public static class Matcher extends BaseMatcher { + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + public static EndOfSiding_step_5.Matcher on(final ViatraQueryEngine engine) { + // check if matcher already exists + Matcher matcher = engine.getExistingMatcher(querySpecification()); + if (matcher == null) { + matcher = (Matcher)engine.getMatcher(querySpecification()); + } + return matcher; + } + + /** + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * @return an initialized matcher + * @noreference This method is for internal matcher initialization by the framework, do not call it manually. + * + */ + public static EndOfSiding_step_5.Matcher create() { + return new Matcher(); + } + + private static final int POSITION_TRAIN = 0; + + private static final int POSITION_LOCATION = 1; + + private static final int POSITION_END = 2; + + private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(EndOfSiding_step_5.Matcher.class); + + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + private Matcher() { + super(querySpecification()); + } + + /** + * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return matches represented as a Match object. + * + */ + public Collection getAllMatches(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return rawStreamAllMatches(new Object[]{pTrain, pLocation, pEnd}).collect(Collectors.toSet()); + } + + /** + * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return a stream of matches represented as a Match object. + * + */ + public Stream streamAllMatches(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return rawStreamAllMatches(new Object[]{pTrain, pLocation, pEnd}); + } + + /** + * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return a match represented as a Match object, or null if no match is found. + * + */ + public Optional getOneArbitraryMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return rawGetOneArbitraryMatch(new Object[]{pTrain, pLocation, pEnd}); + } + + /** + * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, + * under any possible substitution of the unspecified parameters (if any). + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return true if the input is a valid (partial) match of the pattern. + * + */ + public boolean hasMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return rawHasMatch(new Object[]{pTrain, pLocation, pEnd}); + } + + /** + * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return the number of pattern matches found. + * + */ + public int countMatches(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return rawCountMatches(new Object[]{pTrain, pLocation, pEnd}); + } + + /** + * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @param processor the action that will process the selected match. + * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked + * + */ + public boolean forOneArbitraryMatch(final Train pTrain, final Segment pLocation, final Segment pEnd, final Consumer processor) { + return rawForOneArbitraryMatch(new Object[]{pTrain, pLocation, pEnd}, processor); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return the (partial) match object. + * + */ + public EndOfSiding_step_5.Match newMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return EndOfSiding_step_5.Match.newMatch(pTrain, pLocation, pEnd); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOftrain(final Object[] parameters) { + return rawStreamAllValues(POSITION_TRAIN, parameters).map(Train.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()); + } + + /** + * Retrieve the set of values that occur in matches for train. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain(final EndOfSiding_step_5.Match partialMatch) { + return rawStreamAllValuesOftrain(partialMatch.toArray()); + } + + /** + * Retrieve the set of values that occur in matches for train. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain(final Segment pLocation, final Segment pEnd) { + return rawStreamAllValuesOftrain(new Object[]{null, pLocation, pEnd}); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain(final EndOfSiding_step_5.Match partialMatch) { + return rawStreamAllValuesOftrain(partialMatch.toArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain(final Segment pLocation, final Segment pEnd) { + return rawStreamAllValuesOftrain(new Object[]{null, pLocation, pEnd}).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOflocation(final Object[] parameters) { + return rawStreamAllValues(POSITION_LOCATION, parameters).map(Segment.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation() { + return rawStreamAllValuesOflocation(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation() { + return rawStreamAllValuesOflocation(emptyArray()); + } + + /** + * Retrieve the set of values that occur in matches for location. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation(final EndOfSiding_step_5.Match partialMatch) { + return rawStreamAllValuesOflocation(partialMatch.toArray()); + } + + /** + * Retrieve the set of values that occur in matches for location. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation(final Train pTrain, final Segment pEnd) { + return rawStreamAllValuesOflocation(new Object[]{pTrain, null, pEnd}); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation(final EndOfSiding_step_5.Match partialMatch) { + return rawStreamAllValuesOflocation(partialMatch.toArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation(final Train pTrain, final Segment pEnd) { + return rawStreamAllValuesOflocation(new Object[]{pTrain, null, pEnd}).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for end. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOfend(final Object[] parameters) { + return rawStreamAllValues(POSITION_END, parameters).map(Segment.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for end. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOfend() { + return rawStreamAllValuesOfend(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for end. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOfend() { + return rawStreamAllValuesOfend(emptyArray()); + } + + /** + * Retrieve the set of values that occur in matches for end. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOfend(final EndOfSiding_step_5.Match partialMatch) { + return rawStreamAllValuesOfend(partialMatch.toArray()); + } + + /** + * Retrieve the set of values that occur in matches for end. + *

+ * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOfend(final Train pTrain, final Segment pLocation) { + return rawStreamAllValuesOfend(new Object[]{pTrain, pLocation, null}); + } + + /** + * Retrieve the set of values that occur in matches for end. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOfend(final EndOfSiding_step_5.Match partialMatch) { + return rawStreamAllValuesOfend(partialMatch.toArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for end. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOfend(final Train pTrain, final Segment pLocation) { + return rawStreamAllValuesOfend(new Object[]{pTrain, pLocation, null}).collect(Collectors.toSet()); + } + + @Override + protected EndOfSiding_step_5.Match tupleToMatch(final Tuple t) { + try { + return EndOfSiding_step_5.Match.newMatch((Train) t.get(POSITION_TRAIN), (Segment) t.get(POSITION_LOCATION), (Segment) t.get(POSITION_END)); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in tuple not properly typed!",e); + return null; + } + } + + @Override + protected EndOfSiding_step_5.Match arrayToMatch(final Object[] match) { + try { + return EndOfSiding_step_5.Match.newMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION], (Segment) match[POSITION_END]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + @Override + protected EndOfSiding_step_5.Match arrayToMatchMutable(final Object[] match) { + try { + return EndOfSiding_step_5.Match.newMutableMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION], (Segment) match[POSITION_END]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + /** + * @return the singleton instance of the query specification of this pattern + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static IQuerySpecification querySpecification() { + return EndOfSiding_step_5.instance(); + } + } + + private EndOfSiding_step_5() { + super(GeneratedPQuery.INSTANCE); + } + + /** + * @return the singleton instance of the query specification + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static EndOfSiding_step_5 instance() { + try{ + return LazyHolder.INSTANCE; + } catch (ExceptionInInitializerError err) { + throw processInitializerError(err); + } + } + + @Override + protected EndOfSiding_step_5.Matcher instantiate(final ViatraQueryEngine engine) { + return EndOfSiding_step_5.Matcher.on(engine); + } + + @Override + public EndOfSiding_step_5.Matcher instantiate() { + return EndOfSiding_step_5.Matcher.create(); + } + + @Override + public EndOfSiding_step_5.Match newEmptyMatch() { + return EndOfSiding_step_5.Match.newEmptyMatch(); + } + + @Override + public EndOfSiding_step_5.Match newMatch(final Object... parameters) { + return EndOfSiding_step_5.Match.newMatch((modes3.Train) parameters[0], (modes3.Segment) parameters[1], (modes3.Segment) parameters[2]); + } + + /** + * Inner class allowing the singleton instance of {@link EndOfSiding_step_5} to be created + * not at the class load time of the outer class, + * but rather at the first call to {@link EndOfSiding_step_5#instance()}. + * + *

This workaround is required e.g. to support recursion. + * + */ + private static class LazyHolder { + private static final EndOfSiding_step_5 INSTANCE = new EndOfSiding_step_5(); + + /** + * Statically initializes the query specification after the field {@link #INSTANCE} is assigned. + * This initialization order is required to support indirect recursion. + * + *

The static initializer is defined using a helper field to work around limitations of the code generator. + * + */ + private static final Object STATIC_INITIALIZER = ensureInitialized(); + + public static Object ensureInitialized() { + INSTANCE.ensureInitializedInternal(); + return null; + } + } + + private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { + private static final EndOfSiding_step_5.GeneratedPQuery INSTANCE = new GeneratedPQuery(); + + private final PParameter parameter_train = new PParameter("train", "modes3.Train", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Train")), PParameterDirection.INOUT); + + private final PParameter parameter_location = new PParameter("location", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT); + + private final PParameter parameter_end = new PParameter("end", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT); + + private final List parameters = Arrays.asList(parameter_train, parameter_location, parameter_end); + + private GeneratedPQuery() { + super(PVisibility.PUBLIC); + } + + @Override + public String getFullyQualifiedName() { + return "modes3.queries.endOfSiding_step_5"; + } + + @Override + public List getParameterNames() { + return Arrays.asList("train","location","end"); + } + + @Override + public List getParameters() { + return parameters; + } + + @Override + public Set doGetContainedBodies() { + setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED)); + Set bodies = new LinkedHashSet<>(); + { + PBody body = new PBody(this); + PVariable var_train = body.getOrCreateVariableByName("train"); + PVariable var_location = body.getOrCreateVariableByName("location"); + PVariable var_end = body.getOrCreateVariableByName("end"); + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + new TypeConstraint(body, Tuples.flatTupleOf(var_location), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + new TypeConstraint(body, Tuples.flatTupleOf(var_end), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + body.setSymbolicParameters(Arrays.asList( + new ExportedParameter(body, var_train, parameter_train), + new ExportedParameter(body, var_location, parameter_location), + new ExportedParameter(body, var_end, parameter_end) + )); + // // results->matches[match_cntr].location = frame->location;// results->matches[match_cntr++].train = frame->train;// ...OR...// results->matches[match_cntr].location = frame->location;// results->matches[match_cntr++].train = frame->train; Train(train) + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + // Train.location(train, location) + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + PVariable var__virtual_0_ = body.getOrCreateVariableByName(".virtual{0}"); + new TypeConstraint(body, Tuples.flatTupleOf(var_train, var__virtual_0_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train", "location"))); + new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_0_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + new Equality(body, var__virtual_0_, var_location); + // Segment.connectedTo(location, end) + new TypeConstraint(body, Tuples.flatTupleOf(var_location), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + PVariable var__virtual_1_ = body.getOrCreateVariableByName(".virtual{1}"); + new TypeConstraint(body, Tuples.flatTupleOf(var_location, var__virtual_1_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment", "connectedTo"))); + new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_1_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + new Equality(body, var__virtual_1_, var_end); + // neg find multipleConnectedTo(end) + new NegativePatternCall(body, Tuples.flatTupleOf(var_end), MultipleConnectedTo.instance().getInternalQueryRepresentation()); + bodies.add(body); + } + return bodies; + } + } +} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/Modes3Queries.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/Modes3Queries.java index 6e244430..d1238d61 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/Modes3Queries.java +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/Modes3Queries.java @@ -4,16 +4,34 @@ package modes3.queries; import modes3.queries.Adjacent; +import modes3.queries.CloseTrains_step_2; +import modes3.queries.CloseTrains_step_3; +import modes3.queries.CloseTrains_step_4; +import modes3.queries.CloseTrains_step_5; +import modes3.queries.CloseTrains_step_6; +import modes3.queries.CloseTrains_step_7; +import modes3.queries.ConnectedSegmentsDirected; import modes3.queries.ConnectedTo; import modes3.queries.ConnectedToNotSymmetric; import modes3.queries.ConnectedToReflexive; +import modes3.queries.EndOfSiding_step_2; +import modes3.queries.EndOfSiding_step_3; +import modes3.queries.EndOfSiding_step_4; +import modes3.queries.EndOfSiding_step_5; import modes3.queries.InputsOfTurnout; +import modes3.queries.MisalignedTurnout_step_2; +import modes3.queries.MisalignedTurnout_step_3; +import modes3.queries.MisalignedTurnout_step_4; +import modes3.queries.MisalignedTurnout_step_5; +import modes3.queries.MultipleConnectedTo; import modes3.queries.Output; import modes3.queries.OutputReflexive; import modes3.queries.Reachable; import modes3.queries.TooFewInputsOfTurnout; import modes3.queries.TooManyInputsOfSegment; import modes3.queries.TooManyInputsOfTurnout; +import modes3.queries.TrainLocations_step_2; +import modes3.queries.TrainLocations_step_3; import modes3.queries.TurnoutConnectedToBothOutputs; import modes3.queries.TurnoutOutput; import modes3.queries.TurnoutOutputsAreSame; @@ -44,6 +62,24 @@ import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedPatternGroup; *

  • tooFewInputsOfTurnout
  • *
  • reachable
  • *
  • unreachable
  • + *
  • closeTrains_step_2
  • + *
  • closeTrains_step_3
  • + *
  • closeTrains_step_4
  • + *
  • closeTrains_step_5
  • + *
  • closeTrains_step_6
  • + *
  • closeTrains_step_7
  • + *
  • trainLocations_step_2
  • + *
  • trainLocations_step_3
  • + *
  • misalignedTurnout_step_2
  • + *
  • misalignedTurnout_step_3
  • + *
  • misalignedTurnout_step_4
  • + *
  • misalignedTurnout_step_5
  • + *
  • connectedSegmentsDirected
  • + *
  • endOfSiding_step_2
  • + *
  • endOfSiding_step_3
  • + *
  • endOfSiding_step_4
  • + *
  • endOfSiding_step_5
  • + *
  • multipleConnectedTo
  • * * * @see IQueryGroup @@ -83,6 +119,24 @@ public final class Modes3Queries extends BaseGeneratedPatternGroup { querySpecifications.add(TooFewInputsOfTurnout.instance()); querySpecifications.add(Reachable.instance()); querySpecifications.add(Unreachable.instance()); + querySpecifications.add(CloseTrains_step_2.instance()); + querySpecifications.add(CloseTrains_step_3.instance()); + querySpecifications.add(CloseTrains_step_4.instance()); + querySpecifications.add(CloseTrains_step_5.instance()); + querySpecifications.add(CloseTrains_step_6.instance()); + querySpecifications.add(CloseTrains_step_7.instance()); + querySpecifications.add(TrainLocations_step_2.instance()); + querySpecifications.add(TrainLocations_step_3.instance()); + querySpecifications.add(MisalignedTurnout_step_2.instance()); + querySpecifications.add(MisalignedTurnout_step_3.instance()); + querySpecifications.add(MisalignedTurnout_step_4.instance()); + querySpecifications.add(MisalignedTurnout_step_5.instance()); + querySpecifications.add(ConnectedSegmentsDirected.instance()); + querySpecifications.add(EndOfSiding_step_2.instance()); + querySpecifications.add(EndOfSiding_step_3.instance()); + querySpecifications.add(EndOfSiding_step_4.instance()); + querySpecifications.add(EndOfSiding_step_5.instance()); + querySpecifications.add(MultipleConnectedTo.instance()); } public ConnectedTo getConnectedTo() { @@ -204,4 +258,148 @@ public final class Modes3Queries extends BaseGeneratedPatternGroup { public Unreachable.Matcher getUnreachable(final ViatraQueryEngine engine) { return Unreachable.Matcher.on(engine); } + + public CloseTrains_step_2 getCloseTrains_step_2() { + return CloseTrains_step_2.instance(); + } + + public CloseTrains_step_2.Matcher getCloseTrains_step_2(final ViatraQueryEngine engine) { + return CloseTrains_step_2.Matcher.on(engine); + } + + public CloseTrains_step_3 getCloseTrains_step_3() { + return CloseTrains_step_3.instance(); + } + + public CloseTrains_step_3.Matcher getCloseTrains_step_3(final ViatraQueryEngine engine) { + return CloseTrains_step_3.Matcher.on(engine); + } + + public CloseTrains_step_4 getCloseTrains_step_4() { + return CloseTrains_step_4.instance(); + } + + public CloseTrains_step_4.Matcher getCloseTrains_step_4(final ViatraQueryEngine engine) { + return CloseTrains_step_4.Matcher.on(engine); + } + + public CloseTrains_step_5 getCloseTrains_step_5() { + return CloseTrains_step_5.instance(); + } + + public CloseTrains_step_5.Matcher getCloseTrains_step_5(final ViatraQueryEngine engine) { + return CloseTrains_step_5.Matcher.on(engine); + } + + public CloseTrains_step_6 getCloseTrains_step_6() { + return CloseTrains_step_6.instance(); + } + + public CloseTrains_step_6.Matcher getCloseTrains_step_6(final ViatraQueryEngine engine) { + return CloseTrains_step_6.Matcher.on(engine); + } + + public CloseTrains_step_7 getCloseTrains_step_7() { + return CloseTrains_step_7.instance(); + } + + public CloseTrains_step_7.Matcher getCloseTrains_step_7(final ViatraQueryEngine engine) { + return CloseTrains_step_7.Matcher.on(engine); + } + + public TrainLocations_step_2 getTrainLocations_step_2() { + return TrainLocations_step_2.instance(); + } + + public TrainLocations_step_2.Matcher getTrainLocations_step_2(final ViatraQueryEngine engine) { + return TrainLocations_step_2.Matcher.on(engine); + } + + public TrainLocations_step_3 getTrainLocations_step_3() { + return TrainLocations_step_3.instance(); + } + + public TrainLocations_step_3.Matcher getTrainLocations_step_3(final ViatraQueryEngine engine) { + return TrainLocations_step_3.Matcher.on(engine); + } + + public MisalignedTurnout_step_2 getMisalignedTurnout_step_2() { + return MisalignedTurnout_step_2.instance(); + } + + public MisalignedTurnout_step_2.Matcher getMisalignedTurnout_step_2(final ViatraQueryEngine engine) { + return MisalignedTurnout_step_2.Matcher.on(engine); + } + + public MisalignedTurnout_step_3 getMisalignedTurnout_step_3() { + return MisalignedTurnout_step_3.instance(); + } + + public MisalignedTurnout_step_3.Matcher getMisalignedTurnout_step_3(final ViatraQueryEngine engine) { + return MisalignedTurnout_step_3.Matcher.on(engine); + } + + public MisalignedTurnout_step_4 getMisalignedTurnout_step_4() { + return MisalignedTurnout_step_4.instance(); + } + + public MisalignedTurnout_step_4.Matcher getMisalignedTurnout_step_4(final ViatraQueryEngine engine) { + return MisalignedTurnout_step_4.Matcher.on(engine); + } + + public MisalignedTurnout_step_5 getMisalignedTurnout_step_5() { + return MisalignedTurnout_step_5.instance(); + } + + public MisalignedTurnout_step_5.Matcher getMisalignedTurnout_step_5(final ViatraQueryEngine engine) { + return MisalignedTurnout_step_5.Matcher.on(engine); + } + + public ConnectedSegmentsDirected getConnectedSegmentsDirected() { + return ConnectedSegmentsDirected.instance(); + } + + public ConnectedSegmentsDirected.Matcher getConnectedSegmentsDirected(final ViatraQueryEngine engine) { + return ConnectedSegmentsDirected.Matcher.on(engine); + } + + public EndOfSiding_step_2 getEndOfSiding_step_2() { + return EndOfSiding_step_2.instance(); + } + + public EndOfSiding_step_2.Matcher getEndOfSiding_step_2(final ViatraQueryEngine engine) { + return EndOfSiding_step_2.Matcher.on(engine); + } + + public EndOfSiding_step_3 getEndOfSiding_step_3() { + return EndOfSiding_step_3.instance(); + } + + public EndOfSiding_step_3.Matcher getEndOfSiding_step_3(final ViatraQueryEngine engine) { + return EndOfSiding_step_3.Matcher.on(engine); + } + + public EndOfSiding_step_4 getEndOfSiding_step_4() { + return EndOfSiding_step_4.instance(); + } + + public EndOfSiding_step_4.Matcher getEndOfSiding_step_4(final ViatraQueryEngine engine) { + return EndOfSiding_step_4.Matcher.on(engine); + } + + public EndOfSiding_step_5 getEndOfSiding_step_5() { + return EndOfSiding_step_5.instance(); + } + + public EndOfSiding_step_5.Matcher getEndOfSiding_step_5(final ViatraQueryEngine engine) { + return EndOfSiding_step_5.Matcher.on(engine); + } + + public MultipleConnectedTo getMultipleConnectedTo() { + return MultipleConnectedTo.instance(); + } + + public MultipleConnectedTo.Matcher getMultipleConnectedTo(final ViatraQueryEngine engine) { + return MultipleConnectedTo.Matcher.on(engine); + } } diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/MultipleConnectedTo.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/MultipleConnectedTo.java new file mode 100644 index 00000000..277006c9 --- /dev/null +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/MultipleConnectedTo.java @@ -0,0 +1,565 @@ +/** + * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql + */ +package modes3.queries; + +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import modes3.Segment; +import org.apache.log4j.Logger; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.viatra.query.runtime.api.IPatternMatch; +import org.eclipse.viatra.query.runtime.api.IQuerySpecification; +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification; +import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher; +import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch; +import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey; +import org.eclipse.viatra.query.runtime.emf.types.EStructuralFeatureInstancesKey; +import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint; +import org.eclipse.viatra.query.runtime.matchers.psystem.PBody; +import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Equality; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Inequality; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples; +import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil; + +/** + * A pattern-specific query specification that can instantiate Matcher in a type-safe way. + * + *

    Original source: + *

    + *         pattern multipleConnectedTo(s : Segment) {
    + *         	Segment.connectedTo(s, n1);
    + *         	Segment.connectedTo(s, n2);
    + *         	n1 != n2;
    + *         }
    + * 
    + * + * @see Matcher + * @see Match + * + */ +@SuppressWarnings("all") +public final class MultipleConnectedTo extends BaseGeneratedEMFQuerySpecification { + /** + * Pattern-specific match representation of the modes3.queries.multipleConnectedTo pattern, + * to be used in conjunction with {@link Matcher}. + * + *

    Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned. + * Each instance is a (possibly partial) substitution of pattern parameters, + * usable to represent a match of the pattern in the result of a query, + * or to specify the bound (fixed) input parameters when issuing a query. + * + * @see Matcher + * + */ + public static abstract class Match extends BasePatternMatch { + private Segment fS; + + private static List parameterNames = makeImmutableList("s"); + + private Match(final Segment pS) { + this.fS = pS; + } + + @Override + public Object get(final String parameterName) { + switch(parameterName) { + case "s": return this.fS; + default: return null; + } + } + + @Override + public Object get(final int index) { + switch(index) { + case 0: return this.fS; + default: return null; + } + } + + public Segment getS() { + return this.fS; + } + + @Override + public boolean set(final String parameterName, final Object newValue) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + if ("s".equals(parameterName) ) { + this.fS = (Segment) newValue; + return true; + } + return false; + } + + public void setS(final Segment pS) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fS = pS; + } + + @Override + public String patternName() { + return "modes3.queries.multipleConnectedTo"; + } + + @Override + public List parameterNames() { + return MultipleConnectedTo.Match.parameterNames; + } + + @Override + public Object[] toArray() { + return new Object[]{fS}; + } + + @Override + public MultipleConnectedTo.Match toImmutable() { + return isMutable() ? newMatch(fS) : this; + } + + @Override + public String prettyPrint() { + StringBuilder result = new StringBuilder(); + result.append("\"s\"=" + prettyPrintValue(fS)); + return result.toString(); + } + + @Override + public int hashCode() { + return Objects.hash(fS); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) { + return false; + } + if ((obj instanceof MultipleConnectedTo.Match)) { + MultipleConnectedTo.Match other = (MultipleConnectedTo.Match) obj; + return Objects.equals(fS, other.fS); + } else { + // this should be infrequent + if (!(obj instanceof IPatternMatch)) { + return false; + } + IPatternMatch otherSig = (IPatternMatch) obj; + return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray()); + } + } + + @Override + public MultipleConnectedTo specification() { + return MultipleConnectedTo.instance(); + } + + /** + * Returns an empty, mutable match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @return the empty match. + * + */ + public static MultipleConnectedTo.Match newEmptyMatch() { + return new Mutable(null); + } + + /** + * Returns a mutable (partial) match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @param pS the fixed value of pattern parameter s, or null if not bound. + * @return the new, mutable (partial) match object. + * + */ + public static MultipleConnectedTo.Match newMutableMatch(final Segment pS) { + return new Mutable(pS); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

    The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pS the fixed value of pattern parameter s, or null if not bound. + * @return the (partial) match object. + * + */ + public static MultipleConnectedTo.Match newMatch(final Segment pS) { + return new Immutable(pS); + } + + private static final class Mutable extends MultipleConnectedTo.Match { + Mutable(final Segment pS) { + super(pS); + } + + @Override + public boolean isMutable() { + return true; + } + } + + private static final class Immutable extends MultipleConnectedTo.Match { + Immutable(final Segment pS) { + super(pS); + } + + @Override + public boolean isMutable() { + return false; + } + } + } + + /** + * Generated pattern matcher API of the modes3.queries.multipleConnectedTo pattern, + * providing pattern-specific query methods. + * + *

    Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)}, + * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}. + * + *

    Matches of the pattern will be represented as {@link Match}. + * + *

    Original source: + *

    +   * pattern multipleConnectedTo(s : Segment) {
    +   * 	Segment.connectedTo(s, n1);
    +   * 	Segment.connectedTo(s, n2);
    +   * 	n1 != n2;
    +   * }
    +   * 
    + * + * @see Match + * @see MultipleConnectedTo + * + */ + public static class Matcher extends BaseMatcher { + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + public static MultipleConnectedTo.Matcher on(final ViatraQueryEngine engine) { + // check if matcher already exists + Matcher matcher = engine.getExistingMatcher(querySpecification()); + if (matcher == null) { + matcher = (Matcher)engine.getMatcher(querySpecification()); + } + return matcher; + } + + /** + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * @return an initialized matcher + * @noreference This method is for internal matcher initialization by the framework, do not call it manually. + * + */ + public static MultipleConnectedTo.Matcher create() { + return new Matcher(); + } + + private static final int POSITION_S = 0; + + private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(MultipleConnectedTo.Matcher.class); + + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + private Matcher() { + super(querySpecification()); + } + + /** + * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pS the fixed value of pattern parameter s, or null if not bound. + * @return matches represented as a Match object. + * + */ + public Collection getAllMatches(final Segment pS) { + return rawStreamAllMatches(new Object[]{pS}).collect(Collectors.toSet()); + } + + /** + * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * @param pS the fixed value of pattern parameter s, or null if not bound. + * @return a stream of matches represented as a Match object. + * + */ + public Stream streamAllMatches(final Segment pS) { + return rawStreamAllMatches(new Object[]{pS}); + } + + /** + * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pS the fixed value of pattern parameter s, or null if not bound. + * @return a match represented as a Match object, or null if no match is found. + * + */ + public Optional getOneArbitraryMatch(final Segment pS) { + return rawGetOneArbitraryMatch(new Object[]{pS}); + } + + /** + * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, + * under any possible substitution of the unspecified parameters (if any). + * @param pS the fixed value of pattern parameter s, or null if not bound. + * @return true if the input is a valid (partial) match of the pattern. + * + */ + public boolean hasMatch(final Segment pS) { + return rawHasMatch(new Object[]{pS}); + } + + /** + * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pS the fixed value of pattern parameter s, or null if not bound. + * @return the number of pattern matches found. + * + */ + public int countMatches(final Segment pS) { + return rawCountMatches(new Object[]{pS}); + } + + /** + * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pS the fixed value of pattern parameter s, or null if not bound. + * @param processor the action that will process the selected match. + * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked + * + */ + public boolean forOneArbitraryMatch(final Segment pS, final Consumer processor) { + return rawForOneArbitraryMatch(new Object[]{pS}, processor); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

    The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pS the fixed value of pattern parameter s, or null if not bound. + * @return the (partial) match object. + * + */ + public MultipleConnectedTo.Match newMatch(final Segment pS) { + return MultipleConnectedTo.Match.newMatch(pS); + } + + /** + * Retrieve the set of values that occur in matches for s. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOfs(final Object[] parameters) { + return rawStreamAllValues(POSITION_S, parameters).map(Segment.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for s. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOfs() { + return rawStreamAllValuesOfs(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for s. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOfs() { + return rawStreamAllValuesOfs(emptyArray()); + } + + @Override + protected MultipleConnectedTo.Match tupleToMatch(final Tuple t) { + try { + return MultipleConnectedTo.Match.newMatch((Segment) t.get(POSITION_S)); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in tuple not properly typed!",e); + return null; + } + } + + @Override + protected MultipleConnectedTo.Match arrayToMatch(final Object[] match) { + try { + return MultipleConnectedTo.Match.newMatch((Segment) match[POSITION_S]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + @Override + protected MultipleConnectedTo.Match arrayToMatchMutable(final Object[] match) { + try { + return MultipleConnectedTo.Match.newMutableMatch((Segment) match[POSITION_S]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + /** + * @return the singleton instance of the query specification of this pattern + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static IQuerySpecification querySpecification() { + return MultipleConnectedTo.instance(); + } + } + + private MultipleConnectedTo() { + super(GeneratedPQuery.INSTANCE); + } + + /** + * @return the singleton instance of the query specification + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static MultipleConnectedTo instance() { + try{ + return LazyHolder.INSTANCE; + } catch (ExceptionInInitializerError err) { + throw processInitializerError(err); + } + } + + @Override + protected MultipleConnectedTo.Matcher instantiate(final ViatraQueryEngine engine) { + return MultipleConnectedTo.Matcher.on(engine); + } + + @Override + public MultipleConnectedTo.Matcher instantiate() { + return MultipleConnectedTo.Matcher.create(); + } + + @Override + public MultipleConnectedTo.Match newEmptyMatch() { + return MultipleConnectedTo.Match.newEmptyMatch(); + } + + @Override + public MultipleConnectedTo.Match newMatch(final Object... parameters) { + return MultipleConnectedTo.Match.newMatch((modes3.Segment) parameters[0]); + } + + /** + * Inner class allowing the singleton instance of {@link MultipleConnectedTo} to be created + * not at the class load time of the outer class, + * but rather at the first call to {@link MultipleConnectedTo#instance()}. + * + *

    This workaround is required e.g. to support recursion. + * + */ + private static class LazyHolder { + private static final MultipleConnectedTo INSTANCE = new MultipleConnectedTo(); + + /** + * Statically initializes the query specification after the field {@link #INSTANCE} is assigned. + * This initialization order is required to support indirect recursion. + * + *

    The static initializer is defined using a helper field to work around limitations of the code generator. + * + */ + private static final Object STATIC_INITIALIZER = ensureInitialized(); + + public static Object ensureInitialized() { + INSTANCE.ensureInitializedInternal(); + return null; + } + } + + private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { + private static final MultipleConnectedTo.GeneratedPQuery INSTANCE = new GeneratedPQuery(); + + private final PParameter parameter_s = new PParameter("s", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT); + + private final List parameters = Arrays.asList(parameter_s); + + private GeneratedPQuery() { + super(PVisibility.PUBLIC); + } + + @Override + public String getFullyQualifiedName() { + return "modes3.queries.multipleConnectedTo"; + } + + @Override + public List getParameterNames() { + return Arrays.asList("s"); + } + + @Override + public List getParameters() { + return parameters; + } + + @Override + public Set doGetContainedBodies() { + setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED)); + Set bodies = new LinkedHashSet<>(); + { + PBody body = new PBody(this); + PVariable var_s = body.getOrCreateVariableByName("s"); + PVariable var_n1 = body.getOrCreateVariableByName("n1"); + PVariable var_n2 = body.getOrCreateVariableByName("n2"); + new TypeConstraint(body, Tuples.flatTupleOf(var_s), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + body.setSymbolicParameters(Arrays.asList( + new ExportedParameter(body, var_s, parameter_s) + )); + // Segment.connectedTo(s, n1) + new TypeConstraint(body, Tuples.flatTupleOf(var_s), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + PVariable var__virtual_0_ = body.getOrCreateVariableByName(".virtual{0}"); + new TypeConstraint(body, Tuples.flatTupleOf(var_s, var__virtual_0_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment", "connectedTo"))); + new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_0_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + new Equality(body, var__virtual_0_, var_n1); + // Segment.connectedTo(s, n2) + new TypeConstraint(body, Tuples.flatTupleOf(var_s), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + PVariable var__virtual_1_ = body.getOrCreateVariableByName(".virtual{1}"); + new TypeConstraint(body, Tuples.flatTupleOf(var_s, var__virtual_1_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment", "connectedTo"))); + new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_1_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + new Equality(body, var__virtual_1_, var_n2); + // n1 != n2 + new Inequality(body, var_n1, var_n2); + bodies.add(body); + } + return bodies; + } + } +} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooManyInputsOfSegment.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooManyInputsOfSegment.java index ff82dda1..d12ec23e 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooManyInputsOfSegment.java +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooManyInputsOfSegment.java @@ -46,12 +46,6 @@ import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil; * *

    Original source: *

    - *         //{@literal @}Constraint(message = "noInputOfSegment", severity = "error", key = { S })
    - *         //pattern noInputOfSegment(S : Segment) {
    - *         //	neg find turnout(S);
    - *         //	neg find output(_, S);
    - *         //}
    - *         
      *         {@literal @}Constraint(message = "tooManyInputsOfSegment", severity = "error", key = { S })
      *         pattern tooManyInputsOfSegment(S : SimpleSegment) {
      *         	find output(I1, S);
    @@ -251,12 +245,6 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica
        * 
        * 

    Original source: *

    -   * //{@literal @}Constraint(message = "noInputOfSegment", severity = "error", key = { S })
    -   * //pattern noInputOfSegment(S : Segment) {
    -   * //	neg find turnout(S);
    -   * //	neg find output(_, S);
    -   * //}
    -   * 
        * {@literal @}Constraint(message = "tooManyInputsOfSegment", severity = "error", key = { S })
        * pattern tooManyInputsOfSegment(S : SimpleSegment) {
        * 	find output(I1, S);
    diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TrainLocations_step_2.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TrainLocations_step_2.java
    new file mode 100644
    index 00000000..5bf153c3
    --- /dev/null
    +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TrainLocations_step_2.java
    @@ -0,0 +1,564 @@
    +/**
    + * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql
    + */
    +package modes3.queries;
    +
    +import java.util.Arrays;
    +import java.util.Collection;
    +import java.util.LinkedHashSet;
    +import java.util.List;
    +import java.util.Objects;
    +import java.util.Optional;
    +import java.util.Set;
    +import java.util.function.Consumer;
    +import java.util.stream.Collectors;
    +import java.util.stream.Stream;
    +import modes3.Train;
    +import org.apache.log4j.Logger;
    +import org.eclipse.emf.ecore.EClass;
    +import org.eclipse.viatra.query.runtime.api.IPatternMatch;
    +import org.eclipse.viatra.query.runtime.api.IQuerySpecification;
    +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine;
    +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery;
    +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification;
    +import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher;
    +import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch;
    +import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey;
    +import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint;
    +import org.eclipse.viatra.query.runtime.matchers.psystem.PBody;
    +import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable;
    +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter;
    +import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint;
    +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter;
    +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection;
    +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility;
    +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple;
    +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples;
    +import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil;
    +
    +/**
    + * A pattern-specific query specification that can instantiate Matcher in a type-safe way.
    + * 
    + * 

    Original source: + *

    + *         //
    + *         // trainLocations
    + *         //
    + *         
    + *         pattern trainLocations_step_2(in train : Train) {
    + *         //   frame-{@literal >}train = model-{@literal >}trains[i0];
    + *         //   frame-{@literal >}location = frame-{@literal >}train-{@literal >}location;
    + *         //   if (frame-{@literal >}location != NULL) {
    + *         //     ...
    + *         //   }
    + *         
    + *         	Train(train);
    + *         }
    + * 
    + * + * @see Matcher + * @see Match + * + */ +@SuppressWarnings("all") +public final class TrainLocations_step_2 extends BaseGeneratedEMFQuerySpecification { + /** + * Pattern-specific match representation of the modes3.queries.trainLocations_step_2 pattern, + * to be used in conjunction with {@link Matcher}. + * + *

    Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned. + * Each instance is a (possibly partial) substitution of pattern parameters, + * usable to represent a match of the pattern in the result of a query, + * or to specify the bound (fixed) input parameters when issuing a query. + * + * @see Matcher + * + */ + public static abstract class Match extends BasePatternMatch { + private Train fTrain; + + private static List parameterNames = makeImmutableList("train"); + + private Match(final Train pTrain) { + this.fTrain = pTrain; + } + + @Override + public Object get(final String parameterName) { + switch(parameterName) { + case "train": return this.fTrain; + default: return null; + } + } + + @Override + public Object get(final int index) { + switch(index) { + case 0: return this.fTrain; + default: return null; + } + } + + public Train getTrain() { + return this.fTrain; + } + + @Override + public boolean set(final String parameterName, final Object newValue) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + if ("train".equals(parameterName) ) { + this.fTrain = (Train) newValue; + return true; + } + return false; + } + + public void setTrain(final Train pTrain) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fTrain = pTrain; + } + + @Override + public String patternName() { + return "modes3.queries.trainLocations_step_2"; + } + + @Override + public List parameterNames() { + return TrainLocations_step_2.Match.parameterNames; + } + + @Override + public Object[] toArray() { + return new Object[]{fTrain}; + } + + @Override + public TrainLocations_step_2.Match toImmutable() { + return isMutable() ? newMatch(fTrain) : this; + } + + @Override + public String prettyPrint() { + StringBuilder result = new StringBuilder(); + result.append("\"train\"=" + prettyPrintValue(fTrain)); + return result.toString(); + } + + @Override + public int hashCode() { + return Objects.hash(fTrain); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) { + return false; + } + if ((obj instanceof TrainLocations_step_2.Match)) { + TrainLocations_step_2.Match other = (TrainLocations_step_2.Match) obj; + return Objects.equals(fTrain, other.fTrain); + } else { + // this should be infrequent + if (!(obj instanceof IPatternMatch)) { + return false; + } + IPatternMatch otherSig = (IPatternMatch) obj; + return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray()); + } + } + + @Override + public TrainLocations_step_2 specification() { + return TrainLocations_step_2.instance(); + } + + /** + * Returns an empty, mutable match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @return the empty match. + * + */ + public static TrainLocations_step_2.Match newEmptyMatch() { + return new Mutable(null); + } + + /** + * Returns a mutable (partial) match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return the new, mutable (partial) match object. + * + */ + public static TrainLocations_step_2.Match newMutableMatch(final Train pTrain) { + return new Mutable(pTrain); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

    The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return the (partial) match object. + * + */ + public static TrainLocations_step_2.Match newMatch(final Train pTrain) { + return new Immutable(pTrain); + } + + private static final class Mutable extends TrainLocations_step_2.Match { + Mutable(final Train pTrain) { + super(pTrain); + } + + @Override + public boolean isMutable() { + return true; + } + } + + private static final class Immutable extends TrainLocations_step_2.Match { + Immutable(final Train pTrain) { + super(pTrain); + } + + @Override + public boolean isMutable() { + return false; + } + } + } + + /** + * Generated pattern matcher API of the modes3.queries.trainLocations_step_2 pattern, + * providing pattern-specific query methods. + * + *

    Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)}, + * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}. + * + *

    Matches of the pattern will be represented as {@link Match}. + * + *

    Original source: + *

    +   * //
    +   * // trainLocations
    +   * //
    +   * 
    +   * pattern trainLocations_step_2(in train : Train) {
    +   * //   frame-{@literal >}train = model-{@literal >}trains[i0];
    +   * //   frame-{@literal >}location = frame-{@literal >}train-{@literal >}location;
    +   * //   if (frame-{@literal >}location != NULL) {
    +   * //     ...
    +   * //   }
    +   * 
    +   * 	Train(train);
    +   * }
    +   * 
    + * + * @see Match + * @see TrainLocations_step_2 + * + */ + public static class Matcher extends BaseMatcher { + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + public static TrainLocations_step_2.Matcher on(final ViatraQueryEngine engine) { + // check if matcher already exists + Matcher matcher = engine.getExistingMatcher(querySpecification()); + if (matcher == null) { + matcher = (Matcher)engine.getMatcher(querySpecification()); + } + return matcher; + } + + /** + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * @return an initialized matcher + * @noreference This method is for internal matcher initialization by the framework, do not call it manually. + * + */ + public static TrainLocations_step_2.Matcher create() { + return new Matcher(); + } + + private static final int POSITION_TRAIN = 0; + + private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(TrainLocations_step_2.Matcher.class); + + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + private Matcher() { + super(querySpecification()); + } + + /** + * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return matches represented as a Match object. + * + */ + public Collection getAllMatches(final Train pTrain) { + return rawStreamAllMatches(new Object[]{pTrain}).collect(Collectors.toSet()); + } + + /** + * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return a stream of matches represented as a Match object. + * + */ + public Stream streamAllMatches(final Train pTrain) { + return rawStreamAllMatches(new Object[]{pTrain}); + } + + /** + * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return a match represented as a Match object, or null if no match is found. + * + */ + public Optional getOneArbitraryMatch(final Train pTrain) { + return rawGetOneArbitraryMatch(new Object[]{pTrain}); + } + + /** + * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, + * under any possible substitution of the unspecified parameters (if any). + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return true if the input is a valid (partial) match of the pattern. + * + */ + public boolean hasMatch(final Train pTrain) { + return rawHasMatch(new Object[]{pTrain}); + } + + /** + * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return the number of pattern matches found. + * + */ + public int countMatches(final Train pTrain) { + return rawCountMatches(new Object[]{pTrain}); + } + + /** + * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param processor the action that will process the selected match. + * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked + * + */ + public boolean forOneArbitraryMatch(final Train pTrain, final Consumer processor) { + return rawForOneArbitraryMatch(new Object[]{pTrain}, processor); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

    The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return the (partial) match object. + * + */ + public TrainLocations_step_2.Match newMatch(final Train pTrain) { + return TrainLocations_step_2.Match.newMatch(pTrain); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOftrain(final Object[] parameters) { + return rawStreamAllValues(POSITION_TRAIN, parameters).map(Train.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()); + } + + @Override + protected TrainLocations_step_2.Match tupleToMatch(final Tuple t) { + try { + return TrainLocations_step_2.Match.newMatch((Train) t.get(POSITION_TRAIN)); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in tuple not properly typed!",e); + return null; + } + } + + @Override + protected TrainLocations_step_2.Match arrayToMatch(final Object[] match) { + try { + return TrainLocations_step_2.Match.newMatch((Train) match[POSITION_TRAIN]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + @Override + protected TrainLocations_step_2.Match arrayToMatchMutable(final Object[] match) { + try { + return TrainLocations_step_2.Match.newMutableMatch((Train) match[POSITION_TRAIN]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + /** + * @return the singleton instance of the query specification of this pattern + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static IQuerySpecification querySpecification() { + return TrainLocations_step_2.instance(); + } + } + + private TrainLocations_step_2() { + super(GeneratedPQuery.INSTANCE); + } + + /** + * @return the singleton instance of the query specification + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static TrainLocations_step_2 instance() { + try{ + return LazyHolder.INSTANCE; + } catch (ExceptionInInitializerError err) { + throw processInitializerError(err); + } + } + + @Override + protected TrainLocations_step_2.Matcher instantiate(final ViatraQueryEngine engine) { + return TrainLocations_step_2.Matcher.on(engine); + } + + @Override + public TrainLocations_step_2.Matcher instantiate() { + return TrainLocations_step_2.Matcher.create(); + } + + @Override + public TrainLocations_step_2.Match newEmptyMatch() { + return TrainLocations_step_2.Match.newEmptyMatch(); + } + + @Override + public TrainLocations_step_2.Match newMatch(final Object... parameters) { + return TrainLocations_step_2.Match.newMatch((modes3.Train) parameters[0]); + } + + /** + * Inner class allowing the singleton instance of {@link TrainLocations_step_2} to be created + * not at the class load time of the outer class, + * but rather at the first call to {@link TrainLocations_step_2#instance()}. + * + *

    This workaround is required e.g. to support recursion. + * + */ + private static class LazyHolder { + private static final TrainLocations_step_2 INSTANCE = new TrainLocations_step_2(); + + /** + * Statically initializes the query specification after the field {@link #INSTANCE} is assigned. + * This initialization order is required to support indirect recursion. + * + *

    The static initializer is defined using a helper field to work around limitations of the code generator. + * + */ + private static final Object STATIC_INITIALIZER = ensureInitialized(); + + public static Object ensureInitialized() { + INSTANCE.ensureInitializedInternal(); + return null; + } + } + + private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { + private static final TrainLocations_step_2.GeneratedPQuery INSTANCE = new GeneratedPQuery(); + + private final PParameter parameter_train = new PParameter("train", "modes3.Train", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Train")), PParameterDirection.INOUT); + + private final List parameters = Arrays.asList(parameter_train); + + private GeneratedPQuery() { + super(PVisibility.PUBLIC); + } + + @Override + public String getFullyQualifiedName() { + return "modes3.queries.trainLocations_step_2"; + } + + @Override + public List getParameterNames() { + return Arrays.asList("train"); + } + + @Override + public List getParameters() { + return parameters; + } + + @Override + public Set doGetContainedBodies() { + setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED)); + Set bodies = new LinkedHashSet<>(); + { + PBody body = new PBody(this); + PVariable var_train = body.getOrCreateVariableByName("train"); + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + body.setSymbolicParameters(Arrays.asList( + new ExportedParameter(body, var_train, parameter_train) + )); + // // frame->train = model->trains[i0];// frame->location = frame->train->location;// if (frame->location != NULL) {// ...// } Train(train) + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + bodies.add(body); + } + return bodies; + } + } +} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TrainLocations_step_3.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TrainLocations_step_3.java new file mode 100644 index 00000000..edbd4af3 --- /dev/null +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TrainLocations_step_3.java @@ -0,0 +1,713 @@ +/** + * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql + */ +package modes3.queries; + +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import modes3.Segment; +import modes3.Train; +import org.apache.log4j.Logger; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.viatra.query.runtime.api.IPatternMatch; +import org.eclipse.viatra.query.runtime.api.IQuerySpecification; +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification; +import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher; +import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch; +import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey; +import org.eclipse.viatra.query.runtime.emf.types.EStructuralFeatureInstancesKey; +import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint; +import org.eclipse.viatra.query.runtime.matchers.psystem.PBody; +import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Equality; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples; +import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil; + +/** + * A pattern-specific query specification that can instantiate Matcher in a type-safe way. + * + *

    Original source: + *

    + *         pattern trainLocations_step_3(in train : Train, in location : Segment) {
    + *         //     results-{@literal >}matches[match_cntr].location = frame-{@literal >}location;
    + *         //     results-{@literal >}matches[match_cntr++].train = frame-{@literal >}train;
    + *         	Train(train);
    + *             Train.location(train, location);
    + *         }
    + * 
    + * + * @see Matcher + * @see Match + * + */ +@SuppressWarnings("all") +public final class TrainLocations_step_3 extends BaseGeneratedEMFQuerySpecification { + /** + * Pattern-specific match representation of the modes3.queries.trainLocations_step_3 pattern, + * to be used in conjunction with {@link Matcher}. + * + *

    Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned. + * Each instance is a (possibly partial) substitution of pattern parameters, + * usable to represent a match of the pattern in the result of a query, + * or to specify the bound (fixed) input parameters when issuing a query. + * + * @see Matcher + * + */ + public static abstract class Match extends BasePatternMatch { + private Train fTrain; + + private Segment fLocation; + + private static List parameterNames = makeImmutableList("train", "location"); + + private Match(final Train pTrain, final Segment pLocation) { + this.fTrain = pTrain; + this.fLocation = pLocation; + } + + @Override + public Object get(final String parameterName) { + switch(parameterName) { + case "train": return this.fTrain; + case "location": return this.fLocation; + default: return null; + } + } + + @Override + public Object get(final int index) { + switch(index) { + case 0: return this.fTrain; + case 1: return this.fLocation; + default: return null; + } + } + + public Train getTrain() { + return this.fTrain; + } + + public Segment getLocation() { + return this.fLocation; + } + + @Override + public boolean set(final String parameterName, final Object newValue) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + if ("train".equals(parameterName) ) { + this.fTrain = (Train) newValue; + return true; + } + if ("location".equals(parameterName) ) { + this.fLocation = (Segment) newValue; + return true; + } + return false; + } + + public void setTrain(final Train pTrain) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fTrain = pTrain; + } + + public void setLocation(final Segment pLocation) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fLocation = pLocation; + } + + @Override + public String patternName() { + return "modes3.queries.trainLocations_step_3"; + } + + @Override + public List parameterNames() { + return TrainLocations_step_3.Match.parameterNames; + } + + @Override + public Object[] toArray() { + return new Object[]{fTrain, fLocation}; + } + + @Override + public TrainLocations_step_3.Match toImmutable() { + return isMutable() ? newMatch(fTrain, fLocation) : this; + } + + @Override + public String prettyPrint() { + StringBuilder result = new StringBuilder(); + result.append("\"train\"=" + prettyPrintValue(fTrain) + ", "); + result.append("\"location\"=" + prettyPrintValue(fLocation)); + return result.toString(); + } + + @Override + public int hashCode() { + return Objects.hash(fTrain, fLocation); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) { + return false; + } + if ((obj instanceof TrainLocations_step_3.Match)) { + TrainLocations_step_3.Match other = (TrainLocations_step_3.Match) obj; + return Objects.equals(fTrain, other.fTrain) && Objects.equals(fLocation, other.fLocation); + } else { + // this should be infrequent + if (!(obj instanceof IPatternMatch)) { + return false; + } + IPatternMatch otherSig = (IPatternMatch) obj; + return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray()); + } + } + + @Override + public TrainLocations_step_3 specification() { + return TrainLocations_step_3.instance(); + } + + /** + * Returns an empty, mutable match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @return the empty match. + * + */ + public static TrainLocations_step_3.Match newEmptyMatch() { + return new Mutable(null, null); + } + + /** + * Returns a mutable (partial) match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return the new, mutable (partial) match object. + * + */ + public static TrainLocations_step_3.Match newMutableMatch(final Train pTrain, final Segment pLocation) { + return new Mutable(pTrain, pLocation); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

    The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return the (partial) match object. + * + */ + public static TrainLocations_step_3.Match newMatch(final Train pTrain, final Segment pLocation) { + return new Immutable(pTrain, pLocation); + } + + private static final class Mutable extends TrainLocations_step_3.Match { + Mutable(final Train pTrain, final Segment pLocation) { + super(pTrain, pLocation); + } + + @Override + public boolean isMutable() { + return true; + } + } + + private static final class Immutable extends TrainLocations_step_3.Match { + Immutable(final Train pTrain, final Segment pLocation) { + super(pTrain, pLocation); + } + + @Override + public boolean isMutable() { + return false; + } + } + } + + /** + * Generated pattern matcher API of the modes3.queries.trainLocations_step_3 pattern, + * providing pattern-specific query methods. + * + *

    Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)}, + * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}. + * + *

    Matches of the pattern will be represented as {@link Match}. + * + *

    Original source: + *

    +   * pattern trainLocations_step_3(in train : Train, in location : Segment) {
    +   * //     results-{@literal >}matches[match_cntr].location = frame-{@literal >}location;
    +   * //     results-{@literal >}matches[match_cntr++].train = frame-{@literal >}train;
    +   * 	Train(train);
    +   *     Train.location(train, location);
    +   * }
    +   * 
    + * + * @see Match + * @see TrainLocations_step_3 + * + */ + public static class Matcher extends BaseMatcher { + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + public static TrainLocations_step_3.Matcher on(final ViatraQueryEngine engine) { + // check if matcher already exists + Matcher matcher = engine.getExistingMatcher(querySpecification()); + if (matcher == null) { + matcher = (Matcher)engine.getMatcher(querySpecification()); + } + return matcher; + } + + /** + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * @return an initialized matcher + * @noreference This method is for internal matcher initialization by the framework, do not call it manually. + * + */ + public static TrainLocations_step_3.Matcher create() { + return new Matcher(); + } + + private static final int POSITION_TRAIN = 0; + + private static final int POSITION_LOCATION = 1; + + private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(TrainLocations_step_3.Matcher.class); + + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + private Matcher() { + super(querySpecification()); + } + + /** + * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return matches represented as a Match object. + * + */ + public Collection getAllMatches(final Train pTrain, final Segment pLocation) { + return rawStreamAllMatches(new Object[]{pTrain, pLocation}).collect(Collectors.toSet()); + } + + /** + * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return a stream of matches represented as a Match object. + * + */ + public Stream streamAllMatches(final Train pTrain, final Segment pLocation) { + return rawStreamAllMatches(new Object[]{pTrain, pLocation}); + } + + /** + * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return a match represented as a Match object, or null if no match is found. + * + */ + public Optional getOneArbitraryMatch(final Train pTrain, final Segment pLocation) { + return rawGetOneArbitraryMatch(new Object[]{pTrain, pLocation}); + } + + /** + * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, + * under any possible substitution of the unspecified parameters (if any). + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return true if the input is a valid (partial) match of the pattern. + * + */ + public boolean hasMatch(final Train pTrain, final Segment pLocation) { + return rawHasMatch(new Object[]{pTrain, pLocation}); + } + + /** + * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return the number of pattern matches found. + * + */ + public int countMatches(final Train pTrain, final Segment pLocation) { + return rawCountMatches(new Object[]{pTrain, pLocation}); + } + + /** + * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param processor the action that will process the selected match. + * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked + * + */ + public boolean forOneArbitraryMatch(final Train pTrain, final Segment pLocation, final Consumer processor) { + return rawForOneArbitraryMatch(new Object[]{pTrain, pLocation}, processor); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

    The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return the (partial) match object. + * + */ + public TrainLocations_step_3.Match newMatch(final Train pTrain, final Segment pLocation) { + return TrainLocations_step_3.Match.newMatch(pTrain, pLocation); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOftrain(final Object[] parameters) { + return rawStreamAllValues(POSITION_TRAIN, parameters).map(Train.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()); + } + + /** + * Retrieve the set of values that occur in matches for train. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain(final TrainLocations_step_3.Match partialMatch) { + return rawStreamAllValuesOftrain(partialMatch.toArray()); + } + + /** + * Retrieve the set of values that occur in matches for train. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain(final Segment pLocation) { + return rawStreamAllValuesOftrain(new Object[]{null, pLocation}); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain(final TrainLocations_step_3.Match partialMatch) { + return rawStreamAllValuesOftrain(partialMatch.toArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain(final Segment pLocation) { + return rawStreamAllValuesOftrain(new Object[]{null, pLocation}).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOflocation(final Object[] parameters) { + return rawStreamAllValues(POSITION_LOCATION, parameters).map(Segment.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation() { + return rawStreamAllValuesOflocation(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation() { + return rawStreamAllValuesOflocation(emptyArray()); + } + + /** + * Retrieve the set of values that occur in matches for location. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation(final TrainLocations_step_3.Match partialMatch) { + return rawStreamAllValuesOflocation(partialMatch.toArray()); + } + + /** + * Retrieve the set of values that occur in matches for location. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation(final Train pTrain) { + return rawStreamAllValuesOflocation(new Object[]{pTrain, null}); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation(final TrainLocations_step_3.Match partialMatch) { + return rawStreamAllValuesOflocation(partialMatch.toArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation(final Train pTrain) { + return rawStreamAllValuesOflocation(new Object[]{pTrain, null}).collect(Collectors.toSet()); + } + + @Override + protected TrainLocations_step_3.Match tupleToMatch(final Tuple t) { + try { + return TrainLocations_step_3.Match.newMatch((Train) t.get(POSITION_TRAIN), (Segment) t.get(POSITION_LOCATION)); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in tuple not properly typed!",e); + return null; + } + } + + @Override + protected TrainLocations_step_3.Match arrayToMatch(final Object[] match) { + try { + return TrainLocations_step_3.Match.newMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + @Override + protected TrainLocations_step_3.Match arrayToMatchMutable(final Object[] match) { + try { + return TrainLocations_step_3.Match.newMutableMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + /** + * @return the singleton instance of the query specification of this pattern + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static IQuerySpecification querySpecification() { + return TrainLocations_step_3.instance(); + } + } + + private TrainLocations_step_3() { + super(GeneratedPQuery.INSTANCE); + } + + /** + * @return the singleton instance of the query specification + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static TrainLocations_step_3 instance() { + try{ + return LazyHolder.INSTANCE; + } catch (ExceptionInInitializerError err) { + throw processInitializerError(err); + } + } + + @Override + protected TrainLocations_step_3.Matcher instantiate(final ViatraQueryEngine engine) { + return TrainLocations_step_3.Matcher.on(engine); + } + + @Override + public TrainLocations_step_3.Matcher instantiate() { + return TrainLocations_step_3.Matcher.create(); + } + + @Override + public TrainLocations_step_3.Match newEmptyMatch() { + return TrainLocations_step_3.Match.newEmptyMatch(); + } + + @Override + public TrainLocations_step_3.Match newMatch(final Object... parameters) { + return TrainLocations_step_3.Match.newMatch((modes3.Train) parameters[0], (modes3.Segment) parameters[1]); + } + + /** + * Inner class allowing the singleton instance of {@link TrainLocations_step_3} to be created + * not at the class load time of the outer class, + * but rather at the first call to {@link TrainLocations_step_3#instance()}. + * + *

    This workaround is required e.g. to support recursion. + * + */ + private static class LazyHolder { + private static final TrainLocations_step_3 INSTANCE = new TrainLocations_step_3(); + + /** + * Statically initializes the query specification after the field {@link #INSTANCE} is assigned. + * This initialization order is required to support indirect recursion. + * + *

    The static initializer is defined using a helper field to work around limitations of the code generator. + * + */ + private static final Object STATIC_INITIALIZER = ensureInitialized(); + + public static Object ensureInitialized() { + INSTANCE.ensureInitializedInternal(); + return null; + } + } + + private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { + private static final TrainLocations_step_3.GeneratedPQuery INSTANCE = new GeneratedPQuery(); + + private final PParameter parameter_train = new PParameter("train", "modes3.Train", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Train")), PParameterDirection.INOUT); + + private final PParameter parameter_location = new PParameter("location", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT); + + private final List parameters = Arrays.asList(parameter_train, parameter_location); + + private GeneratedPQuery() { + super(PVisibility.PUBLIC); + } + + @Override + public String getFullyQualifiedName() { + return "modes3.queries.trainLocations_step_3"; + } + + @Override + public List getParameterNames() { + return Arrays.asList("train","location"); + } + + @Override + public List getParameters() { + return parameters; + } + + @Override + public Set doGetContainedBodies() { + setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED)); + Set bodies = new LinkedHashSet<>(); + { + PBody body = new PBody(this); + PVariable var_train = body.getOrCreateVariableByName("train"); + PVariable var_location = body.getOrCreateVariableByName("location"); + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + new TypeConstraint(body, Tuples.flatTupleOf(var_location), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + body.setSymbolicParameters(Arrays.asList( + new ExportedParameter(body, var_train, parameter_train), + new ExportedParameter(body, var_location, parameter_location) + )); + // // results->matches[match_cntr].location = frame->location;// results->matches[match_cntr++].train = frame->train; Train(train) + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + // Train.location(train, location) + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + PVariable var__virtual_0_ = body.getOrCreateVariableByName(".virtual{0}"); + new TypeConstraint(body, Tuples.flatTupleOf(var_train, var__virtual_0_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train", "location"))); + new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_0_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + new Equality(body, var__virtual_0_, var_location); + bodies.add(body); + } + return bodies; + } + } +} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.CloseTrainsObjectiveHint.xtendbin b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.CloseTrainsObjectiveHint.xtendbin new file mode 100644 index 00000000..87975792 Binary files /dev/null and b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.CloseTrainsObjectiveHint.xtendbin differ diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.EndOfSidingObjectiveHint.xtendbin b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.EndOfSidingObjectiveHint.xtendbin new file mode 100644 index 00000000..f243e180 Binary files /dev/null and b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.EndOfSidingObjectiveHint.xtendbin differ diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.MisalignedTurnoutObjectiveHint.xtendbin b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.MisalignedTurnoutObjectiveHint.xtendbin new file mode 100644 index 00000000..cdef4dc7 Binary files /dev/null and b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.MisalignedTurnoutObjectiveHint.xtendbin differ diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbin b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbin index 77f1ea6e..759ac9e4 100644 Binary files a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbin and b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbin differ diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3TypeScopeHint.xtendbin b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3TypeScopeHint.xtendbin index 4fdbb71b..386baeda 100644 Binary files a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3TypeScopeHint.xtendbin and b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3TypeScopeHint.xtendbin differ diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3UnitPropagationGenerator.xtendbin b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3UnitPropagationGenerator.xtendbin index e5e1b63e..79059b7f 100644 Binary files a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3UnitPropagationGenerator.xtendbin and b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3UnitPropagationGenerator.xtendbin differ diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.TrainLocationsObjectiveHint.xtendbin b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.TrainLocationsObjectiveHint.xtendbin new file mode 100644 index 00000000..3c3a380e Binary files /dev/null and b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.TrainLocationsObjectiveHint.xtendbin differ diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.gitignore b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.gitignore index fb94df96..1a7df1d9 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.gitignore +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.gitignore @@ -1,3 +1,13 @@ /.Modes3ModelGenerator.java._trace /.Modes3UnitPropagationGenerator.java._trace /.Modes3TypeScopeHint.java._trace +/.Modes3TypeScopeHint.xtendbin +/.Modes3UnitPropagationGenerator.xtendbin +/Modes3TypeScopeHint.java +/.Modes3ModelGenerator.xtendbin +/Modes3ModelGenerator.java +/Modes3UnitPropagationGenerator.java +/.CloseTrainsObjectiveHint.java._trace +/.TrainLocationsObjectiveHint.java._trace +/.MisalignedTurnoutObjectiveHint.java._trace +/.EndOfSidingObjectiveHint.java._trace diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/CloseTrainsObjectiveHint.java b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/CloseTrainsObjectiveHint.java new file mode 100644 index 00000000..babfa7e1 --- /dev/null +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/CloseTrainsObjectiveHint.java @@ -0,0 +1,279 @@ +package modes3.run; + +import com.google.common.base.Objects; +import com.google.common.collect.ImmutableList; +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic; +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace; +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Dimension; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilder; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronExtensionOperator; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; +import modes3.Modes3Package; +import modes3.queries.CloseTrains_step_2; +import modes3.queries.CloseTrains_step_3; +import modes3.queries.CloseTrains_step_4; +import modes3.queries.CloseTrains_step_5; +import modes3.queries.CloseTrains_step_6; +import modes3.queries.CloseTrains_step_7; +import org.eclipse.viatra.query.runtime.api.IPatternMatch; +import org.eclipse.xtext.xbase.lib.Extension; +import org.eclipse.xtext.xbase.lib.Functions.Function1; +import org.eclipse.xtext.xbase.lib.IterableExtensions; + +@SuppressWarnings("all") +public class CloseTrainsObjectiveHint extends CostObjectiveHint { + private final Type segmentType; + + private final Type trainType; + + public CloseTrainsObjectiveHint(@Extension final Ecore2Logic ecore2Logic, final Ecore2Logic_Trace ecore2LogicTrace) { + @Extension + final Modes3Package Modes3Package = modes3.Modes3Package.eINSTANCE; + this.segmentType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getSegment()); + this.trainType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getTrain()); + } + + @Override + public boolean isExact() { + return true; + } + + @Override + public PolyhedronExtensionOperator createPolyhedronExtensionOperator(final Map costElementMatchers) { + PolyhedronExtensionOperator _xblockexpression = null; + { + final CostElementMatchers step2 = costElementMatchers.get(CloseTrains_step_2.instance().getFullyQualifiedName()); + final CostElementMatchers step3 = costElementMatchers.get(CloseTrains_step_3.instance().getFullyQualifiedName()); + final CostElementMatchers step4 = costElementMatchers.get(CloseTrains_step_4.instance().getFullyQualifiedName()); + final CostElementMatchers step5 = costElementMatchers.get(CloseTrains_step_5.instance().getFullyQualifiedName()); + final CostElementMatchers step6 = costElementMatchers.get(CloseTrains_step_6.instance().getFullyQualifiedName()); + final CostElementMatchers step7 = costElementMatchers.get(CloseTrains_step_7.instance().getFullyQualifiedName()); + final PolyhedronExtensionOperator _function = (ExtendedLinearExpressionBuilderFactory it) -> { + final ExtendedLinearExpressionBuilder objectiveBuilder = it.createBuilder(); + ImmutableList _matches = step2.getMatches(); + for (final CostElementMatch m : _matches) { + { + final Dimension dimension = it.getDimension(m.getMatch()); + objectiveBuilder.add(step2.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m.isMulti(); + if (_isMulti) { + it.createBuilder().add(1, dimension).add((-1), this.trainType).build().assertEqualsTo(0); + } else { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final ImmutableList step3Matches = step3.getMatches(); + for (final CostElementMatch m_1 : step3Matches) { + { + final Dimension dimension = it.getDimension(m_1.getMatch()); + objectiveBuilder.add(step3.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_1.isMulti(); + boolean _not = (!_isMulti); + if (_not) { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_1.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final Function1 _function_1 = (CostElementMatch it_1) -> { + return step2.projectMayMatch(it_1.getMatch(), 2); + }; + Set>> _entrySet = IterableExtensions.groupBy(step3Matches, _function_1).entrySet(); + for (final Map.Entry> pair : _entrySet) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder(); + List _value = pair.getValue(); + for (final CostElementMatch m_2 : _value) { + multiplicityBuilder.add(1, m_2.getMatch()); + } + multiplicityBuilder.add((-1), pair.getKey()); + multiplicityBuilder.build().assertEqualsTo(0); + } + } + CloseTrainsObjectiveHint.boundLimit(it, step3Matches, 2, this.trainType, 1); + CloseTrainsObjectiveHint.boundLimit(it, step3Matches, 3, this.segmentType, 1); + final ImmutableList step4Matches = step4.getMatches(); + for (final CostElementMatch m_2 : step4Matches) { + { + final Dimension dimension = it.getDimension(m_2.getMatch()); + objectiveBuilder.add(step4.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_2.isMulti(); + boolean _not = (!_isMulti); + if (_not) { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_2.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final Function1 _function_2 = (CostElementMatch it_1) -> { + return step3.projectMayMatch(it_1.getMatch(), 2, 3); + }; + Set>> _entrySet_1 = IterableExtensions.groupBy(step4Matches, _function_2).entrySet(); + for (final Map.Entry> pair_1 : _entrySet_1) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder(); + List _value = pair_1.getValue(); + for (final CostElementMatch m_3 : _value) { + multiplicityBuilder.add(1, m_3.getMatch()); + } + multiplicityBuilder.add((-2), pair_1.getKey()); + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0)); + } + } + CloseTrainsObjectiveHint.boundLimit(it, step4Matches, 2, this.trainType, 2); + CloseTrainsObjectiveHint.boundLimit(it, step4Matches, 3, this.segmentType, 2); + CloseTrainsObjectiveHint.boundLimit(it, step4Matches, 4, this.segmentType, 2); + final ImmutableList step5Matches = step5.getMatches(); + for (final CostElementMatch m_3 : step5Matches) { + { + final Dimension dimension = it.getDimension(m_3.getMatch()); + objectiveBuilder.add(step5.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_3.isMulti(); + boolean _not = (!_isMulti); + if (_not) { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_3.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final Function1 _function_3 = (CostElementMatch it_1) -> { + return step4.projectMayMatch(it_1.getMatch(), 2, 3, 4); + }; + Set>> _entrySet_2 = IterableExtensions.groupBy(step5Matches, _function_3).entrySet(); + for (final Map.Entry> pair_2 : _entrySet_2) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder(); + List _value = pair_2.getValue(); + for (final CostElementMatch m_4 : _value) { + multiplicityBuilder.add(1, m_4.getMatch()); + } + multiplicityBuilder.add((-2), pair_2.getKey()); + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0)); + } + } + CloseTrainsObjectiveHint.boundLimit(it, step5Matches, 2, this.trainType, 4); + CloseTrainsObjectiveHint.boundLimit(it, step5Matches, 3, this.segmentType, 4); + CloseTrainsObjectiveHint.boundLimit(it, step5Matches, 4, this.segmentType, 4); + CloseTrainsObjectiveHint.boundLimit(it, step5Matches, 5, this.segmentType, 4); + final ImmutableList step6Matches = step6.getMatches(); + for (final CostElementMatch m_4 : step6Matches) { + { + final Dimension dimension = it.getDimension(m_4.getMatch()); + objectiveBuilder.add(step6.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_4.isMulti(); + if (_isMulti) { + Object _get = m_4.getMatch().get(3); + Object _get_1 = m_4.getMatch().get(5); + boolean _equals = Objects.equal(_get, _get_1); + if (_equals) { + it.createBuilder().add(2, m_4.getMatch()).add((-1), step5.projectMayMatch(m_4.getMatch(), 2, 3, 4, 5)).build().assertEqualsTo(0); + } else { + it.createBuilder().add(1, m_4.getMatch()).add((-1), step5.projectMayMatch(m_4.getMatch(), 2, 3, 4, 5)).build().assertEqualsTo(0); + } + } else { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_4.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + CloseTrainsObjectiveHint.boundLimit(it, step6Matches, 2, this.trainType, 2); + CloseTrainsObjectiveHint.boundLimit(it, step6Matches, 3, this.segmentType, 2); + CloseTrainsObjectiveHint.boundLimit(it, step6Matches, 4, this.segmentType, 2); + CloseTrainsObjectiveHint.boundLimit(it, step6Matches, 5, this.segmentType, 2); + final ImmutableList step7Matches = step7.getMatches(); + for (final CostElementMatch m_5 : step7Matches) { + { + final Dimension dimension = it.getDimension(m_5.getMatch()); + objectiveBuilder.add(step7.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_5.isMulti(); + boolean _not = (!_isMulti); + if (_not) { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_5.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final Function1 _function_4 = (CostElementMatch it_1) -> { + return step6.projectMayMatch(it_1.getMatch(), 2, 3, 4, 5); + }; + Set>> _entrySet_3 = IterableExtensions.groupBy(step7Matches, _function_4).entrySet(); + for (final Map.Entry> pair_3 : _entrySet_3) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder(); + List _value = pair_3.getValue(); + for (final CostElementMatch m_6 : _value) { + multiplicityBuilder.add(1, m_6.getMatch()); + } + multiplicityBuilder.add((-1), pair_3.getKey()); + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0)); + } + } + CloseTrainsObjectiveHint.boundLimit(it, step7Matches, 2, this.trainType, 2); + CloseTrainsObjectiveHint.boundLimit(it, step7Matches, 3, this.segmentType, 2); + CloseTrainsObjectiveHint.boundLimit(it, step7Matches, 4, this.segmentType, 2); + CloseTrainsObjectiveHint.boundLimit(it, step7Matches, 5, this.segmentType, 2); + CloseTrainsObjectiveHint.boundLimit(it, step7Matches, 6, this.trainType, 2); + this.buildWithBounds(objectiveBuilder); + }; + _xblockexpression = _function; + } + return _xblockexpression; + } + + private static void boundLimit(@Extension final ExtendedLinearExpressionBuilderFactory factory, final Collection matches, final int index, final Type type, final int count) { + final Function1 _function = (CostElementMatch it) -> { + return it.getMatch().get(index); + }; + Set>> _entrySet = IterableExtensions.groupBy(matches, _function).entrySet(); + for (final Map.Entry> pair : _entrySet) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = factory.createBuilder(); + List _value = pair.getValue(); + for (final CostElementMatch m : _value) { + multiplicityBuilder.add(1, m.getMatch()); + } + boolean _isMulti = CostElementMatchers.isMulti(pair.getKey()); + if (_isMulti) { + multiplicityBuilder.add((-count), type); + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0)); + } else { + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(count)); + } + } + } + } +} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/EndOfSidingObjectiveHint.java b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/EndOfSidingObjectiveHint.java new file mode 100644 index 00000000..77c513e1 --- /dev/null +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/EndOfSidingObjectiveHint.java @@ -0,0 +1,193 @@ +package modes3.run; + +import com.google.common.collect.ImmutableList; +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic; +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace; +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Dimension; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilder; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronExtensionOperator; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; +import modes3.Modes3Package; +import modes3.queries.EndOfSiding_step_2; +import modes3.queries.EndOfSiding_step_3; +import modes3.queries.EndOfSiding_step_4; +import modes3.queries.EndOfSiding_step_5; +import org.eclipse.viatra.query.runtime.api.IPatternMatch; +import org.eclipse.xtext.xbase.lib.Extension; +import org.eclipse.xtext.xbase.lib.Functions.Function1; +import org.eclipse.xtext.xbase.lib.IterableExtensions; + +@SuppressWarnings("all") +public class EndOfSidingObjectiveHint extends CostObjectiveHint { + private final Type segmentType; + + private final Type trainType; + + public EndOfSidingObjectiveHint(@Extension final Ecore2Logic ecore2Logic, final Ecore2Logic_Trace ecore2LogicTrace) { + @Extension + final Modes3Package Modes3Package = modes3.Modes3Package.eINSTANCE; + this.segmentType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getSegment()); + this.trainType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getTrain()); + } + + @Override + public boolean isExact() { + return true; + } + + @Override + public PolyhedronExtensionOperator createPolyhedronExtensionOperator(final Map costElementMatchers) { + PolyhedronExtensionOperator _xblockexpression = null; + { + final CostElementMatchers step2 = costElementMatchers.get(EndOfSiding_step_2.instance().getFullyQualifiedName()); + final CostElementMatchers step3 = costElementMatchers.get(EndOfSiding_step_3.instance().getFullyQualifiedName()); + final CostElementMatchers step4 = costElementMatchers.get(EndOfSiding_step_4.instance().getFullyQualifiedName()); + final CostElementMatchers step5 = costElementMatchers.get(EndOfSiding_step_5.instance().getFullyQualifiedName()); + final PolyhedronExtensionOperator _function = (ExtendedLinearExpressionBuilderFactory it) -> { + final ExtendedLinearExpressionBuilder objectiveBuilder = it.createBuilder(); + ImmutableList _matches = step2.getMatches(); + for (final CostElementMatch m : _matches) { + { + final Dimension dimension = it.getDimension(m.getMatch()); + objectiveBuilder.add(step2.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m.isMulti(); + if (_isMulti) { + it.createBuilder().add(1, dimension).add((-1), this.trainType).build().assertEqualsTo(0); + } else { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final ImmutableList step3Matches = step3.getMatches(); + for (final CostElementMatch m_1 : step3Matches) { + { + final Dimension dimension = it.getDimension(m_1.getMatch()); + objectiveBuilder.add(step3.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_1.isMulti(); + boolean _not = (!_isMulti); + if (_not) { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_1.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final Function1 _function_1 = (CostElementMatch it_1) -> { + return step2.projectMayMatch(it_1.getMatch(), 2); + }; + Set>> _entrySet = IterableExtensions.groupBy(step3Matches, _function_1).entrySet(); + for (final Map.Entry> pair : _entrySet) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder(); + List _value = pair.getValue(); + for (final CostElementMatch m_2 : _value) { + multiplicityBuilder.add(1, m_2.getMatch()); + } + multiplicityBuilder.add((-1), pair.getKey()); + multiplicityBuilder.build().assertEqualsTo(0); + } + } + EndOfSidingObjectiveHint.boundLimit(it, step3Matches, 2, this.trainType, 1); + EndOfSidingObjectiveHint.boundLimit(it, step3Matches, 3, this.segmentType, 1); + final ImmutableList step4Matches = step4.getMatches(); + for (final CostElementMatch m_2 : step4Matches) { + { + final Dimension dimension = it.getDimension(m_2.getMatch()); + objectiveBuilder.add(step4.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_2.isMulti(); + boolean _not = (!_isMulti); + if (_not) { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_2.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final Function1 _function_2 = (CostElementMatch it_1) -> { + return step3.projectMayMatch(it_1.getMatch(), 2, 3); + }; + Set>> _entrySet_1 = IterableExtensions.groupBy(step4Matches, _function_2).entrySet(); + for (final Map.Entry> pair_1 : _entrySet_1) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder(); + List _value = pair_1.getValue(); + for (final CostElementMatch m_3 : _value) { + multiplicityBuilder.add(1, m_3.getMatch()); + } + multiplicityBuilder.add((-2), pair_1.getKey()); + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0)); + } + } + EndOfSidingObjectiveHint.boundLimit(it, step4Matches, 2, this.trainType, 2); + EndOfSidingObjectiveHint.boundLimit(it, step4Matches, 3, this.segmentType, 2); + EndOfSidingObjectiveHint.boundLimit(it, step4Matches, 4, this.segmentType, 2); + final ImmutableList step5Matches = step5.getMatches(); + for (final CostElementMatch m_3 : step5Matches) { + { + final Dimension dimension = it.getDimension(m_3.getMatch()); + objectiveBuilder.add(step5.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_3.isMulti(); + boolean _not = (!_isMulti); + if (_not) { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_3.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + it.createBuilder().add(1, m_3.getMatch()).add((-1), step4.projectMayMatch(m_3.getMatch(), 2, 3, 4)).build().tightenUpperBound(Integer.valueOf(0)); + } + } + EndOfSidingObjectiveHint.boundLimit(it, step5Matches, 2, this.trainType, 1); + EndOfSidingObjectiveHint.boundLimit(it, step5Matches, 3, this.segmentType, 2); + EndOfSidingObjectiveHint.boundLimit(it, step5Matches, 4, this.segmentType, 1); + this.buildWithBounds(objectiveBuilder); + }; + _xblockexpression = _function; + } + return _xblockexpression; + } + + private static void boundLimit(@Extension final ExtendedLinearExpressionBuilderFactory factory, final Collection matches, final int index, final Type type, final int count) { + final Function1 _function = (CostElementMatch it) -> { + return it.getMatch().get(index); + }; + Set>> _entrySet = IterableExtensions.groupBy(matches, _function).entrySet(); + for (final Map.Entry> pair : _entrySet) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = factory.createBuilder(); + List _value = pair.getValue(); + for (final CostElementMatch m : _value) { + multiplicityBuilder.add(1, m.getMatch()); + } + boolean _isMulti = CostElementMatchers.isMulti(pair.getKey()); + if (_isMulti) { + multiplicityBuilder.add((-count), type); + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0)); + } else { + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(count)); + } + } + } + } +} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/MisalignedTurnoutObjectiveHint.java b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/MisalignedTurnoutObjectiveHint.java new file mode 100644 index 00000000..835a6559 --- /dev/null +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/MisalignedTurnoutObjectiveHint.java @@ -0,0 +1,195 @@ +package modes3.run; + +import com.google.common.collect.ImmutableList; +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic; +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace; +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Dimension; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilder; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronExtensionOperator; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; +import modes3.Modes3Package; +import modes3.queries.MisalignedTurnout_step_2; +import modes3.queries.MisalignedTurnout_step_3; +import modes3.queries.MisalignedTurnout_step_4; +import modes3.queries.MisalignedTurnout_step_5; +import org.eclipse.viatra.query.runtime.api.IPatternMatch; +import org.eclipse.xtext.xbase.lib.Extension; +import org.eclipse.xtext.xbase.lib.Functions.Function1; +import org.eclipse.xtext.xbase.lib.IterableExtensions; + +@SuppressWarnings("all") +public class MisalignedTurnoutObjectiveHint extends CostObjectiveHint { + private final Type segmentType; + + private final Type turnoutType; + + private final Type trainType; + + public MisalignedTurnoutObjectiveHint(@Extension final Ecore2Logic ecore2Logic, final Ecore2Logic_Trace ecore2LogicTrace) { + @Extension + final Modes3Package Modes3Package = modes3.Modes3Package.eINSTANCE; + this.segmentType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getSegment()); + this.turnoutType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getTurnout()); + this.trainType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getTrain()); + } + + @Override + public boolean isExact() { + return true; + } + + @Override + public PolyhedronExtensionOperator createPolyhedronExtensionOperator(final Map costElementMatchers) { + PolyhedronExtensionOperator _xblockexpression = null; + { + final CostElementMatchers step2 = costElementMatchers.get(MisalignedTurnout_step_2.instance().getFullyQualifiedName()); + final CostElementMatchers step3 = costElementMatchers.get(MisalignedTurnout_step_3.instance().getFullyQualifiedName()); + final CostElementMatchers step4 = costElementMatchers.get(MisalignedTurnout_step_4.instance().getFullyQualifiedName()); + final CostElementMatchers step5 = costElementMatchers.get(MisalignedTurnout_step_5.instance().getFullyQualifiedName()); + final PolyhedronExtensionOperator _function = (ExtendedLinearExpressionBuilderFactory it) -> { + final ExtendedLinearExpressionBuilder objectiveBuilder = it.createBuilder(); + ImmutableList _matches = step2.getMatches(); + for (final CostElementMatch m : _matches) { + { + final Dimension dimension = it.getDimension(m.getMatch()); + objectiveBuilder.add(step2.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m.isMulti(); + if (_isMulti) { + it.createBuilder().add(1, dimension).add((-1), this.turnoutType).build().assertEqualsTo(0); + } else { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final ImmutableList step3Matches = step3.getMatches(); + for (final CostElementMatch m_1 : step3Matches) { + { + final Dimension dimension = it.getDimension(m_1.getMatch()); + objectiveBuilder.add(step3.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_1.isMulti(); + boolean _not = (!_isMulti); + if (_not) { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_1.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final Function1 _function_1 = (CostElementMatch it_1) -> { + return step2.projectMayMatch(it_1.getMatch(), 2); + }; + Set>> _entrySet = IterableExtensions.groupBy(step3Matches, _function_1).entrySet(); + for (final Map.Entry> pair : _entrySet) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder(); + List _value = pair.getValue(); + for (final CostElementMatch m_2 : _value) { + multiplicityBuilder.add(1, m_2.getMatch()); + } + multiplicityBuilder.add((-1), pair.getKey()); + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0)); + } + } + MisalignedTurnoutObjectiveHint.boundLimit(it, step3Matches, 2, this.turnoutType, 1); + MisalignedTurnoutObjectiveHint.boundLimit(it, step3Matches, 3, this.segmentType, 2); + final ImmutableList step4Matches = step4.getMatches(); + for (final CostElementMatch m_2 : step4Matches) { + { + final Dimension dimension = it.getDimension(m_2.getMatch()); + objectiveBuilder.add(step4.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_2.isMulti(); + boolean _not = (!_isMulti); + if (_not) { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_2.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + it.createBuilder().add(1, m_2.getMatch()).add((-1), step3.projectMayMatch(m_2.getMatch(), 2, 3)).build().tightenUpperBound(Integer.valueOf(0)); + } + } + MisalignedTurnoutObjectiveHint.boundLimit(it, step4Matches, 2, this.turnoutType, 1); + MisalignedTurnoutObjectiveHint.boundLimit(it, step4Matches, 3, this.segmentType, 2); + final ImmutableList step5Matches = step5.getMatches(); + for (final CostElementMatch m_3 : step5Matches) { + { + final Dimension dimension = it.getDimension(m_3.getMatch()); + objectiveBuilder.add(step5.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_3.isMulti(); + boolean _not = (!_isMulti); + if (_not) { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_3.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final Function1 _function_2 = (CostElementMatch it_1) -> { + return step4.projectMayMatch(it_1.getMatch(), 2, 3); + }; + Set>> _entrySet_1 = IterableExtensions.groupBy(step5Matches, _function_2).entrySet(); + for (final Map.Entry> pair_1 : _entrySet_1) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder(); + List _value = pair_1.getValue(); + for (final CostElementMatch m_4 : _value) { + multiplicityBuilder.add(1, m_4.getMatch()); + } + multiplicityBuilder.add((-1), pair_1.getKey()); + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0)); + } + } + MisalignedTurnoutObjectiveHint.boundLimit(it, step5Matches, 2, this.turnoutType, 1); + MisalignedTurnoutObjectiveHint.boundLimit(it, step5Matches, 3, this.segmentType, 2); + MisalignedTurnoutObjectiveHint.boundLimit(it, step5Matches, 4, this.trainType, 2); + this.buildWithBounds(objectiveBuilder); + }; + _xblockexpression = _function; + } + return _xblockexpression; + } + + private static void boundLimit(@Extension final ExtendedLinearExpressionBuilderFactory factory, final Collection matches, final int index, final Type type, final int count) { + final Function1 _function = (CostElementMatch it) -> { + return it.getMatch().get(index); + }; + Set>> _entrySet = IterableExtensions.groupBy(matches, _function).entrySet(); + for (final Map.Entry> pair : _entrySet) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = factory.createBuilder(); + List _value = pair.getValue(); + for (final CostElementMatch m : _value) { + multiplicityBuilder.add(1, m.getMatch()); + } + boolean _isMulti = CostElementMatchers.isMulti(pair.getKey()); + if (_isMulti) { + multiplicityBuilder.add((-count), type); + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0)); + } else { + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(count)); + } + } + } + } +} diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/Modes3ModelGenerator.java b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/Modes3ModelGenerator.java index f32a7172..16db7053 100644 --- a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/Modes3ModelGenerator.java +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/Modes3ModelGenerator.java @@ -13,6 +13,7 @@ import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.Ecore2logic import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.Ecore2logicannotationsPackage; import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.InverseRelationAssertion; import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel; +import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicModelInterpretation; import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicProblemBuilder; import hu.bme.mit.inf.dslreasoner.logic.model.builder.SolutionScope; import hu.bme.mit.inf.dslreasoner.logic.model.builder.TracedOutput; @@ -32,6 +33,7 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem; import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicproblemPackage; import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicResult; import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult; +import hu.bme.mit.inf.dslreasoner.logic2ecore.Logic2Ecore; import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2Logic; import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2LogicConfiguration; import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2LogicTrace; @@ -50,10 +52,15 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.par import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.RelationLink; import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretation2Gml; import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualisation; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.CostObjectiveConfiguration; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.CostObjectiveElementConfiguration; import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.DebugConfiguration; import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.StateCoderStrategy; import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasoner; import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.PartialModelAsLogicInterpretation; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveKind; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveThreshold; import hu.bme.mit.inf.dslreasoner.visualisation.pi2graphviz.GraphvizVisualiser; import hu.bme.mit.inf.dslreasoner.workspace.FileSystemWorkspace; import java.util.Collections; @@ -64,10 +71,31 @@ import java.util.function.Predicate; import modes3.Modes3Factory; import modes3.Modes3ModelRoot; import modes3.Modes3Package; +import modes3.queries.CloseTrains_step_2; +import modes3.queries.CloseTrains_step_3; +import modes3.queries.CloseTrains_step_4; +import modes3.queries.CloseTrains_step_5; +import modes3.queries.CloseTrains_step_6; +import modes3.queries.CloseTrains_step_7; +import modes3.queries.EndOfSiding_step_2; +import modes3.queries.EndOfSiding_step_3; +import modes3.queries.EndOfSiding_step_4; +import modes3.queries.EndOfSiding_step_5; +import modes3.queries.MisalignedTurnout_step_2; +import modes3.queries.MisalignedTurnout_step_3; +import modes3.queries.MisalignedTurnout_step_4; +import modes3.queries.MisalignedTurnout_step_5; import modes3.queries.Modes3Queries; +import modes3.queries.TrainLocations_step_2; +import modes3.queries.TrainLocations_step_3; +import modes3.run.CloseTrainsObjectiveHint; +import modes3.run.EndOfSidingObjectiveHint; +import modes3.run.MisalignedTurnoutObjectiveHint; import modes3.run.Modes3TypeScopeHint; import modes3.run.Modes3UnitPropagationGenerator; +import modes3.run.TrainLocationsObjectiveHint; import org.eclipse.emf.common.util.EList; +import org.eclipse.emf.common.util.TreeIterator; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; @@ -102,6 +130,10 @@ public class Modes3ModelGenerator { private enum MonitoringQuery { closeTrains, + trainLocations, + + endOfSiding, + misalignedTurnout; } @@ -183,8 +215,9 @@ public class Modes3ModelGenerator { ObjectExtensions.>operator_doubleArrow( it_1.minNewElementsByType, _function_4); final Procedure1> _function_5 = (Map it_2) -> { - it_2.put(this.ecore2Logic.TypeofEClass(metamodelLogic.getTrace(), Modes3Package.eINSTANCE.getTrain()), Integer.valueOf(5)); - it_2.put(this.ecore2Logic.TypeofEClass(metamodelLogic.getTrace(), Modes3Package.eINSTANCE.getTurnout()), Integer.valueOf(5)); + it_2.put(this.ecore2Logic.TypeofEClass(metamodelLogic.getTrace(), Modes3Package.eINSTANCE.getTrain()), Integer.valueOf((this.modelSize / 5))); + it_2.put(this.ecore2Logic.TypeofEClass(metamodelLogic.getTrace(), Modes3Package.eINSTANCE.getTurnout()), Integer.valueOf((this.modelSize / 5))); + it_2.put(this.ecore2Logic.TypeofEClass(metamodelLogic.getTrace(), Modes3Package.eINSTANCE.getSimpleSegment()), Integer.valueOf(((3 * this.modelSize) / 5))); }; ObjectExtensions.>operator_doubleArrow( it_1.maxNewElementsByType, _function_5); @@ -196,7 +229,9 @@ public class Modes3ModelGenerator { }; ObjectExtensions.operator_doubleArrow( it.solutionScope, _function_4); - it.scopeWeight = 5; + CostObjectiveConfiguration _objective = this.getObjective(this.ecore2Logic, metamodelLogic.getTrace()); + it.costObjectives.add(_objective); + it.scopeWeight = 6; it.nameNewElements = false; it.typeInferenceMethod = TypeInferenceMethod.PreliminaryAnalysis; it.stateCoderStrategy = StateCoderStrategy.PairwiseNeighbourhood; @@ -224,80 +259,103 @@ public class Modes3ModelGenerator { URI _xifexpression = null; if ((solution instanceof ModelResult)) { InputOutput.println("Saving generated solutions"); - final EList representations = ((ModelResult)solution).getRepresentation(); - int _size = representations.size(); + final Logic2Ecore logic2Ecore = new Logic2Ecore(this.ecore2Logic); + final List interpretations = this.solver.getInterpretations(((ModelResult)solution)); + int _size = interpretations.size(); ExclusiveRange _doubleDotLessThan = new ExclusiveRange(0, _size, true); for (final Integer representationIndex : _doubleDotLessThan) { { - final Object representation = representations.get((representationIndex).intValue()); + final LogicModelInterpretation interpretation = interpretations.get((representationIndex).intValue()); final int representationNumber = ((representationIndex).intValue() + 1); - if ((representation instanceof PartialInterpretation)) { + if ((interpretation instanceof PartialModelAsLogicInterpretation)) { + final PartialInterpretation representation = ((PartialModelAsLogicInterpretation)interpretation).getPartialInterpretation(); StringConcatenation _builder_1 = new StringConcatenation(); _builder_1.append("solution"); _builder_1.append(representationNumber); _builder_1.append(".partialinterpretation"); - workspace.writeModel(((EObject)representation), _builder_1.toString()); + workspace.writeModel(representation, _builder_1.toString()); final PartialInterpretation2Gml partialInterpretation2GML = new PartialInterpretation2Gml(); - final String gml = partialInterpretation2GML.transform(((PartialInterpretation)representation)); + final String gml = partialInterpretation2GML.transform(representation); StringConcatenation _builder_2 = new StringConcatenation(); _builder_2.append("solution"); _builder_2.append(representationNumber); _builder_2.append(".gml"); workspace.writeText(_builder_2.toString(), gml); - int _size_1 = ((PartialInterpretation)representation).getNewElements().size(); - boolean _lessThan = (_size_1 < 160); - if (_lessThan) { - if ((representation instanceof PartialInterpretation)) { - final Function1 _function_3 = (Type it) -> { + final EObject model = logic2Ecore.transformInterpretation(interpretation, metamodelLogic.getTrace()); + final TreeIterator iterator = model.eAllContents(); + int id = 0; + while (iterator.hasNext()) { + { + final EObject obj = iterator.next(); + final Function1 _function_3 = (EAttribute it) -> { String _name_2 = it.getName(); - return Boolean.valueOf(Objects.equal(_name_2, "Modes3ModelRoot class DefinedPart")); + return Boolean.valueOf(Objects.equal(_name_2, "id")); }; - Type _findFirst = IterableExtensions.findFirst(((PartialInterpretation)representation).getProblem().getTypes(), _function_3); - final TypeDefinition rootType = ((TypeDefinition) _findFirst); - final Function1 _function_4 = (PartialComplexTypeInterpretation it) -> { - String _name_2 = it.getInterpretationOf().getName(); - return Boolean.valueOf(Objects.equal(_name_2, "Modes3ModelRoot class")); - }; - final PartialComplexTypeInterpretation rootIntepretation = IterableExtensions.findFirst(Iterables.filter(((PartialInterpretation)representation).getPartialtypeinterpratation(), - PartialComplexTypeInterpretation.class), _function_4); - rootIntepretation.getElements().removeAll(rootType.getElements()); - ((PartialInterpretation)representation).getProblem().getElements().removeAll(rootType.getElements()); - EList _partialrelationinterpretation = ((PartialInterpretation)representation).getPartialrelationinterpretation(); - for (final PartialRelationInterpretation relationInterpretation : _partialrelationinterpretation) { - final Predicate _function_5 = (RelationLink link) -> { - boolean _xifexpression_1 = false; - if ((link instanceof BinaryElementRelationLink)) { - _xifexpression_1 = (rootType.getElements().contains(((BinaryElementRelationLink)link).getParam1()) || rootType.getElements().contains(((BinaryElementRelationLink)link).getParam2())); - } else { - _xifexpression_1 = false; - } - return _xifexpression_1; - }; - relationInterpretation.getRelationlinks().removeIf(_function_5); + final EAttribute idFeature = IterableExtensions.findFirst(obj.eClass().getEAllAttributes(), _function_3); + if ((idFeature != null)) { + obj.eSet(idFeature, Integer.valueOf(id)); + id++; } - rootType.getElements().clear(); } + } + StringConcatenation _builder_3 = new StringConcatenation(); + _builder_3.append("solution"); + _builder_3.append(representationNumber); + _builder_3.append(".modes3"); + workspace.writeModel(model, _builder_3.toString()); + int _size_1 = representation.getNewElements().size(); + boolean _lessThan = (_size_1 < 160); + if (_lessThan) { + final Function1 _function_3 = (Type it) -> { + String _name_2 = it.getName(); + return Boolean.valueOf(Objects.equal(_name_2, "Modes3ModelRoot class DefinedPart")); + }; + Type _findFirst = IterableExtensions.findFirst(representation.getProblem().getTypes(), _function_3); + final TypeDefinition rootType = ((TypeDefinition) _findFirst); + final Function1 _function_4 = (PartialComplexTypeInterpretation it) -> { + String _name_2 = it.getInterpretationOf().getName(); + return Boolean.valueOf(Objects.equal(_name_2, "Modes3ModelRoot class")); + }; + final PartialComplexTypeInterpretation rootIntepretation = IterableExtensions.findFirst(Iterables.filter(representation.getPartialtypeinterpratation(), + PartialComplexTypeInterpretation.class), _function_4); + rootIntepretation.getElements().removeAll(rootType.getElements()); + representation.getProblem().getElements().removeAll(rootType.getElements()); + EList _partialrelationinterpretation = representation.getPartialrelationinterpretation(); + for (final PartialRelationInterpretation relationInterpretation : _partialrelationinterpretation) { + final Predicate _function_5 = (RelationLink link) -> { + boolean _xifexpression_1 = false; + if ((link instanceof BinaryElementRelationLink)) { + _xifexpression_1 = (rootType.getElements().contains(((BinaryElementRelationLink)link).getParam1()) || + rootType.getElements().contains(((BinaryElementRelationLink)link).getParam2())); + } else { + _xifexpression_1 = false; + } + return _xifexpression_1; + }; + relationInterpretation.getRelationlinks().removeIf(_function_5); + } + rootType.getElements().clear(); final GraphvizVisualiser visualiser = new GraphvizVisualiser(); - final PartialInterpretationVisualisation visualisation = visualiser.visualiseConcretization(((PartialInterpretation)representation)); - StringConcatenation _builder_3 = new StringConcatenation(); - _builder_3.append("solution"); - _builder_3.append(representationNumber); - _builder_3.append(".png"); - visualisation.writeToFile(workspace, _builder_3.toString()); + final PartialInterpretationVisualisation visualisation = visualiser.visualiseConcretization(representation); + StringConcatenation _builder_4 = new StringConcatenation(); + _builder_4.append("solution"); + _builder_4.append(representationNumber); + _builder_4.append(".png"); + visualisation.writeToFile(workspace, _builder_4.toString()); } } else { - StringConcatenation _builder_4 = new StringConcatenation(); - _builder_4.append("solution"); - _builder_4.append(representationNumber); - _builder_4.append(".txt"); - workspace.writeText(_builder_4.toString(), representation.toString()); + StringConcatenation _builder_5 = new StringConcatenation(); + _builder_5.append("solution"); + _builder_5.append(representationNumber); + _builder_5.append(".txt"); + workspace.writeText(_builder_5.toString(), interpretation.toString()); } } } } else { URI _xblockexpression_1 = null; { - InputOutput.println("Failed to solver problem"); + InputOutput.println("Failed to solve problem"); final LogicProblem partial = logic.getOutput(); _xblockexpression_1 = workspace.writeModel(partial, "solution.partialinterpretation"); } @@ -354,6 +412,153 @@ public class Modes3ModelGenerator { return _xblockexpression; } + public CostObjectiveConfiguration getObjective(final Ecore2Logic ecore2Logic, final Ecore2Logic_Trace ecore2LogicTrace) { + CostObjectiveConfiguration _costObjectiveConfiguration = new CostObjectiveConfiguration(); + final Procedure1 _function = (CostObjectiveConfiguration it) -> { + final Modes3ModelGenerator.MonitoringQuery monitoringQuery = this.monitoringQuery; + if (monitoringQuery != null) { + switch (monitoringQuery) { + case closeTrains: + CostObjectiveElementConfiguration _costObjectiveElementConfiguration = new CostObjectiveElementConfiguration(); + final Procedure1 _function_1 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = CloseTrains_step_2.instance().getFullyQualifiedName(); + it_1.weight = ((14 + 53) + 11); + }; + CostObjectiveElementConfiguration _doubleArrow = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration, _function_1); + it.elements.add(_doubleArrow); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_1 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_2 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = CloseTrains_step_3.instance().getFullyQualifiedName(); + it_1.weight = (21 + 14); + }; + CostObjectiveElementConfiguration _doubleArrow_1 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_1, _function_2); + it.elements.add(_doubleArrow_1); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_2 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_3 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = CloseTrains_step_4.instance().getFullyQualifiedName(); + it_1.weight = (((14 + 44) + 14) + 9); + }; + CostObjectiveElementConfiguration _doubleArrow_2 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_2, _function_3); + it.elements.add(_doubleArrow_2); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_3 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_4 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = CloseTrains_step_5.instance().getFullyQualifiedName(); + it_1.weight = ((14 + 41) + 11); + }; + CostObjectiveElementConfiguration _doubleArrow_3 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_3, _function_4); + it.elements.add(_doubleArrow_3); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_4 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_5 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = CloseTrains_step_6.instance().getFullyQualifiedName(); + it_1.weight = 27; + }; + CostObjectiveElementConfiguration _doubleArrow_4 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_4, _function_5); + it.elements.add(_doubleArrow_4); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_5 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_6 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = CloseTrains_step_7.instance().getFullyQualifiedName(); + it_1.weight = 48; + }; + CostObjectiveElementConfiguration _doubleArrow_5 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_5, _function_6); + it.elements.add(_doubleArrow_5); + CloseTrainsObjectiveHint _closeTrainsObjectiveHint = new CloseTrainsObjectiveHint(ecore2Logic, ecore2LogicTrace); + it.hint = _closeTrainsObjectiveHint; + break; + case trainLocations: + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_6 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_7 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = TrainLocations_step_2.instance().getFullyQualifiedName(); + it_1.weight = ((14 + 53) + 11); + }; + CostObjectiveElementConfiguration _doubleArrow_6 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_6, _function_7); + it.elements.add(_doubleArrow_6); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_7 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_8 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = TrainLocations_step_3.instance().getFullyQualifiedName(); + it_1.weight = 48; + }; + CostObjectiveElementConfiguration _doubleArrow_7 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_7, _function_8); + it.elements.add(_doubleArrow_7); + TrainLocationsObjectiveHint _trainLocationsObjectiveHint = new TrainLocationsObjectiveHint(ecore2Logic, ecore2LogicTrace); + it.hint = _trainLocationsObjectiveHint; + break; + case misalignedTurnout: + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_8 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_9 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = MisalignedTurnout_step_2.instance().getFullyQualifiedName(); + it_1.weight = ((14 + 53) + 11); + }; + CostObjectiveElementConfiguration _doubleArrow_8 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_8, _function_9); + it.elements.add(_doubleArrow_8); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_9 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_10 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = MisalignedTurnout_step_3.instance().getFullyQualifiedName(); + it_1.weight = 108; + }; + CostObjectiveElementConfiguration _doubleArrow_9 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_9, _function_10); + it.elements.add(_doubleArrow_9); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_10 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_11 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = MisalignedTurnout_step_4.instance().getFullyQualifiedName(); + it_1.weight = 27; + }; + CostObjectiveElementConfiguration _doubleArrow_10 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_10, _function_11); + it.elements.add(_doubleArrow_10); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_11 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_12 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = MisalignedTurnout_step_5.instance().getFullyQualifiedName(); + it_1.weight = 48; + }; + CostObjectiveElementConfiguration _doubleArrow_11 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_11, _function_12); + it.elements.add(_doubleArrow_11); + MisalignedTurnoutObjectiveHint _misalignedTurnoutObjectiveHint = new MisalignedTurnoutObjectiveHint(ecore2Logic, ecore2LogicTrace); + it.hint = _misalignedTurnoutObjectiveHint; + break; + case endOfSiding: + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_12 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_13 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = EndOfSiding_step_2.instance().getFullyQualifiedName(); + it_1.weight = ((14 + 53) + 11); + }; + CostObjectiveElementConfiguration _doubleArrow_12 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_12, _function_13); + it.elements.add(_doubleArrow_12); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_13 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_14 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = EndOfSiding_step_3.instance().getFullyQualifiedName(); + it_1.weight = (21 + 14); + }; + CostObjectiveElementConfiguration _doubleArrow_13 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_13, _function_14); + it.elements.add(_doubleArrow_13); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_14 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_15 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = EndOfSiding_step_4.instance().getFullyQualifiedName(); + it_1.weight = (((((((14 + 35) + 21) + 15) + 14) + 21) + 15) + 11); + }; + CostObjectiveElementConfiguration _doubleArrow_14 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_14, _function_15); + it.elements.add(_doubleArrow_14); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_15 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_16 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = EndOfSiding_step_5.instance().getFullyQualifiedName(); + it_1.weight = 48; + }; + CostObjectiveElementConfiguration _doubleArrow_15 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_15, _function_16); + it.elements.add(_doubleArrow_15); + EndOfSidingObjectiveHint _endOfSidingObjectiveHint = new EndOfSidingObjectiveHint(ecore2Logic, ecore2LogicTrace); + it.hint = _endOfSidingObjectiveHint; + break; + default: + throw new IllegalArgumentException(("Unknown monitoring query: " + this.monitoringQuery)); + } + } else { + throw new IllegalArgumentException(("Unknown monitoring query: " + this.monitoringQuery)); + } + it.kind = ObjectiveKind.HIGHER_IS_BETTER; + it.threshold = ObjectiveThreshold.NO_THRESHOLD; + it.findExtremum = true; + }; + return ObjectExtensions.operator_doubleArrow(_costObjectiveConfiguration, _function); + } + public static Object init() { Object _xblockexpression = null; { diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/TrainLocationsObjectiveHint.java b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/TrainLocationsObjectiveHint.java new file mode 100644 index 00000000..570f9deb --- /dev/null +++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/TrainLocationsObjectiveHint.java @@ -0,0 +1,117 @@ +package modes3.run; + +import com.google.common.collect.ImmutableList; +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic; +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace; +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Dimension; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilder; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronExtensionOperator; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; +import modes3.Modes3Package; +import modes3.queries.TrainLocations_step_2; +import modes3.queries.TrainLocations_step_3; +import org.eclipse.xtext.xbase.lib.Extension; +import org.eclipse.xtext.xbase.lib.Functions.Function1; +import org.eclipse.xtext.xbase.lib.IterableExtensions; + +@SuppressWarnings("all") +public class TrainLocationsObjectiveHint extends CostObjectiveHint { + private final Type segmentType; + + private final Type trainType; + + public TrainLocationsObjectiveHint(@Extension final Ecore2Logic ecore2Logic, final Ecore2Logic_Trace ecore2LogicTrace) { + @Extension + final Modes3Package Modes3Package = modes3.Modes3Package.eINSTANCE; + this.segmentType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getSegment()); + this.trainType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getTrain()); + } + + @Override + public boolean isExact() { + return true; + } + + @Override + public PolyhedronExtensionOperator createPolyhedronExtensionOperator(final Map costElementMatchers) { + PolyhedronExtensionOperator _xblockexpression = null; + { + final CostElementMatchers step2 = costElementMatchers.get(TrainLocations_step_2.instance().getFullyQualifiedName()); + final CostElementMatchers step3 = costElementMatchers.get(TrainLocations_step_3.instance().getFullyQualifiedName()); + final PolyhedronExtensionOperator _function = (ExtendedLinearExpressionBuilderFactory it) -> { + final ExtendedLinearExpressionBuilder objectiveBuilder = it.createBuilder(); + ImmutableList _matches = step2.getMatches(); + for (final CostElementMatch m : _matches) { + { + final Dimension dimension = it.getDimension(m.getMatch()); + objectiveBuilder.add(step2.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m.isMulti(); + if (_isMulti) { + it.createBuilder().add(1, dimension).add((-1), this.trainType).build().assertEqualsTo(0); + } else { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final ImmutableList step3Matches = step3.getMatches(); + for (final CostElementMatch m_1 : step3Matches) { + { + final Dimension dimension = it.getDimension(m_1.getMatch()); + objectiveBuilder.add(step3.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_1.isMulti(); + boolean _not = (!_isMulti); + if (_not) { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_1.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + TrainLocationsObjectiveHint.boundLimit(it, step3Matches, 2, this.trainType, 1); + TrainLocationsObjectiveHint.boundLimit(it, step3Matches, 3, this.segmentType, 1); + this.buildWithBounds(objectiveBuilder); + }; + _xblockexpression = _function; + } + return _xblockexpression; + } + + private static void boundLimit(@Extension final ExtendedLinearExpressionBuilderFactory factory, final Collection matches, final int index, final Type type, final int count) { + final Function1 _function = (CostElementMatch it) -> { + return it.getMatch().get(index); + }; + Set>> _entrySet = IterableExtensions.groupBy(matches, _function).entrySet(); + for (final Map.Entry> pair : _entrySet) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = factory.createBuilder(); + List _value = pair.getValue(); + for (final CostElementMatch m : _value) { + multiplicityBuilder.add(1, m.getMatch()); + } + boolean _isMulti = CostElementMatchers.isMulti(pair.getKey()); + if (_isMulti) { + multiplicityBuilder.add((-count), type); + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0)); + } else { + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(count)); + } + } + } + } +} diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.alloyexamples/META-INF/MANIFEST.MF b/Domains/hu.bme.mit.inf.dslreasoner.domains.alloyexamples/META-INF/MANIFEST.MF index 5fb85170..cc71bd06 100644 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.alloyexamples/META-INF/MANIFEST.MF +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.alloyexamples/META-INF/MANIFEST.MF @@ -15,7 +15,6 @@ Require-Bundle: org.eclipse.viatra.addon.querybasedfeatures.runtime, org.eclipse.viatra.query.runtime, org.eclipse.core.runtime, org.eclipse.emf.ecore;visibility:=reexport, - org.eclipse.emf.emfstore.common, com.google.guava, org.eclipse.xtext.xbase.lib, org.eclipse.xtend.lib, 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 b9da0f0b..ec1557e8 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 @@ -8,7 +8,8 @@ Export-Package: hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra, hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval, hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval.aggregators, hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns, - hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.queries + hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.queries, + hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules Require-Bundle: hu.bme.mit.inf.dslreasoner.logic.model;bundle-version="1.0.0", hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage;bundle-version="1.0.0", hu.bme.mit.inf.dslreasoner.ecore2logic;bundle-version="1.0.0", 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 deleted file mode 100644 index 3bcd9116..00000000 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationMethodProvider.xtend +++ /dev/null @@ -1,226 +0,0 @@ -package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra - -import com.google.common.collect.ImmutableMap -import com.google.common.collect.ImmutableSet -import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel -import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem -import hu.bme.mit.inf.dslreasoner.viatra2logic.viatra2logicannotations.TransfomedViatraQuery -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.CbcPolyhedronSolver -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.MultiplicityGoalConstraintCalculator -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronScopePropagator -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.RelationConstraintCalculator -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagator -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.TypeHierarchyScopePropagator -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Z3PolyhedronSolver -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.GeneratedPatterns -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.ModalPatternQueries -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternProvider -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.UnitPropagationPatternGenerator -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules.GoalConstraintProvider -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules.RefinementRuleProvider -import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation -import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace -import java.util.Collection -import java.util.List -import java.util.Map -import java.util.Set -import org.eclipse.viatra.query.runtime.api.GenericQueryGroup -import org.eclipse.viatra.query.runtime.api.IPatternMatch -import org.eclipse.viatra.query.runtime.api.IQuerySpecification -import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine -import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher -import org.eclipse.viatra.query.runtime.emf.EMFScope -import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint -import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery -import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRule -import org.eclipse.xtend.lib.annotations.Data - -class ModelGenerationStatistics { - public var long transformationExecutionTime = 0 - - synchronized def addExecutionTime(long amount) { - transformationExecutionTime += amount - } - - public var long scopePropagationTime = 0 - - synchronized def addScopePropagationTime(long amount) { - scopePropagationTime += amount - } - - public var long mustRelationPropagationTime = 0 - - synchronized def addMustRelationPropagationTime(long amount) { - mustRelationPropagationTime += amount - } - - public var long preliminaryTypeAnalisisTime = 0 - - public var int decisionsTried = 0 - - synchronized def incrementDecisionCount() { - decisionsTried++ - } - - public var int transformationInvocations - - synchronized def incrementTransformationCount() { - transformationInvocations++ - } - - public var int scopePropagatorInvocations - - synchronized def incrementScopePropagationCount() { - scopePropagatorInvocations++ - } - - public var int scopePropagatorSolverInvocations - - synchronized def incrementScopePropagationSolverCount() { - scopePropagatorSolverInvocations++ - } -} - -@Data class ModelGenerationMethod { - ModelGenerationStatistics statistics - - Collection> objectRefinementRules - Collection> relationRefinementRules - - List unfinishedMultiplicities - - Collection>> unfinishedWF - - Collection>> invalidWF - - Map>> mustUnitPropagationPreconditions - Map>> currentUnitPropagationPreconditions - - Map modalRelationQueries - - Collection>> allPatterns -} - -enum TypeInferenceMethod { - Generic, - PreliminaryAnalysis -} - -class ModelGenerationMethodProvider { - val PatternProvider patternProvider = new PatternProvider - val RefinementRuleProvider refinementRuleProvider = new RefinementRuleProvider - val GoalConstraintProvider goalConstraintProvider = new GoalConstraintProvider - val relationConstraintCalculator = new RelationConstraintCalculator - - def ModelGenerationMethod createModelGenerationMethod( - LogicProblem logicProblem, - PartialInterpretation emptySolution, - ReasonerWorkspace workspace, - boolean nameNewElements, - TypeInferenceMethod typeInferenceMethod, - boolean calculateObjectCreationCosts, - ScopePropagatorStrategy scopePropagatorStrategy, - Collection hints, - Collection unitPropagationPatternGenerators, - DocumentationLevel debugLevel - ) { - val statistics = new ModelGenerationStatistics - val writeFiles = (debugLevel === DocumentationLevel.NORMAL || debugLevel === DocumentationLevel.FULL) - - val Set existingQueries = logicProblem.relations.map[annotations].flatten.filter(TransfomedViatraQuery). - map[it.patternPQuery as PQuery].toSet - - val relationConstraints = relationConstraintCalculator.calculateRelationConstraints(logicProblem) - val queries = patternProvider.generateQueries(logicProblem, emptySolution, statistics, existingQueries, - workspace, typeInferenceMethod, scopePropagatorStrategy, relationConstraints, hints, - unitPropagationPatternGenerators, writeFiles) - - val scopePropagator = createScopePropagator(scopePropagatorStrategy, emptySolution, hints, queries, statistics) - scopePropagator.propagateAllScopeConstraints - val unitRulePropagator = refinementRuleProvider.createUnitPrulePropagator(logicProblem, emptySolution, - queries, scopePropagator, statistics) - val objectRefinementRules = refinementRuleProvider.createObjectRefinementRules(logicProblem, emptySolution, - queries, unitRulePropagator, nameNewElements, statistics) - val relationRefinementRules = refinementRuleProvider.createRelationRefinementRules(queries, unitRulePropagator, - statistics) - - val unfinishedMultiplicities = goalConstraintProvider.getUnfinishedMultiplicityQueries(logicProblem, queries, - calculateObjectCreationCosts) - - val unfinishedWF = queries.getUnfinishedWFQueries.values - - val modalRelationQueriesBuilder = ImmutableMap.builder - for (entry : queries.modalRelationQueries.entrySet) { - val annotation = entry.key.annotations.filter(TransfomedViatraQuery).head - if (annotation !== null) { - modalRelationQueriesBuilder.put(annotation.patternFullyQualifiedName, entry.value) - } - } - val modalRelationQueries = modalRelationQueriesBuilder.build - - val invalidWF = queries.getInvalidWFQueries.values - - val mustUnitPropagationPreconditions = queries.getMustUnitPropagationPreconditionPatterns - val currentUnitPropagationPreconditions = queries.getCurrentUnitPropagationPreconditionPatterns - - val queriesToPrepare = ImmutableSet.builder.addAll(queries.refineObjectQueries.values).addAll( - queries.refineTypeQueries.values).addAll(queries.refineRelationQueries.values).addAll(queries. - multiplicityConstraintQueries.values.flatMap[allQueries]).addAll(queries.unfinishedWFQueries.values).addAll( - queries.invalidWFQueries.values).addAll(queries.mustUnitPropagationPreconditionPatterns.values).addAll( - queries.currentUnitPropagationPreconditionPatterns.values).add(queries.hasElementInContainmentQuery).build - val queryEngine = ViatraQueryEngine.on(new EMFScope(emptySolution)) - GenericQueryGroup.of(queriesToPrepare).prepare(queryEngine) - - return new ModelGenerationMethod( - statistics, - objectRefinementRules.values, - relationRefinementRules.values, - unfinishedMultiplicities, - unfinishedWF, - invalidWF, - mustUnitPropagationPreconditions, - currentUnitPropagationPreconditions, - modalRelationQueries, - queries.allQueries - ) - } - - private def createScopePropagator(ScopePropagatorStrategy scopePropagatorStrategy, - PartialInterpretation emptySolution, Collection hints, GeneratedPatterns queries, - ModelGenerationStatistics statistics) { - if (!hints.empty && !(scopePropagatorStrategy instanceof ScopePropagatorStrategy.Polyhedral)) { - throw new IllegalArgumentException("Only the Polyhedral scope propagator strategy can use hints.") - } - switch (scopePropagatorStrategy) { - case ScopePropagatorStrategy.None, - case ScopePropagatorStrategy.Basic: - new ScopePropagator(emptySolution, statistics) - case ScopePropagatorStrategy.BasicTypeHierarchy: - new TypeHierarchyScopePropagator(emptySolution, statistics) - ScopePropagatorStrategy.Polyhedral: { - val types = queries.refineObjectQueries.keySet.map[newType].toSet - val allPatternsByName = queries.allQueries.toMap[fullyQualifiedName] - val solver = switch (scopePropagatorStrategy.solver) { - case Z3Integer: - new Z3PolyhedronSolver(false, scopePropagatorStrategy.timeoutSeconds) - case Z3Real: - new Z3PolyhedronSolver(true, scopePropagatorStrategy.timeoutSeconds) - case Cbc: - new CbcPolyhedronSolver(false, scopePropagatorStrategy.timeoutSeconds, true) - case Clp: - new CbcPolyhedronSolver(true, scopePropagatorStrategy.timeoutSeconds, true) - default: - throw new IllegalArgumentException("Unknown polyhedron solver: " + - scopePropagatorStrategy.solver) - } - new PolyhedronScopePropagator(emptySolution, statistics, types, queries.multiplicityConstraintQueries, - queries.hasElementInContainmentQuery, allPatternsByName, hints, solver, - scopePropagatorStrategy.requiresUpperBoundIndexing, scopePropagatorStrategy.updateHeuristic) - } - default: - throw new IllegalArgumentException("Unknown scope propagator strategy: " + scopePropagatorStrategy) - } - } -} diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationStatistics.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationStatistics.xtend new file mode 100644 index 00000000..bd5bf807 --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationStatistics.xtend @@ -0,0 +1,47 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra + +class ModelGenerationStatistics { + public var long transformationExecutionTime = 0 + + synchronized def addExecutionTime(long amount) { + transformationExecutionTime += amount + } + + public var long scopePropagationTime = 0 + + synchronized def addScopePropagationTime(long amount) { + scopePropagationTime += amount + } + + public var long mustRelationPropagationTime = 0 + + synchronized def addMustRelationPropagationTime(long amount) { + mustRelationPropagationTime += amount + } + + public var long preliminaryTypeAnalisisTime = 0 + + public var int decisionsTried = 0 + + synchronized def incrementDecisionCount() { + decisionsTried++ + } + + public var int transformationInvocations + + synchronized def incrementTransformationCount() { + transformationInvocations++ + } + + public var int scopePropagatorInvocations + + synchronized def incrementScopePropagationCount() { + scopePropagatorInvocations++ + } + + public var int scopePropagatorSolverInvocations + + synchronized def incrementScopePropagationSolverCount() { + scopePropagatorSolverInvocations++ + } +} diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/TypeInferenceMethod.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/TypeInferenceMethod.xtend new file mode 100644 index 00000000..9296a0be --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/TypeInferenceMethod.xtend @@ -0,0 +1,44 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra + +import com.google.common.collect.ImmutableMap +import com.google.common.collect.ImmutableSet +import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel +import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem +import hu.bme.mit.inf.dslreasoner.viatra2logic.viatra2logicannotations.TransfomedViatraQuery +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.CachingSimplePolyhedronScopePropagatorStrategy +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.CbcPolyhedronSolver +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.MultiplicityGoalConstraintCalculator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronScopePropagator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.RelationConstraintCalculator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.TypeHierarchyScopePropagator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Z3PolyhedronSolver +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.GeneratedPatterns +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.ModalPatternQueries +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternProvider +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.UnitPropagationPatternGenerator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules.GoalConstraintProvider +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules.RefinementRuleProvider +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation +import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace +import java.util.Collection +import java.util.List +import java.util.Map +import java.util.Set +import org.eclipse.viatra.query.runtime.api.GenericQueryGroup +import org.eclipse.viatra.query.runtime.api.IPatternMatch +import org.eclipse.viatra.query.runtime.api.IQuerySpecification +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine +import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher +import org.eclipse.viatra.query.runtime.emf.EMFScope +import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery +import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRule +import org.eclipse.xtend.lib.annotations.Data + +enum TypeInferenceMethod { + Generic, + PreliminaryAnalysis +} \ 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/ExtendedLinearExpressionBuilderFactory.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ExtendedLinearExpressionBuilderFactory.xtend new file mode 100644 index 00000000..6054affe --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ExtendedLinearExpressionBuilderFactory.xtend @@ -0,0 +1,140 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality + +import com.google.common.collect.ImmutableList +import com.google.common.collect.ImmutableMap +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type +import java.util.ArrayList +import java.util.HashMap +import java.util.HashSet +import java.util.List +import java.util.Map +import java.util.Set +import org.eclipse.viatra.query.runtime.api.IPatternMatch +import org.eclipse.xtend.lib.annotations.Accessors +import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor + +interface BoundSaturationListener { + def void boundsSaturated(Integer lower, Integer upper) +} + +interface ExtendedLinearExpressionBuilderFactory { + def ExtendedLinearExpressionBuilder createBuilder() + + def Dimension getDimension(IPatternMatch patternMatch) +} + +interface ExtendedLinearExpressionBuilder extends LinearTypeExpressionBuilder { + override ExtendedLinearExpressionBuilder add(int scale, Type type) + + def ExtendedLinearExpressionBuilder add(int scale, IPatternMatch patternMatch) + + def ExtendedLinearExpressionBuilder add(int scale, Dimension dimension) + + def LinearBoundedExpression build(BoundSaturationListener listener) +} + +class ExtendedPolyhedronBuilder implements ExtendedLinearExpressionBuilderFactory { + val Map typeBounds + val Map, LinearBoundedExpression> expressionsCache + + val ImmutableList.Builder dimensions = ImmutableList.builder + val Set constraints = new HashSet + val Set expressionsToSaturate = new HashSet + val Map patternMatchCounts = new HashMap + @Accessors(PUBLIC_GETTER) val List> saturationListeners = new ArrayList + + new(Polyhedron polyhedron, Map typeBounds, + Map, LinearBoundedExpression> initialExpressionsCache) { + this.typeBounds = typeBounds + this.expressionsCache = new HashMap(initialExpressionsCache) + dimensions.addAll(polyhedron.dimensions) + constraints.addAll(polyhedron.constraints) + expressionsToSaturate.addAll(polyhedron.expressionsToSaturate) + } + + override createBuilder() { + new ExtendedLinearExpressionBuilderImpl(this) + } + + override getDimension(IPatternMatch patternMatch) { + patternMatchCounts.computeIfAbsent(patternMatch) [ key | + val dimension = new Dimension(key.toString, 0, null) + dimensions.add(dimension) + dimension + ] + } + + def buildPolyhedron() { + new Polyhedron( + dimensions.build, + ImmutableList.copyOf(constraints), + ImmutableList.copyOf(expressionsToSaturate) + ) + } + + @FinalFieldsConstructor + private static class ExtendedLinearExpressionBuilderImpl implements ExtendedLinearExpressionBuilder { + val ExtendedPolyhedronBuilder polyhedronBuilder + + val Map coefficients = new HashMap + + override add(int scale, Type type) { + val expression = polyhedronBuilder.typeBounds.get(type) + if (expression === null) { + throw new IllegalArgumentException("Unknown Type: " + type) + } + add(scale, expression) + } + + override add(int scale, IPatternMatch patternMatch) { + val dimension = polyhedronBuilder.getDimension(patternMatch) + add(scale, dimension) + } + + private def add(int scale, LinearBoundedExpression expression) { + switch (expression) { + Dimension: add(scale, expression) + LinearConstraint: add(scale, expression.coefficients) + default: throw new IllegalArgumentException("Unknown LinearBoundedExpression: " + expression) + } + } + + private def add(int scale, Map coefficients) { + for (pair : coefficients.entrySet) { + add(scale * pair.value, pair.key) + } + this + } + + override add(int scale, Dimension dimension) { + coefficients.merge(dimension, scale)[a, b|a + b] + this + } + + override build() { + val filteredCoefficients = ImmutableMap.copyOf(coefficients.filter [ _, coefficient | + coefficient != 0 + ]) + polyhedronBuilder.expressionsCache.computeIfAbsent(filteredCoefficients) [ map | + if (map.size == 1) { + val pair = map.entrySet.head + if (pair.value == 1) { + return pair.key + } + } + val constraint = new LinearConstraint(map) + polyhedronBuilder.constraints.add(constraint) + constraint + ] + } + + override build(BoundSaturationListener listener) { + val expression = build() + if (listener !== null) { + polyhedronBuilder.expressionsToSaturate.add(expression) + polyhedronBuilder.saturationListeners.add(expression -> listener) + } + expression + } + } +} diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ExtendedPolyhedronScopePropagatorStrategy.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ExtendedPolyhedronScopePropagatorStrategy.xtend new file mode 100644 index 00000000..32923396 --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ExtendedPolyhedronScopePropagatorStrategy.xtend @@ -0,0 +1,63 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality + +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationStatistics +import java.util.Collection +import java.util.Map +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Relation + +interface PolyhedronExtensionOperator { + def void extendPolyhedron(ExtendedLinearExpressionBuilderFactory factory) +} + +class ExtendedPolyhedronScopePropagatorStrategy extends PolyhedronScopePropagatorStrategy { + val PolyhedronSolver solver + val Collection extensionOperators + + var Map typeBounds + var Map, LinearBoundedExpression> initialExpressionsCache + + new(PolyhedronSolver solver, Collection extensionOperators, + ModelGenerationStatistics statistics) { + super(statistics) + this.solver = solver + this.extensionOperators = extensionOperators + } + + override setPolyhedron(Polyhedron polyhedron, Map typeBounds, + Map, LinearBoundedExpression> initialExpressionsCache) { + super.setPolyhedron(polyhedron, typeBounds, initialExpressionsCache) + this.typeBounds = typeBounds + this.initialExpressionsCache = initialExpressionsCache + } + + override isRelevantRelation(Relation relation) { + true + } + + override protected doSaturate() { + val builder = new ExtendedPolyhedronBuilder(polyhedron, typeBounds, initialExpressionsCache) + for (extensionOperator : extensionOperators) { + extensionOperator.extendPolyhedron(builder) + } + val extendedPolyhedron = builder.buildPolyhedron() + val saturationOperator = solver.createSaturationOperator(extendedPolyhedron) + val result = try { + saturationOperator.saturate() + } finally { + saturationOperator.close() + } + if (result == PolyhedronSaturationResult.EMPTY) { + // The partial model cannot be refined any more, we can't provide objective bounds. + for (pair : builder.saturationListeners) { + pair.value.boundsSaturated(null, null) + } + return false + } + for (pair : builder.saturationListeners) { + val expression = pair.key + pair.value.boundsSaturated(expression.lowerBound, expression.upperBound) + } + true + } +} diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagator.xtend index c28d4caa..ad8f94ab 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagator.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagator.xtend @@ -1,7 +1,5 @@ package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality -import com.google.common.cache.Cache -import com.google.common.cache.CacheBuilder import com.google.common.collect.ImmutableList import com.google.common.collect.ImmutableMap import com.google.common.collect.ImmutableSet @@ -23,7 +21,6 @@ import java.util.HashSet import java.util.List import java.util.Map import java.util.Set -import javax.naming.OperationNotSupportedException import org.eclipse.viatra.query.runtime.api.IPatternMatch import org.eclipse.viatra.query.runtime.api.IQuerySpecification import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine @@ -32,31 +29,29 @@ import org.eclipse.viatra.query.runtime.emf.EMFScope import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { - static val CACHE_SIZE = 10000 - val boolean updateHeuristic val Map scopeBounds val LinearBoundedExpression topLevelBounds val Polyhedron polyhedron - val PolyhedronSaturationOperator operator + val PolyhedronScopePropagatorStrategy strategy val Set relevantRelations - val Cache cache = CacheBuilder.newBuilder.maximumSize(CACHE_SIZE).build List updaters = emptyList new(PartialInterpretation p, ModelGenerationStatistics statistics, Set possibleNewDynamicTypes, Map unfinishedMultiplicityQueries, IQuerySpecification> hasElementInContainmentQuery, Map>> allPatternsByName, - Collection hints, PolyhedronSolver solver, boolean propagateRelations, - boolean updateHeuristic) { + Collection hints, PolyhedronScopePropagatorStrategy strategy, + boolean propagateRelations, boolean updateHeuristic) { super(p, statistics) this.updateHeuristic = updateHeuristic + this.strategy = strategy val builder = new PolyhedronBuilder(p) builder.buildPolyhedron(possibleNewDynamicTypes) scopeBounds = builder.scopeBounds topLevelBounds = builder.topLevelBounds polyhedron = builder.polyhedron - operator = solver.createSaturationOperator(polyhedron) + strategy.setPolyhedron(polyhedron, builder.typeBounds, builder.expressionsCache) propagateAllScopeConstraints() if (propagateRelations) { val maximumNumberOfNewNodes = topLevelBounds.upperBound @@ -80,30 +75,10 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { resetBounds() populatePolyhedronFromScope() // println(polyhedron) - val signature = polyhedron.createSignature - val cachedSignature = cache.getIfPresent(signature) - switch (cachedSignature) { - case null: { - statistics.incrementScopePropagationSolverCount - val result = operator.saturate() - if (result == PolyhedronSaturationResult.EMPTY) { - cache.put(signature, PolyhedronSignature.EMPTY) -// println("INVALID") - setScopesInvalid() - } else { - val resultSignature = polyhedron.createSignature - cache.put(signature, resultSignature) - populateScopesFromPolyhedron() - } - } - case PolyhedronSignature.EMPTY: - setScopesInvalid() - PolyhedronSignature.Bounds: { - polyhedron.applySignature(signature) - populateScopesFromPolyhedron() - } - default: - throw new IllegalStateException("Unknown polyhedron signature: " + signature) + if (strategy.saturate) { + populateScopesFromPolyhedron() + } else { + setScopesInvalid() } // println(polyhedron) if (updateHeuristic) { @@ -112,9 +87,9 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { } override isPropagationNeededAfterAdditionToRelation(Relation r) { - relevantRelations.contains(r) || super.isPropagationNeededAfterAdditionToRelation(r) + relevantRelations.contains(r) || strategy.isRelevantRelation(r) || super.isPropagationNeededAfterAdditionToRelation(r) } - + override isQueryEngineFlushRequiredBeforePropagation() { true } @@ -253,7 +228,10 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { } buildRelevantRelations(constraints.keySet) for (hint : hints) { - updatersBuilder.add(hint.createConstraintUpdater(this)) + val updater = hint.createConstraintUpdater(this) + if (updater !== null) { + updatersBuilder.add(updater) + } } updaters = updatersBuilder.build addCachedConstraintsToPolyhedron() @@ -410,7 +388,7 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { for (scope : p.scopes) { switch (targetTypeInterpretation : scope.targetTypeInterpretation) { PartialPrimitiveInterpretation: - throw new OperationNotSupportedException("Primitive type scopes are not yet implemented") + throw new IllegalStateException("Primitive type scopes are not yet implemented") PartialComplexTypeInterpretation: { val complexType = targetTypeInterpretation.interpretationOf val typeBound = typeBounds.get(complexType) diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagatorStrategy.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagatorStrategy.xtend new file mode 100644 index 00000000..f93dcd18 --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagatorStrategy.xtend @@ -0,0 +1,92 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality + +import com.google.common.cache.Cache +import com.google.common.cache.CacheBuilder +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Relation +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationStatistics +import java.util.Map +import org.eclipse.xtend.lib.annotations.Accessors +import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor + +@FinalFieldsConstructor +abstract class PolyhedronScopePropagatorStrategy { + val ModelGenerationStatistics statistics + + @Accessors(PUBLIC_GETTER) var Polyhedron polyhedron + + def void setPolyhedron(Polyhedron polyhedron, Map typeBounds, + Map, LinearBoundedExpression> initialExpressionsCache) { + if (this.polyhedron !== null) { + throw new IllegalStateException("polyhedron was already set") + } + this.polyhedron = polyhedron + initialize() + } + + def boolean saturate() { + if (polyhedron === null) { + throw new IllegalStateException("polyhedron was not set") + } + doSaturate() + } + + def boolean isRelevantRelation(Relation relation) { + false + } + + protected def incrementScopePropagationSolverCount() { + statistics.incrementScopePropagationSolverCount() + } + + protected def void initialize() { + } + + protected def boolean doSaturate() +} + +@FinalFieldsConstructor +class CachingSimplePolyhedronScopePropagatorStrategy extends PolyhedronScopePropagatorStrategy { + static val CACHE_SIZE = 10000 + + val PolyhedronSolver solver + + val Cache cache = CacheBuilder.newBuilder.maximumSize(CACHE_SIZE).build + var PolyhedronSaturationOperator operator + + new(PolyhedronSolver solver, ModelGenerationStatistics statistics) { + super(statistics) + this.solver = solver + } + + override protected initialize() { + operator = solver.createSaturationOperator(polyhedron) + } + + override protected doSaturate() { + val signature = polyhedron.createSignature + val cachedSignature = cache.getIfPresent(signature) + switch (cachedSignature) { + case null: { + incrementScopePropagationSolverCount() + val result = operator.saturate() + if (result == PolyhedronSaturationResult.EMPTY) { + cache.put(signature, PolyhedronSignature.EMPTY) + false + } else { + val resultSignature = polyhedron.createSignature + cache.put(signature, resultSignature) + true + } + } + case PolyhedronSignature.EMPTY: + false + PolyhedronSignature.Bounds: { + polyhedron.applySignature(signature) + true + } + default: + throw new IllegalStateException("Unknown polyhedron signature: " + signature) + } + } +} 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 index 4e046190..21bd2d9e 100644 --- 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 @@ -116,7 +116,7 @@ abstract class PolyhedronSignature { } @Accessors -abstract class LinearBoundedExpression { +class Bounds { var Integer lowerBound var Integer upperBound @@ -132,12 +132,19 @@ abstract class LinearBoundedExpression { } } + def void assertBetween(Integer tighterLowerBound, Integer tighterUpperBound) { + tightenLowerBound(tighterLowerBound) + tightenUpperBound(tighterUpperBound) + } + def void assertEqualsTo(int bound) { - tightenLowerBound(bound) - tightenUpperBound(bound) + assertBetween(bound, bound) } } +abstract class LinearBoundedExpression extends Bounds { +} + @Accessors class Dimension extends LinearBoundedExpression { val String name 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 4ad61ccb..402a0b7d 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 @@ -4,6 +4,7 @@ Bundle-Name: Reasoner Bundle-SymbolicName: hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner Bundle-Version: 1.0.0.qualifier Export-Package: hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner, + hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse, hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization Require-Bundle: hu.bme.mit.inf.dslreasoner.ecore2logic;bundle-version="1.0.0", hu.bme.mit.inf.dslreasoner.logic.model;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 9ef5e091..691e0645 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,7 +1,6 @@ package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner import org.eclipse.viatra.dse.objectives.IGlobalConstraint -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod abstract class ModelGenerationMethodBasedGlobalConstraint implements IGlobalConstraint { val protected ModelGenerationMethod method diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ModelGenerationMethodProvider.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ModelGenerationMethodProvider.xtend new file mode 100644 index 00000000..25137eba --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ModelGenerationMethodProvider.xtend @@ -0,0 +1,201 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner + +import com.google.common.collect.ImmutableMap +import com.google.common.collect.ImmutableSet +import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel +import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem +import hu.bme.mit.inf.dslreasoner.viatra2logic.viatra2logicannotations.TransfomedViatraQuery +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationStatistics +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.CachingSimplePolyhedronScopePropagatorStrategy +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.CbcPolyhedronSolver +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.MultiplicityGoalConstraintCalculator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronExtensionOperator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronScopePropagator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.RelationConstraintCalculator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.TypeHierarchyScopePropagator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Z3PolyhedronSolver +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.GeneratedPatterns +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.ModalPatternQueries +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternProvider +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules.GoalConstraintProvider +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules.RefinementRuleProvider +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.DiversityChecker +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.ViatraReasonerSolutionSaver +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ThreeValuedCostObjectiveProvider +import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace +import java.util.Collection +import java.util.List +import java.util.Map +import java.util.Set +import org.eclipse.viatra.dse.objectives.IObjective +import org.eclipse.viatra.query.runtime.api.GenericQueryGroup +import org.eclipse.viatra.query.runtime.api.IPatternMatch +import org.eclipse.viatra.query.runtime.api.IQuerySpecification +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine +import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher +import org.eclipse.viatra.query.runtime.emf.EMFScope +import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery +import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRule +import org.eclipse.xtend.lib.annotations.Data +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedPolyhedronScopePropagatorStrategy + +@Data class ModelGenerationMethod { + ModelGenerationStatistics statistics + + Collection> objectRefinementRules + Collection> relationRefinementRules + + List unfinishedMultiplicities + + Collection>> unfinishedWF + + Collection>> invalidWF + + Map>> mustUnitPropagationPreconditions + Map>> currentUnitPropagationPreconditions + + Map modalRelationQueries + + Collection>> allPatterns + + Collection costObjectives + boolean optimizationProblem + ViatraReasonerSolutionSaver solutionSaver +} + +class ModelGenerationMethodProvider { + val PatternProvider patternProvider = new PatternProvider + val RefinementRuleProvider refinementRuleProvider = new RefinementRuleProvider + val GoalConstraintProvider goalConstraintProvider = new GoalConstraintProvider + val relationConstraintCalculator = new RelationConstraintCalculator + + def ModelGenerationMethod createModelGenerationMethod( + LogicProblem logicProblem, + PartialInterpretation emptySolution, + ReasonerWorkspace workspace, + ViatraReasonerConfiguration config + ) { + val statistics = new ModelGenerationStatistics + val debugLevel = config.documentationLevel + val writeFiles = (debugLevel === DocumentationLevel.NORMAL || debugLevel === DocumentationLevel.FULL) + + val Set existingQueries = logicProblem.relations.map[annotations].flatten.filter(TransfomedViatraQuery). + map[it.patternPQuery as PQuery].toSet + + val relationConstraints = relationConstraintCalculator.calculateRelationConstraints(logicProblem) + val queries = patternProvider.generateQueries(logicProblem, emptySolution, statistics, existingQueries, + workspace, config.typeInferenceMethod, config.scopePropagatorStrategy, relationConstraints, config.hints, + config.unitPropagationPatternGenerators, writeFiles) + + val unfinishedMultiplicities = goalConstraintProvider.getUnfinishedMultiplicityQueries(logicProblem, queries, + config.calculateObjectCreationCosts) + val unfinishedWF = queries.getUnfinishedWFQueries.values + val modalRelationQueriesBuilder = ImmutableMap.builder + for (entry : queries.modalRelationQueries.entrySet) { + val annotation = entry.key.annotations.filter(TransfomedViatraQuery).head + if (annotation !== null) { + modalRelationQueriesBuilder.put(annotation.patternFullyQualifiedName, entry.value) + } + } + val modalRelationQueries = modalRelationQueriesBuilder.build + val invalidWF = queries.getInvalidWFQueries.values + val mustUnitPropagationPreconditions = queries.getMustUnitPropagationPreconditionPatterns + val currentUnitPropagationPreconditions = queries.getCurrentUnitPropagationPreconditionPatterns + val queriesToPrepare = ImmutableSet.builder.addAll(queries.refineObjectQueries.values).addAll( + queries.refineTypeQueries.values).addAll(queries.refineRelationQueries.values).addAll( + queries.mustRelationPropagationQueries.values).addAll(queries.multiplicityConstraintQueries.values.flatMap [ + allQueries + ]).addAll(queries.unfinishedWFQueries.values).addAll(queries.invalidWFQueries.values).addAll( + queries.mustUnitPropagationPreconditionPatterns.values).addAll( + queries.currentUnitPropagationPreconditionPatterns.values).add(queries.hasElementInContainmentQuery).build + val queryEngine = ViatraQueryEngine.on(new EMFScope(emptySolution)) + GenericQueryGroup.of(queriesToPrepare).prepare(queryEngine) + + val objectiveProvider = new ThreeValuedCostObjectiveProvider(queryEngine, emptySolution, modalRelationQueries) + val transformedObjectives = objectiveProvider.getCostObjectives(config.costObjectives) + + val solutionSaver = new ViatraReasonerSolutionSaver(transformedObjectives.leveledExtremalObjectives, + config.solutionScope.numberOfRequiredSolutions, DiversityChecker.of(config.diversityRequirement)) + + val allHints = ImmutableSet.builder + allHints.addAll(config.hints) + for (hint : transformedObjectives.hints) { + hint.boundsProvider = solutionSaver + allHints.add(hint) + } + + val scopePropagator = createScopePropagator(config.scopePropagatorStrategy, emptySolution, allHints.build, + transformedObjectives.extensionOperators, queries, statistics) + scopePropagator.propagateAllScopeConstraints + val unitRulePropagator = refinementRuleProvider.createUnitPrulePropagator(logicProblem, emptySolution, queries, + scopePropagator, statistics) + val objectRefinementRules = refinementRuleProvider.createObjectRefinementRules(logicProblem, emptySolution, + queries, unitRulePropagator, config.nameNewElements, statistics) + val relationRefinementRules = refinementRuleProvider.createRelationRefinementRules(queries, unitRulePropagator, + statistics) + + return new ModelGenerationMethod( + statistics, + objectRefinementRules.values, + relationRefinementRules.values, + unfinishedMultiplicities, + unfinishedWF, + invalidWF, + mustUnitPropagationPreconditions, + currentUnitPropagationPreconditions, + modalRelationQueries, + queries.allQueries, + transformedObjectives.objectives, + transformedObjectives.optimizationProblem, + solutionSaver + ) + } + + private def createScopePropagator(ScopePropagatorStrategy scopePropagatorStrategy, + PartialInterpretation emptySolution, Collection hints, + Collection extensionOperators, GeneratedPatterns queries, + ModelGenerationStatistics statistics) { + if (!hints.empty && !(scopePropagatorStrategy instanceof ScopePropagatorStrategy.Polyhedral)) { + throw new IllegalArgumentException("Only the Polyhedral scope propagator strategy can use hints.") + } + switch (scopePropagatorStrategy) { + case ScopePropagatorStrategy.None, + case ScopePropagatorStrategy.Basic: + new ScopePropagator(emptySolution, statistics) + case ScopePropagatorStrategy.BasicTypeHierarchy: + new TypeHierarchyScopePropagator(emptySolution, statistics) + ScopePropagatorStrategy.Polyhedral: { + val types = queries.refineObjectQueries.keySet.map[newType].toSet + val allPatternsByName = queries.allQueries.toMap[fullyQualifiedName] + val solver = switch (scopePropagatorStrategy.solver) { + case Z3Integer: + new Z3PolyhedronSolver(false, scopePropagatorStrategy.timeoutSeconds) + case Z3Real: + new Z3PolyhedronSolver(true, scopePropagatorStrategy.timeoutSeconds) + case Cbc: + new CbcPolyhedronSolver(false, scopePropagatorStrategy.timeoutSeconds, true) + case Clp: + new CbcPolyhedronSolver(true, scopePropagatorStrategy.timeoutSeconds, true) + default: + throw new IllegalArgumentException("Unknown polyhedron solver: " + + scopePropagatorStrategy.solver) + } + val strategy = if (extensionOperators.empty) { + new CachingSimplePolyhedronScopePropagatorStrategy(solver, statistics) + } else { + new ExtendedPolyhedronScopePropagatorStrategy(solver, extensionOperators, statistics) + } + new PolyhedronScopePropagator(emptySolution, statistics, types, queries.multiplicityConstraintQueries, + queries.hasElementInContainmentQuery, allPatternsByName, hints, strategy, + scopePropagatorStrategy.requiresUpperBoundIndexing, scopePropagatorStrategy.updateHeuristic) + } + default: + throw new IllegalArgumentException("Unknown scope propagator strategy: " + scopePropagatorStrategy) + } + } +} 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 8e05665c..8e992741 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,7 +1,5 @@ package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner -import com.google.common.collect.ImmutableList -import com.google.common.collect.Lists import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasoner import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasonerException @@ -11,7 +9,6 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicproblemPackage import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicresultFactory import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethodProvider import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.PartialInterpretationInitialiser import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation @@ -22,7 +19,6 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.sta import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.PairwiseNeighbourhoodBasedStateCoderFactory import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.BasicScopeGlobalConstraint import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.BestFirstStrategyForModelGeneration -import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.DiversityChecker import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.InconsistentScopeGlobalConstraint import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.LoggerSolutionFoundHandler import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.ModelGenerationCompositeObjective @@ -32,11 +28,8 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.PunishSizeObjective import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.ScopeObjective import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.SurelyViolatedObjectiveGlobalConstraint import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.UnfinishedMultiplicityObjective -import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.ViatraReasonerSolutionSaver import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.WF2ObjectiveConverter import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveKind -import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ThreeValuedCostElement -import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ThreeValuedCostObjective import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace import java.util.List import java.util.Map @@ -86,13 +79,7 @@ class ViatraReasoner extends LogicReasoner { problem, emptySolution, workspace, - viatraConfig.nameNewElements, - viatraConfig.typeInferenceMethod, - viatraConfig.calculateObjectCreationCosts, - viatraConfig.scopePropagatorStrategy, - viatraConfig.hints, - viatraConfig.unitPropagationPatternGenerators, - viatraConfig.documentationLevel + viatraConfig ) val compositeObjective = new ModelGenerationCompositeObjective( @@ -112,45 +99,21 @@ class ViatraReasoner extends LogicReasoner { dse.addObjective(punishObjective) } - val extremalObjectives = Lists.newArrayListWithExpectedSize(viatraConfig.costObjectives.size) - for (entry : viatraConfig.costObjectives.indexed) { - val objectiveName = '''costObjective«entry.key»''' - val objectiveConfig = entry.value - val elementsBuilder = ImmutableList.builder - for (elementConfig : objectiveConfig.elements) { - val relationName = elementConfig.patternQualifiedName - val modalQueries = method.modalRelationQueries.get(relationName) - if (modalQueries === null) { - throw new IllegalArgumentException("Unknown relation: " + relationName) - } - elementsBuilder.add(new ThreeValuedCostElement( - modalQueries.currentQuery, - modalQueries.mayQuery, - modalQueries.mustQuery, - elementConfig.weight - )) - } - val costElements = elementsBuilder.build - val costObjective = new ThreeValuedCostObjective(objectiveName, costElements, objectiveConfig.kind, - objectiveConfig.threshold, 3) + for (costObjective : method.costObjectives) { dse.addObjective(costObjective) - if (objectiveConfig.findExtremum) { - extremalObjectives += costObjective - } } - val numberOfRequiredSolutions = configuration.solutionScope.numberOfRequiredSolutions - val solutionStore = if (extremalObjectives.empty) { - new SolutionStore(numberOfRequiredSolutions) - } else { + val solutionStore = if (method.optimizationProblem) { new SolutionStore() + } else { + new SolutionStore(numberOfRequiredSolutions) } solutionStore.registerSolutionFoundHandler(new LoggerSolutionFoundHandler(viatraConfig)) - val diversityChecker = DiversityChecker.of(viatraConfig.diversityRequirement) val numericSolver = new NumericSolver(method, viatraConfig.runIntermediateNumericalConsistencyChecks, false) - val solutionSaver = new ViatraReasonerSolutionSaver(newArrayList(extremalObjectives), numberOfRequiredSolutions, - diversityChecker, numericSolver) + val solutionSaver = method.solutionSaver + solutionSaver.numericSolver = numericSolver val solutionCopier = solutionSaver.solutionCopier + val diversityChecker = solutionSaver.diversityChecker solutionStore.withSolutionSaver(solutionSaver) dse.solutionStore = solutionStore @@ -185,7 +148,8 @@ class ViatraReasoner extends LogicReasoner { dse.addTransformationRule(rule) } - val strategy = new BestFirstStrategyForModelGeneration(workspace, viatraConfig, method, solutionSaver, numericSolver) + val strategy = new BestFirstStrategyForModelGeneration(workspace, viatraConfig, method, solutionSaver, + numericSolver) viatraConfig.progressMonitor.workedForwardTransformation val transformationFinished = System.nanoTime val transformationTime = transformationFinished - transformationStartTime @@ -211,14 +175,15 @@ class ViatraReasoner extends LogicReasoner { it.value = (pair.value / 1000000) as int ] } - for(x: 0.. [ it.name = '''Solution«x+1»DetailedStatistics''' it.value = strategy.times.get(x) ] } it.entries += createIntStatisticEntry => [ - it.name = "ExplorationInitializationTime" it.value = ((strategy.explorationStarted-transformationFinished)/1000000) as int + it.name = "ExplorationInitializationTime" + it.value = ((strategy.explorationStarted - transformationFinished) / 1000000) as int ] it.entries += createIntStatisticEntry => [ it.name = "TransformationExecutionTime" @@ -253,22 +218,28 @@ class ViatraReasoner extends LogicReasoner { it.value = dse.numberOfStates as int ] it.entries += createIntStatisticEntry => [ - it.name = "ForwardTime" it.value = (strategy.forwardTime/1000000) as int + it.name = "ForwardTime" + it.value = (strategy.forwardTime / 1000000) as int ] it.entries += createIntStatisticEntry => [ - it.name = "BacktrackingTime" it.value = (strategy.backtrackingTime/1000000) as int + it.name = "BacktrackingTime" + it.value = (strategy.backtrackingTime / 1000000) as int ] it.entries += createIntStatisticEntry => [ - it.name = "GlobalConstraintEvaluationTime" it.value = (strategy.globalConstraintEvaluationTime/1000000) as int + it.name = "GlobalConstraintEvaluationTime" + it.value = (strategy.globalConstraintEvaluationTime / 1000000) as int ] it.entries += createIntStatisticEntry => [ - it.name = "FitnessCalculationTime" it.value = (strategy.fitnessCalculationTime/1000000) as int + it.name = "FitnessCalculationTime" + it.value = (strategy.fitnessCalculationTime / 1000000) as int ] it.entries += createIntStatisticEntry => [ - it.name = "SolutionCopyTime" it.value = (solutionSaver.totalCopierRuntime/1000000) as int + it.name = "SolutionCopyTime" + it.value = (solutionSaver.totalCopierRuntime / 1000000) as int ] it.entries += createIntStatisticEntry => [ - it.name = "ActivationSelectionTime" it.value = (strategy.activationSelector.runtime/1000000) as int + it.name = "ActivationSelectionTime" + it.value = (strategy.activationSelector.runtime / 1000000) as int ] it.entries += createIntStatisticEntry => [ it.name = "Decisions" @@ -287,27 +258,34 @@ class ViatraReasoner extends LogicReasoner { it.value = method.statistics.scopePropagatorSolverInvocations ] it.entries += createIntStatisticEntry => [ - it.name = "NumericalSolverSumTime" it.value = (strategy.numericSolver.runtime/1000000) as int + it.name = "NumericalSolverSumTime" + it.value = (strategy.numericSolver.runtime / 1000000) as int ] it.entries += createIntStatisticEntry => [ - it.name = "NumericalSolverProblemFormingTime" it.value = (strategy.numericSolver.solverFormingProblem/1000000) as int + it.name = "NumericalSolverProblemFormingTime" + it.value = (strategy.numericSolver.solverFormingProblem / 1000000) as int ] it.entries += createIntStatisticEntry => [ - it.name = "NumericalSolverSolvingTime" it.value = (strategy.numericSolver.solverSolvingProblem/1000000) as int + it.name = "NumericalSolverSolvingTime" + it.value = (strategy.numericSolver.solverSolvingProblem / 1000000) as int ] it.entries += createIntStatisticEntry => [ - it.name = "NumericalSolverInterpretingSolution" it.value = (strategy.numericSolver.solverSolution/1000000) as int + it.name = "NumericalSolverInterpretingSolution" + it.value = (strategy.numericSolver.solverSolution / 1000000) as int ] it.entries += createIntStatisticEntry => [ - it.name = "NumericalSolverCachingTime" it.value = (strategy.numericSolver.cachingTime/1000000) as int + it.name = "NumericalSolverCachingTime" + it.value = (strategy.numericSolver.cachingTime / 1000000) as int ] it.entries += createIntStatisticEntry => [ - it.name = "NumericalSolverCallNumber" it.value = strategy.numericSolver.numberOfSolverCalls + it.name = "NumericalSolverCallNumber" + it.value = strategy.numericSolver.numberOfSolverCalls ] it.entries += createIntStatisticEntry => [ - it.name = "NumericalSolverCachedAnswerNumber" it.value = strategy.numericSolver.numberOfCachedSolverCalls + it.name = "NumericalSolverCachedAnswerNumber" + it.value = strategy.numericSolver.numberOfCachedSolverCalls ] - if(diversityChecker.active) { + if (diversityChecker.active) { it.entries += createIntStatisticEntry => [ it.name = "SolutionDiversityCheckTime" it.value = (diversityChecker.totalRuntime / 1000000) as int diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasonerConfiguration.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasonerConfiguration.xtend index a2ed6016..fbe6da9d 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 @@ -4,7 +4,6 @@ import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasoner import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicSolverConfiguration import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RelationDeclaration import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeDeclaration -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeInferenceMethod import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedralScopePropagatorConstraints @@ -12,6 +11,7 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Polyhedr import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.UnitPropagationPatternGenerator import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualiser +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveKind import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveThreshold import java.util.LinkedList @@ -114,9 +114,11 @@ class CostObjectiveConfiguration { public var ObjectiveKind kind public var ObjectiveThreshold threshold public var boolean findExtremum + public var CostObjectiveHint hint } class CostObjectiveElementConfiguration { public var String patternQualifiedName public var int weight } + 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 4800f71d..4b7cead1 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 @@ -28,8 +28,6 @@ import org.eclipse.viatra.dse.objectives.Fitness; import org.eclipse.viatra.dse.objectives.ObjectiveComparatorHelper; import org.eclipse.viatra.dse.solutionstore.ISolutionFoundHandler; import org.eclipse.viatra.dse.solutionstore.SolutionStore; -import org.eclipse.viatra.query.runtime.api.IPatternMatch; -import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher; import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel; import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasoner; @@ -37,12 +35,11 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem; import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.InconsistencyResult; import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicResult; import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult; -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod; import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic.PartialInterpretation2Logic; import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation; -import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.NeighbourhoodBasedPartialInterpretationStateCoder; import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualisation; import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualiser; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethod; import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration; import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace; @@ -301,7 +298,7 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { return activationIds; } - private void checkForSolution(final Fitness fittness) { + private void checkForSolution(final Fitness fitness) { solutionStore.newSolution(context); } 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 066040a0..70e8e9c2 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 @@ -1,13 +1,13 @@ package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse import hu.bme.mit.inf.dslreasoner.viatra2logic.NumericTranslator -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.BooleanElement import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.IntegerElement import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PrimitiveElement import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.RealElement import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.StringElement +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethod import java.math.BigDecimal import java.util.HashMap import java.util.LinkedHashMap 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 cfd11816..b48d0831 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 @@ -22,12 +22,13 @@ import java.util.List import java.util.Map import java.util.TreeSet import org.eclipse.emf.ecore.EObject +import org.eclipse.xtend.lib.annotations.Accessors import org.eclipse.xtext.xbase.lib.Functions.Function1 import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.* class PartialModelAsLogicInterpretation implements LogicModelInterpretation{ - val PartialInterpretation partialInterpretation + @Accessors val PartialInterpretation partialInterpretation val Map trace; val Map type2Interpretation val Map relation2Interpretation diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionCopier.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionCopier.xtend index 38c8f5a1..33b69436 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionCopier.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionCopier.xtend @@ -26,16 +26,12 @@ class CopiedSolution { * using the supplied {@link NumericSolver}. */ class SolutionCopier { - val NumericSolver numericSolver val copiedSolutions = new LinkedHashMap + @Accessors NumericSolver numericSolver long startTime = System.nanoTime @Accessors(PUBLIC_GETTER) long totalCopierRuntime = 0 - new(NumericSolver numericSolver) { - this.numericSolver = numericSolver - } - def void copySolution(ThreadContext context, Object solutionId) { val existingCopy = copiedSolutions.get(solutionId) if (existingCopy === null) { @@ -47,7 +43,7 @@ class SolutionCopier { totalCopierRuntime += System.nanoTime - copyStart val copierRuntime = System.nanoTime - startTime val copiedSolution = new CopiedSolution(copiedPartialInterpretation, copier, copierRuntime) - numericSolver.fillSolutionCopy(copiedSolution.trace) + numericSolver?.fillSolutionCopy(copiedSolution.trace) copiedSolutions.put(solutionId, copiedSolution) } else { existingCopy.current = true diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend index c0b5008c..e00f76ff 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend @@ -1,5 +1,9 @@ package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Bounds +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.DirectionalThresholdObjective +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.IObjectiveBoundsProvider +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveThreshold import java.util.HashMap import java.util.Map import org.eclipse.viatra.dse.api.DSEException @@ -18,24 +22,32 @@ import org.eclipse.xtend.lib.annotations.Accessors * Will also automatically fill any missing numerical values in the saved solutions * using the supplied {@link NumericSolver}. */ -class ViatraReasonerSolutionSaver implements ISolutionSaver { +class ViatraReasonerSolutionSaver implements ISolutionSaver, IObjectiveBoundsProvider { + static val TOLERANCE = 1e-10 + @Accessors val SolutionCopier solutionCopier - val NumericSolver numericSolver @Accessors val DiversityChecker diversityChecker + val IObjective[][] leveledExtremalObjectives val boolean hasExtremalObjectives val int numberOfRequiredSolutions val ObjectiveComparatorHelper comparatorHelper val Map trajectories = new HashMap - @Accessors(PUBLIC_SETTER) var Map solutionsCollection + @Accessors var NumericSolver numericSolver + @Accessors var Map solutionsCollection - new(IObjective[][] leveledExtremalObjectives, int numberOfRequiredSolutions, DiversityChecker diversityChecker, NumericSolver numericSolver) { + new(IObjective[][] leveledExtremalObjectives, int numberOfRequiredSolutions, DiversityChecker diversityChecker) { this.diversityChecker = diversityChecker comparatorHelper = new ObjectiveComparatorHelper(leveledExtremalObjectives) + this.leveledExtremalObjectives = leveledExtremalObjectives hasExtremalObjectives = leveledExtremalObjectives.exists[!empty] this.numberOfRequiredSolutions = numberOfRequiredSolutions - this.solutionCopier = new SolutionCopier(numericSolver) + this.solutionCopier = new SolutionCopier + } + + def setNumericSolver(NumericSolver numericSolver) { this.numericSolver = numericSolver + solutionCopier.numericSolver = numericSolver } override saveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) { @@ -51,6 +63,7 @@ class ViatraReasonerSolutionSaver implements ISolutionSaver { if (!shouldSaveSolution(fitness, context)) { return false } + println("Found: " + fitness) val dominatedTrajectories = newArrayList for (entry : trajectories.entrySet) { val isLastFitnessBetter = comparatorHelper.compare(fitness, entry.value) @@ -99,7 +112,7 @@ class ViatraReasonerSolutionSaver implements ISolutionSaver { } private def shouldSaveSolution(Fitness fitness, ThreadContext context) { - return fitness.satisifiesHardObjectives && numericSolver.currentSatisfiable + fitness.satisifiesHardObjectives && (numericSolver === null || numericSolver.currentSatisfiable) } private def basicSaveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory, @@ -145,8 +158,93 @@ class ViatraReasonerSolutionSaver implements ISolutionSaver { } solutionsCollection.size < numberOfRequiredSolutions } - + def getTotalCopierRuntime() { solutionCopier.totalCopierRuntime } + + override computeRequiredBounds(IObjective objective, Bounds bounds) { + if (!hasExtremalObjectives) { + return + } + if (objective instanceof DirectionalThresholdObjective) { + switch (threshold : objective.threshold) { + case ObjectiveThreshold.NO_THRESHOLD: { + // No threshold to set. + } + ObjectiveThreshold.Exclusive: { + switch (kind : objective.kind) { + case HIGHER_IS_BETTER: + bounds.tightenLowerBound(Math.floor(threshold.threshold + 1) as int) + case LOWER_IS_BETTER: + bounds.tightenUpperBound(Math.ceil(threshold.threshold - 1) as int) + default: + throw new IllegalArgumentException("Unknown objective kind" + kind) + } + if (threshold.clampToThreshold) { + return + } + } + ObjectiveThreshold.Inclusive: { + switch (kind : objective.kind) { + case HIGHER_IS_BETTER: + bounds.tightenLowerBound(Math.ceil(threshold.threshold) as int) + case LOWER_IS_BETTER: + bounds.tightenUpperBound(Math.floor(threshold.threshold) as int) + default: + throw new IllegalArgumentException("Unknown objective kind" + kind) + } + if (threshold.clampToThreshold) { + return + } + } + default: + throw new IllegalArgumentException("Unknown threshold: " + threshold) + } + for (level : leveledExtremalObjectives) { + switch (level.size) { + case 0: { + // Nothing to do, wait for the next level. + } + case 1: { + val primaryObjective = level.get(0) + if (primaryObjective != objective) { + // There are no worst-case bounds for secondary objectives. + return + } + } + default: + // There are no worst-case bounds for Pareto front calculation. + return + } + } + val fitnessIterator = trajectories.values.iterator + if (!fitnessIterator.hasNext) { + return + } + val fitness = fitnessIterator.next.get(objective.name) + while (fitnessIterator.hasNext) { + val otherFitness = fitnessIterator.next.get(objective.name) + if (Math.abs(fitness - otherFitness) > TOLERANCE) { + throw new IllegalStateException("Inconsistent fitness: " + objective.name) + } + } + switch (kind : objective.kind) { + case HIGHER_IS_BETTER: + if (needsMoreSolutionsWithSameFitness) { + bounds.tightenLowerBound(Math.floor(fitness) as int) + } else { + bounds.tightenLowerBound(Math.floor(fitness + 1) as int) + } + case LOWER_IS_BETTER: + if (needsMoreSolutionsWithSameFitness) { + bounds.tightenUpperBound(Math.ceil(fitness) as int) + } else { + bounds.tightenUpperBound(Math.ceil(fitness - 1) as int) + } + default: + throw new IllegalArgumentException("Unknown objective kind" + kind) + } + } + } } diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/CostElementMatchers.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/CostElementMatchers.xtend new file mode 100644 index 00000000..885b14e8 --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/CostElementMatchers.xtend @@ -0,0 +1,137 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization + +import com.google.common.collect.ImmutableList +import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicproblemPackage +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationPackage +import java.util.List +import org.eclipse.emf.ecore.EObject +import org.eclipse.viatra.query.runtime.api.IPatternMatch +import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher +import org.eclipse.xtend.lib.annotations.Data +import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation + +@FunctionalInterface +interface ParameterScopeBound { + def double getUpperBound() +} + +@Data +class CostElementMatch { + val IPatternMatch match + val boolean must + + def isMulti() { + CostElementMatchers.isMultiMatch(match) + } +} + +@Data +class CostElementMatchers { + val ViatraQueryMatcher currentMatcher + val ViatraQueryMatcher mayMatcher + val ViatraQueryMatcher mustMatcher + val List parameterScopeBounds + val int weight + + def getCurrentNumberOfMatches() { + currentMatcher.countMatches + } + + def getMinimumNumberOfMatches() { + mustMatcher.countMatches + } + + def getMaximumNumberOfMatches() { + var double sum = 0 + val iterator = mayMatcher.streamAllMatches.iterator + while (iterator.hasNext) { + val match = iterator.next + var double product = 1 + val numberOfParameters = parameterScopeBounds.size + for (var int i = 0; i < numberOfParameters; i++) { + if (isMulti(match.get(i + 2))) { + val scopeBound = parameterScopeBounds.get(i) + product *= scopeBound.upperBound + } + + } + sum += product + } + sum + } + + def getMatches() { + ImmutableList.copyOf(mayMatcher.streamAllMatches.iterator.map [ match | + new CostElementMatch(match, mustMatcher.isMatch(match)) + ]) + } + + def projectMayMatch(IPatternMatch match, int... indices) { + mayMatcher.projectMatch(match, indices) + } + + private static def projectMatch(ViatraQueryMatcher matcher, IPatternMatch match, int... indices) { + checkMatch(match) + val n = matcher.specification.parameters.length - 2 + if (indices.length != n) { + throw new IllegalArgumentException("Invalid number of projection indices") + } + val newMatch = matcher.newEmptyMatch + newMatch.set(0, match.get(0)) + newMatch.set(1, match.get(1)) + for (var int i = 0; i < n; i++) { + newMatch.set(i + 2, match.get(indices.get(i))) + } + if (!matcher.hasMatch(newMatch)) { + throw new IllegalArgumentException("Projected match does not exist") + } + return newMatch + } + + private static def isMatch(ViatraQueryMatcher matcher, IPatternMatch match) { + val n = matcher.specification.parameters.length + if (n != match.specification.parameters.length) { + throw new IllegalArgumentException("Invalid number of match arguments") + } + val newMatch = matcher.newEmptyMatch + for (var int i = 0; i < n; i++) { + newMatch.set(i, match.get(i)) + } + return matcher.hasMatch(newMatch) + } + + static def isMulti(Object o) { + if (o instanceof EObject) { + switch (feature : o.eContainmentFeature) { + case LogicproblemPackage.eINSTANCE.logicProblem_Elements, + case PartialinterpretationPackage.eINSTANCE.partialInterpretation_NewElements: + false + case PartialinterpretationPackage.eINSTANCE.partialInterpretation_OpenWorldElements: + true + default: + throw new IllegalStateException("Unknown containment feature for element: " + feature) + } + } else { + false + } + } + + static def isMultiMatch(IPatternMatch match) { + checkMatch(match) + val n = match.specification.parameters.length + for (var int i = 2; i < n; i++) { + if (isMulti(match.get(i))) { + return true + } + } + false + } + + private static def checkMatch(IPatternMatch match) { + val n = match.specification.parameters.length + if (n < 2 || !(match.get(0) instanceof LogicProblem) || !(match.get(1) instanceof PartialInterpretation)) { + throw new IllegalArgumentException("Match is not from the partial interpretation") + } + } +} diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/CostObjectiveHint.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/CostObjectiveHint.xtend new file mode 100644 index 00000000..2434073d --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/CostObjectiveHint.xtend @@ -0,0 +1,68 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization + +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.BoundSaturationListener +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilder +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeExpressionBuilderFactory +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronExtensionOperator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternGenerator +import java.util.Map +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery +import org.eclipse.xtend.lib.annotations.Accessors + +abstract class CostObjectiveHint implements LinearTypeConstraintHint, BoundSaturationListener { + @Accessors ThreeValuedCostObjective objective + @Accessors IObjectiveBoundsProvider boundsProvider + + Integer bestUpper = null + + override getAdditionalPatterns(PatternGenerator patternGenerator, Map fqnToPQuery) { + '''''' + } + + override createConstraintUpdater(LinearTypeExpressionBuilderFactory builderFactory) { + null + } + + def isExact() { + false + } + + def PolyhedronExtensionOperator createPolyhedronExtensionOperator( + Map costElementMatchers) { + null + } + + def setObjective(ThreeValuedCostObjective objective) { + if (this.objective !== null) { + throw new IllegalStateException("Objective was already set") + } + this.objective = objective + } + + def setBoundsProvider(IObjectiveBoundsProvider boundsProvider) { + if (this.boundsProvider !== null) { + throw new IllegalStateException("Objective bounds provider was already set") + } + this.boundsProvider = boundsProvider + } + + protected def buildWithBounds(ExtendedLinearExpressionBuilder builder) { + val bounds = builder.build(this) + if (objective !== null && boundsProvider !== null) { + boundsProvider.computeRequiredBounds(objective, bounds) + } + if (exact && bestUpper !== null) { + bounds.tightenLowerBound(bestUpper) + } + bounds + } + + override boundsSaturated(Integer lower, Integer upper) { + if (upper !== null && (bestUpper === null || bestUpper < upper)) { + bestUpper = upper + } + objective?.boundsSaturated(lower, upper) + } + +} diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/IObjectiveBoundsProvider.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/IObjectiveBoundsProvider.xtend new file mode 100644 index 00000000..3c4d36a5 --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/IObjectiveBoundsProvider.xtend @@ -0,0 +1,8 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization + +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Bounds +import org.eclipse.viatra.dse.objectives.IObjective + +interface IObjectiveBoundsProvider { + def void computeRequiredBounds(IObjective objective, Bounds bounds) +} 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 index 0a6fd55b..9b1a7e9f 100644 --- 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 @@ -1,85 +1,80 @@ package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization -import com.google.common.collect.ImmutableList -import java.util.Collection +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.BoundSaturationListener +import java.util.Map import org.eclipse.viatra.dse.base.ThreadContext -import org.eclipse.viatra.query.runtime.api.IPatternMatch -import org.eclipse.viatra.query.runtime.api.IQuerySpecification -import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher -import org.eclipse.xtend.lib.annotations.Data +import org.eclipse.xtend.lib.annotations.Accessors -@Data -class ThreeValuedCostElement { - val IQuerySpecification> currentMatchQuery - val IQuerySpecification> mayMatchQuery - val IQuerySpecification> mustMatchQuery - val int weight -} - -class ThreeValuedCostObjective extends AbstractThreeValuedObjective { - val Collection costElements - Collection matchers +class ThreeValuedCostObjective extends AbstractThreeValuedObjective implements BoundSaturationListener { + @Accessors val Map matchers + double lowerBoundHint = Double.NEGATIVE_INFINITY + double upperBoundHint = Double.POSITIVE_INFINITY - new(String name, Collection costElements, ObjectiveKind kind, ObjectiveThreshold threshold, + new(String name, Map matchers, ObjectiveKind kind, ObjectiveThreshold threshold, int level) { super(name, kind, threshold, level) - this.costElements = costElements + this.matchers = matchers } override createNew() { - new ThreeValuedCostObjective(name, costElements, kind, threshold, level) + // new ThreeValuedCostObjective(name, matchers, kind, threshold, level) + throw new UnsupportedOperationException("ThreeValuedCostObjective can only be used from a single thread") } override init(ThreadContext context) { - val queryEngine = context.queryEngine - matchers = ImmutableList.copyOf(costElements.map [ element | - new CostElementMatchers( - queryEngine.getMatcher(element.currentMatchQuery), - queryEngine.getMatcher(element.mayMatchQuery), - queryEngine.getMatcher(element.mustMatchQuery), - element.weight - ) - ]) } override getRawFitness(ThreadContext context) { - var int cost = 0 - for (matcher : matchers) { - cost += matcher.weight * matcher.currentMatcher.countMatches + var double cost = 0 + for (matcher : matchers.values) { + cost += matcher.weight * matcher.currentNumberOfMatches } - cost as double + cost } override getLowestPossibleFitness(ThreadContext threadContext) { - var int cost = 0 - for (matcher : matchers) { + var double cost = 0 + for (matcher : matchers.values) { if (matcher.weight >= 0) { - cost += matcher.weight * matcher.mustMatcher.countMatches - } else if (matcher.mayMatcher.countMatches > 0) { - // TODO Count may matches. - return Double.NEGATIVE_INFINITY + cost += matcher.weight * matcher.minimumNumberOfMatches + } else { + cost += matcher.weight * matcher.maximumNumberOfMatches } } - cost as double + val boundWithHint = Math.max(lowerBoundHint, cost) + if (boundWithHint > upperBoundHint) { + throw new IllegalStateException("Inconsistent cost bounds") + } + boundWithHint } override getHighestPossibleFitness(ThreadContext threadContext) { - var int cost = 0 - for (matcher : matchers) { + var double cost = 0 + for (matcher : matchers.values) { if (matcher.weight <= 0) { - cost += matcher.weight * matcher.mustMatcher.countMatches - } else if (matcher.mayMatcher.countMatches > 0) { - return Double.POSITIVE_INFINITY + cost += matcher.weight * matcher.minimumNumberOfMatches + } else { + cost += matcher.weight * matcher.maximumNumberOfMatches } } - cost as double + val boundWithHint = Math.min(upperBoundHint, cost) + if (boundWithHint < lowerBoundHint) { + throw new IllegalStateException("Inconsistent cost bounds") + } + boundWithHint } - @Data - private static class CostElementMatchers { - val ViatraQueryMatcher currentMatcher - val ViatraQueryMatcher mayMatcher - val ViatraQueryMatcher mustMatcher - val int weight + override boundsSaturated(Integer lower, Integer upper) { + lowerBoundHint = if (lower === null) { + Double.NEGATIVE_INFINITY + } else { + lower + } + upperBoundHint = if (upper === null) { + Double.POSITIVE_INFINITY + } else { + upper + } + println('''Bounds saturated: «lower»..«upper»''') } } diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/ThreeValuedCostObjectiveProvider.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/ThreeValuedCostObjectiveProvider.xtend new file mode 100644 index 00000000..c2750acd --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/ThreeValuedCostObjectiveProvider.xtend @@ -0,0 +1,205 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization + +import com.google.common.collect.ImmutableList +import com.google.common.collect.ImmutableMap +import com.google.common.collect.Lists +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.BoolTypeReference +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.ComplexTypeReference +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.IntTypeReference +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RealTypeReference +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Relation +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.StringTypeReference +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeDeclaration +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeReference +import hu.bme.mit.inf.dslreasoner.viatra2logic.viatra2logicannotations.TransfomedViatraQuery +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronExtensionOperator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.ModalPatternQueries +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialBooleanInterpretation +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialComplexTypeInterpretation +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialIntegerInterpretation +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialRealInterpretation +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialStringInterpretation +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.CostObjectiveConfiguration +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.CostObjectiveElementConfiguration +import java.util.Collection +import java.util.Map +import org.eclipse.viatra.dse.objectives.IObjective +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine +import org.eclipse.xtend.lib.annotations.Data + +@Data +class ThreeValuedCostObjectiveProviderResult { + val Collection objectives + val Collection hints + val Collection extensionOperators + val IObjective[][] leveledExtremalObjectives + val boolean optimizationProblem +} + +class ThreeValuedCostObjectiveProvider { + static val COST_OBJECTIVE_LEVEL = 3 + + val ViatraQueryEngine queryEngine + val Map modalRelationQueries + val Map qualifiedNameToRelationMap + val ParameterScopeBound defaultBounds + val ParameterScopeBound booleanBounds + val ParameterScopeBound integerBounds + val ParameterScopeBound realBounds + val ParameterScopeBound stringBounds + val Map typeDeclarationToBoundsMap + + new(ViatraQueryEngine queryEngine, PartialInterpretation interpretation, + Map modalRelationQueries) { + this.queryEngine = queryEngine + this.modalRelationQueries = modalRelationQueries + qualifiedNameToRelationMap = ImmutableMap.copyOf( + interpretation.problem.annotations.filter(TransfomedViatraQuery). + toMap([patternFullyQualifiedName], [target])) + defaultBounds = new PartialInterpretationBasedParameterScopeBound(interpretation) + var ParameterScopeBound booleanBounds = null + var ParameterScopeBound integerBounds = null + var ParameterScopeBound realBounds = null + var ParameterScopeBound stringBounds = null + val typeDeclarationToBoundsMapBuilder = ImmutableMap.builder + for (scope : interpretation.scopes) { + val bounds = new ScopeBasedParameterScopeBound(scope) + switch (typeInterpretation : scope.targetTypeInterpretation) { + PartialBooleanInterpretation: + if (booleanBounds === null) { + booleanBounds = bounds + } else { + throw new IllegalStateException("Duplicate partial boolean interpretation") + } + PartialIntegerInterpretation: + if (integerBounds === null) { + integerBounds = bounds + } else { + throw new IllegalStateException("Duplicate partial integer interpretation") + } + PartialRealInterpretation: + if (realBounds === null) { + realBounds = bounds + } else { + throw new IllegalStateException("Duplicate partial real interpretation") + } + PartialStringInterpretation: + if (stringBounds === null) { + stringBounds = bounds + } else { + throw new IllegalStateException("Duplicate partial string interpretation") + } + PartialComplexTypeInterpretation: + typeDeclarationToBoundsMapBuilder.put(typeInterpretation.interpretationOf, bounds) + } + } + this.booleanBounds = booleanBounds ?: defaultBounds + this.integerBounds = integerBounds ?: defaultBounds + this.realBounds = realBounds ?: defaultBounds + this.stringBounds = stringBounds ?: defaultBounds + typeDeclarationToBoundsMap = typeDeclarationToBoundsMapBuilder.build + } + + def getCostObjectives(Collection costObjectives) { + val objectives = ImmutableList.builder + val hints = ImmutableList.builder + val extensionOperators = ImmutableList.builder + val extremalObjectives = Lists.newArrayListWithExpectedSize(costObjectives.size) + for (entry : costObjectives.indexed) { + val objectiveName = '''costObjective«entry.key»''' + val objectiveConfig = entry.value + val costObjective = transformCostObjective(objectiveConfig, objectiveName) + objectives.add(costObjective) + if (objectiveConfig.findExtremum) { + extremalObjectives += costObjective + } + val hint = objectiveConfig.hint + if (hint !== null) { + hints.add(hint) + hint.objective = costObjective + val extensionOperator = hint.createPolyhedronExtensionOperator(costObjective.matchers) + if (extensionOperator !== null) { + extensionOperators.add(extensionOperator) + } + } + } + new ThreeValuedCostObjectiveProviderResult( + objectives.build, + hints.build, + extensionOperators.build, + newArrayList(extremalObjectives), + !extremalObjectives.empty + ) + } + + private def transformCostObjective(CostObjectiveConfiguration configuration, String name) { + val costElements = ImmutableMap.copyOf(configuration.elements.toMap([patternQualifiedName], [ + transformCostElement + ])) + new ThreeValuedCostObjective(name, costElements, configuration.kind, configuration.threshold, + COST_OBJECTIVE_LEVEL) + } + + private def transformCostElement(CostObjectiveElementConfiguration elementConfig) { + val relationName = elementConfig.patternQualifiedName + val modalQueries = modalRelationQueries.get(relationName) + if (modalQueries === null) { + throw new IllegalArgumentException("Unknown relation queries: " + relationName) + } + val relation = qualifiedNameToRelationMap.get(relationName) + if (relation === null) { + throw new IllegalArgumentException("Unknown transformed relation: " + relationName) + } + val parameterBounds = ImmutableList.copyOf(relation.parameters.map[parameterBound]) + new CostElementMatchers( + queryEngine.getMatcher(modalQueries.currentQuery), + queryEngine.getMatcher(modalQueries.mayQuery), + queryEngine.getMatcher(modalQueries.mustQuery), + parameterBounds, + elementConfig.weight + ) + } + + private def getParameterBound(TypeReference typeReference) { + switch (typeReference) { + BoolTypeReference: booleanBounds + IntTypeReference: integerBounds + RealTypeReference: realBounds + StringTypeReference: stringBounds + ComplexTypeReference: typeDeclarationToBoundsMap.getOrDefault(typeReference.referred, defaultBounds) + } + } + + private static abstract class AbstractParameterScopeBound implements ParameterScopeBound { + override getUpperBound() { + val rawValue = rawUpperBound + if (rawValue < 0) { + Double.POSITIVE_INFINITY + } else { + rawValue + } + } + + protected def int getRawUpperBound() + } + + @Data + private static class ScopeBasedParameterScopeBound extends AbstractParameterScopeBound { + val Scope scope + + override protected getRawUpperBound() { + scope.maxNewElements + } + } + + @Data + private static class PartialInterpretationBasedParameterScopeBound extends AbstractParameterScopeBound { + val PartialInterpretation interpretation + + override protected getRawUpperBound() { + interpretation.maxNewElements + } + } +} diff --git a/Tests/MODELS2020-CaseStudies/case.study.familyTree.run/bin/.gitignore b/Tests/MODELS2020-CaseStudies/case.study.familyTree.run/bin/.gitignore new file mode 100644 index 00000000..7050a7e3 --- /dev/null +++ b/Tests/MODELS2020-CaseStudies/case.study.familyTree.run/bin/.gitignore @@ -0,0 +1 @@ +/queries/ diff --git a/Tests/MODELS2020-CaseStudies/case.study.familyTree.run/bin/queries/.gitignore b/Tests/MODELS2020-CaseStudies/case.study.familyTree.run/bin/queries/.gitignore index 3b9ccef7..19bc3cc8 100644 --- a/Tests/MODELS2020-CaseStudies/case.study.familyTree.run/bin/queries/.gitignore +++ b/Tests/MODELS2020-CaseStudies/case.study.familyTree.run/bin/queries/.gitignore @@ -7,3 +7,7 @@ /.MemberHasParent.java._trace /.TwoMembersHaveNoParent.java._trace /.NegativeAge.java._trace +/MemberHasParent.java +/NegativeAge.java +/ParentTooYoung.java +/TwoMembersHaveNoParent.java diff --git a/Tests/MODELS2020-CaseStudies/case.study.familyTree.run/src-gen/queries/.gitignore b/Tests/MODELS2020-CaseStudies/case.study.familyTree.run/src-gen/queries/.gitignore index 3b9ccef7..19bc3cc8 100644 --- a/Tests/MODELS2020-CaseStudies/case.study.familyTree.run/src-gen/queries/.gitignore +++ b/Tests/MODELS2020-CaseStudies/case.study.familyTree.run/src-gen/queries/.gitignore @@ -7,3 +7,7 @@ /.MemberHasParent.java._trace /.TwoMembersHaveNoParent.java._trace /.NegativeAge.java._trace +/MemberHasParent.java +/NegativeAge.java +/ParentTooYoung.java +/TwoMembersHaveNoParent.java diff --git a/Tests/MODELS2020-CaseStudies/case.study.pledge.originalFiles/xtend-gen/converter/.UML2TGF.xtendbin b/Tests/MODELS2020-CaseStudies/case.study.pledge.originalFiles/xtend-gen/converter/.UML2TGF.xtendbin index 5c5071cc..23513b51 100644 Binary files a/Tests/MODELS2020-CaseStudies/case.study.pledge.originalFiles/xtend-gen/converter/.UML2TGF.xtendbin and b/Tests/MODELS2020-CaseStudies/case.study.pledge.originalFiles/xtend-gen/converter/.UML2TGF.xtendbin differ diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/FileSystemInconsistencyDetector.xtend b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/FileSystemInconsistencyDetector.xtend index f4f36951..9cc6e415 100644 --- a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/FileSystemInconsistencyDetector.xtend +++ b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/FileSystemInconsistencyDetector.xtend @@ -1,10 +1,10 @@ package hu.bme.mit.inf.dslreasoner.run -import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethod import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethodBasedGlobalConstraint -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod import org.eclipse.viatra.dse.base.ThreadContext +import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher class FileSystemInconsistencyDetector extends ModelGenerationMethodBasedGlobalConstraint { var PartialInterpretation partialInterpretation diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/MetamodelLoader.xtend b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/MetamodelLoader.xtend index bf9ca274..cbc692b3 100644 --- a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/MetamodelLoader.xtend +++ b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/MetamodelLoader.xtend @@ -12,8 +12,8 @@ import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace import hu.bme.mit.inf.dslreasoner.ecore2logic.EcoreMetamodelDescriptor import hu.bme.mit.inf.dslreasoner.partialsnapshot_mavo.yakindu.Patterns import hu.bme.mit.inf.dslreasoner.viatra2logic.ViatraQuerySetDescriptor -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethod import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethodBasedGlobalConstraint import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace import java.util.Collection diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SGraphInconsistencyDetector.xtend b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SGraphInconsistencyDetector.xtend index 22addd3d..b8167566 100644 --- a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SGraphInconsistencyDetector.xtend +++ b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SGraphInconsistencyDetector.xtend @@ -1,7 +1,7 @@ package hu.bme.mit.inf.dslreasoner.run -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethod import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethodBasedGlobalConstraint import org.eclipse.viatra.dse.base.ThreadContext import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher -- cgit v1.2.3-70-g09d2