From 77fda749551e2cbba552e38d5dbae7f8d4af3ae1 Mon Sep 17 00:00:00 2001 From: jkauttio Date: Thu, 4 Sep 2014 11:03:45 +0000 Subject: [PATCH] Create a new branch for BPMN import prototype refs #5197 git-svn-id: https://www.simantics.org/svn/simantics/sysdyn/branches/bpmn-import@30211 ac1ea38d-2e2b-0410-8846-a27921b304fc --- org.simantics.sysdyn/.classpath | 7 + org.simantics.sysdyn/.hgignore | 5 + org.simantics.sysdyn/.project | 28 + .../.settings/org.eclipse.jdt.core.prefs | 8 + org.simantics.sysdyn/META-INF/MANIFEST.MF | 61 + org.simantics.sysdyn/ModelicaParser.html | 727 +++ org.simantics.sysdyn/adapters.xml | 109 + org.simantics.sysdyn/bpmn/BPMN20.xsd | 37 + org.simantics.sysdyn/bpmn/BPMNDI.xsd | 100 + org.simantics.sysdyn/bpmn/DC.xsd | 29 + org.simantics.sysdyn/bpmn/DI.xsd | 100 + org.simantics.sysdyn/bpmn/Semantic.xsd | 1562 +++++++ org.simantics.sysdyn/bpmn/generate.bat | 2 + org.simantics.sysdyn/bpmn/helloworld.xml | 55 + org.simantics.sysdyn/build.properties | 18 + org.simantics.sysdyn/plugin.xml | 19 + org.simantics.sysdyn/scl/Simantics/Sysdyn.scl | 110 + .../src/org/simantics/sysdyn/Activator.java | 64 + .../src/org/simantics/sysdyn/Functions.java | 269 ++ .../src/org/simantics/sysdyn/TestParser.java | 233 + .../adapter/ActiveDatasetsIndexVariable.java | 56 + .../sysdyn/adapter/CustomMigrationStep.java | 58 + .../sysdyn/adapter/IndexVariable.java | 272 ++ .../sysdyn/adapter/NamesIndexVariable.java | 29 + .../SensitivityExperimentParameter.java | 105 + .../sysdyn/adapter/TimeIndexVariable.java | 32 + .../sysdyn/adapter/TimesIndexVariable.java | 52 + .../sysdyn/adapter/ValueIndexVariable.java | 42 + .../adapter/ValueIndexVariableBase.java | 140 + .../sysdyn/adapter/ValueIndexVariableI.java | 58 + .../sysdyn/adapter/ValuesIndexVariable.java | 62 + .../sysdyn/adapter/VariableRVIUtils.java | 345 ++ .../adapter/VariableValueSubscription.java | 111 + .../adapter/distribution/IDistribution.java | 27 + .../sysdyn/adapter/distribution/Interval.java | 84 + .../distribution/NormalDistribution.java | 404 ++ .../distribution/UniformDistribution.java | 57 + .../generator/HaltonSequenceGenerator.java | 95 + .../sysdyn/adapter/generator/IGenerator.java | 34 + .../adapter/generator/RandomGenerator.java | 64 + .../elementaryCycles/AdjacencyList.java | 46 + .../ElementaryCyclesSearch.java | 167 + .../sysdyn/elementaryCycles/SCCResult.java | 34 + .../StrongConnectedComponents.java | 280 ++ .../sysdyn/elementaryCycles/TestCycles.java | 68 + .../sysdyn/elementaryCycles/license.txt | 11 + .../expressionParser/ExpressionParser.java | 1862 ++++++++ .../expressionParser/ExpressionParser.jj | 430 ++ .../ExpressionParserConstants.java | 130 + .../ExpressionParserTokenManager.java | 1361 ++++++ .../expressionParser/ParseException.java | 196 + .../expressionParser/SimpleCharStream.java | 480 ++ .../TestExpressionParser.java | 47 + .../sysdyn/expressionParser/Token.java | 155 + .../expressionParser/TokenMgrError.java | 156 + .../sysdyn/manager/ActiveResults.java | 71 + .../simantics/sysdyn/manager/FileResult.java | 116 + .../sysdyn/manager/FunctionUtils.java | 260 ++ .../simantics/sysdyn/manager/GameResult.java | 33 + .../sysdyn/manager/HistoryDatasetResult.java | 324 ++ .../sysdyn/manager/HistoryDatasetUtils.java | 92 + .../sysdyn/manager/MemoryResult.java | 249 ++ .../sysdyn/manager/OldSysdynExperiment.java | 893 ++++ .../sysdyn/manager/SaveResultJob.java | 126 + .../sysdyn/manager/SaveResultSetJob.java | 153 + .../sysdyn/manager/SimulateDurationJob.java | 102 + .../sysdyn/manager/SysdynConsole.java | 205 + .../sysdyn/manager/SysdynDataSet.java | 38 + .../sysdyn/manager/SysdynExperiment.java | 451 ++ .../sysdyn/manager/SysdynExperiments.java | 300 ++ .../sysdyn/manager/SysdynGameExperiment.java | 415 ++ .../manager/SysdynGameExperimentBase.java | 218 + .../manager/SysdynGameExperimentInternal.java | 181 + .../simantics/sysdyn/manager/SysdynModel.java | 589 +++ .../sysdyn/manager/SysdynModelManager.java | 84 + .../manager/SysdynPlaybackExperiment.java | 285 ++ .../sysdyn/manager/SysdynResult.java | 41 + .../SysdynSensitivityAnalysisExperiment.java | 378 ++ .../manager/VariableSubscriptionManager.java | 16 + .../sysdyn/modelExport/ExportConstants.java | 10 + .../modelExport/SysdynModelExporter.java | 133 + .../sysdyn/modelImport/BPMNParser.java | 105 + .../sysdyn/modelImport/IModelParser.java | 9 + .../sysdyn/modelImport/MdlParser.java | 325 ++ .../simantics/sysdyn/modelImport/MdlUtil.java | 310 ++ .../sysdyn/modelImport/bpmn/BPMNDiagram.java | 106 + .../sysdyn/modelImport/bpmn/BPMNEdge.java | 182 + .../sysdyn/modelImport/bpmn/BPMNLabel.java | 69 + .../modelImport/bpmn/BPMNLabelStyle.java | 71 + .../sysdyn/modelImport/bpmn/BPMNPlane.java | 69 + .../sysdyn/modelImport/bpmn/BPMNShape.java | 263 ++ .../sysdyn/modelImport/bpmn/Bounds.java | 114 + .../sysdyn/modelImport/bpmn/Diagram.java | 157 + .../modelImport/bpmn/DiagramElement.java | 205 + .../sysdyn/modelImport/bpmn/Edge.java | 83 + .../sysdyn/modelImport/bpmn/Font.java | 200 + .../sysdyn/modelImport/bpmn/Label.java | 76 + .../sysdyn/modelImport/bpmn/LabeledEdge.java | 44 + .../sysdyn/modelImport/bpmn/LabeledShape.java | 44 + .../modelImport/bpmn/MessageVisibleKind.java | 58 + .../sysdyn/modelImport/bpmn/Node.java | 46 + .../modelImport/bpmn/ObjectFactory.java | 2741 ++++++++++++ .../modelImport/bpmn/ParticipantBandKind.java | 70 + .../sysdyn/modelImport/bpmn/Plane.java | 86 + .../sysdyn/modelImport/bpmn/Point.java | 76 + .../sysdyn/modelImport/bpmn/Shape.java | 76 + .../sysdyn/modelImport/bpmn/Style.java | 76 + .../sysdyn/modelImport/bpmn/TActivity.java | 370 ++ .../modelImport/bpmn/TAdHocOrdering.java | 58 + .../modelImport/bpmn/TAdHocSubProcess.java | 129 + .../sysdyn/modelImport/bpmn/TArtifact.java | 46 + .../sysdyn/modelImport/bpmn/TAssignment.java | 100 + .../sysdyn/modelImport/bpmn/TAssociation.java | 127 + .../bpmn/TAssociationDirection.java | 61 + .../sysdyn/modelImport/bpmn/TAuditing.java | 40 + .../sysdyn/modelImport/bpmn/TBaseElement.java | 203 + .../bpmn/TBaseElementWithMixedContent.java | 151 + .../modelImport/bpmn/TBoundaryEvent.java | 100 + .../modelImport/bpmn/TBusinessRuleTask.java | 72 + .../modelImport/bpmn/TCallActivity.java | 69 + .../modelImport/bpmn/TCallChoreography.java | 106 + .../modelImport/bpmn/TCallConversation.java | 106 + .../modelImport/bpmn/TCallableElement.java | 170 + .../bpmn/TCancelEventDefinition.java | 40 + .../sysdyn/modelImport/bpmn/TCatchEvent.java | 252 ++ .../sysdyn/modelImport/bpmn/TCategory.java | 105 + .../modelImport/bpmn/TCategoryValue.java | 68 + .../modelImport/bpmn/TChoreography.java | 115 + .../bpmn/TChoreographyActivity.java | 177 + .../bpmn/TChoreographyLoopType.java | 64 + .../modelImport/bpmn/TChoreographyTask.java | 80 + .../modelImport/bpmn/TCollaboration.java | 440 ++ .../bpmn/TCompensateEventDefinition.java | 96 + .../bpmn/TComplexBehaviorDefinition.java | 99 + .../modelImport/bpmn/TComplexGateway.java | 102 + .../bpmn/TConditionalEventDefinition.java | 72 + .../modelImport/bpmn/TConversation.java | 40 + .../bpmn/TConversationAssociation.java | 96 + .../modelImport/bpmn/TConversationLink.java | 123 + .../modelImport/bpmn/TConversationNode.java | 176 + .../modelImport/bpmn/TCorrelationKey.java | 106 + .../bpmn/TCorrelationProperty.java | 135 + .../bpmn/TCorrelationPropertyBinding.java | 101 + ...orrelationPropertyRetrievalExpression.java | 101 + .../bpmn/TCorrelationSubscription.java | 106 + .../modelImport/bpmn/TDataAssociation.java | 177 + .../sysdyn/modelImport/bpmn/TDataInput.java | 157 + .../bpmn/TDataInputAssociation.java | 40 + .../sysdyn/modelImport/bpmn/TDataObject.java | 130 + .../bpmn/TDataObjectReference.java | 130 + .../sysdyn/modelImport/bpmn/TDataOutput.java | 157 + .../bpmn/TDataOutputAssociation.java | 40 + .../sysdyn/modelImport/bpmn/TDataState.java | 68 + .../sysdyn/modelImport/bpmn/TDataStore.java | 185 + .../modelImport/bpmn/TDataStoreReference.java | 126 + .../sysdyn/modelImport/bpmn/TDefinitions.java | 475 ++ .../modelImport/bpmn/TDocumentation.java | 147 + .../sysdyn/modelImport/bpmn/TEndEvent.java | 40 + .../sysdyn/modelImport/bpmn/TEndPoint.java | 40 + .../sysdyn/modelImport/bpmn/TError.java | 123 + .../bpmn/TErrorEventDefinition.java | 69 + .../sysdyn/modelImport/bpmn/TEscalation.java | 123 + .../bpmn/TEscalationEventDefinition.java | 69 + .../sysdyn/modelImport/bpmn/TEvent.java | 82 + .../modelImport/bpmn/TEventBasedGateway.java | 103 + .../bpmn/TEventBasedGatewayType.java | 58 + .../modelImport/bpmn/TEventDefinition.java | 53 + .../modelImport/bpmn/TExclusiveGateway.java | 72 + .../sysdyn/modelImport/bpmn/TExpression.java | 44 + .../sysdyn/modelImport/bpmn/TExtension.java | 134 + .../modelImport/bpmn/TExtensionElements.java | 78 + .../sysdyn/modelImport/bpmn/TFlowElement.java | 168 + .../sysdyn/modelImport/bpmn/TFlowNode.java | 117 + .../modelImport/bpmn/TFormalExpression.java | 98 + .../sysdyn/modelImport/bpmn/TGateway.java | 80 + .../modelImport/bpmn/TGatewayDirection.java | 64 + .../bpmn/TGlobalBusinessRuleTask.java | 72 + .../bpmn/TGlobalChoreographyTask.java | 69 + .../modelImport/bpmn/TGlobalConversation.java | 40 + .../modelImport/bpmn/TGlobalManualTask.java | 40 + .../modelImport/bpmn/TGlobalScriptTask.java | 100 + .../sysdyn/modelImport/bpmn/TGlobalTask.java | 90 + .../modelImport/bpmn/TGlobalUserTask.java | 109 + .../sysdyn/modelImport/bpmn/TGroup.java | 69 + .../modelImport/bpmn/THumanPerformer.java | 44 + .../modelImport/bpmn/TImplicitThrowEvent.java | 40 + .../sysdyn/modelImport/bpmn/TImport.java | 122 + .../modelImport/bpmn/TInclusiveGateway.java | 72 + .../modelImport/bpmn/TInputOutputBinding.java | 129 + .../bpmn/TInputOutputSpecification.java | 176 + .../sysdyn/modelImport/bpmn/TInputSet.java | 207 + .../sysdyn/modelImport/bpmn/TInterface.java | 135 + .../bpmn/TIntermediateCatchEvent.java | 40 + .../bpmn/TIntermediateThrowEvent.java | 40 + .../modelImport/bpmn/TItemDefinition.java | 131 + .../sysdyn/modelImport/bpmn/TItemKind.java | 58 + .../sysdyn/modelImport/bpmn/TLane.java | 190 + .../sysdyn/modelImport/bpmn/TLaneSet.java | 105 + .../bpmn/TLinkEventDefinition.java | 133 + .../bpmn/TLoopCharacteristics.java | 45 + .../sysdyn/modelImport/bpmn/TManualTask.java | 40 + .../sysdyn/modelImport/bpmn/TMessage.java | 96 + .../bpmn/TMessageEventDefinition.java | 99 + .../sysdyn/modelImport/bpmn/TMessageFlow.java | 150 + .../bpmn/TMessageFlowAssociation.java | 96 + .../sysdyn/modelImport/bpmn/TMonitoring.java | 40 + .../bpmn/TMultiInstanceFlowCondition.java | 64 + .../TMultiInstanceLoopCharacteristics.java | 357 ++ .../sysdyn/modelImport/bpmn/TOperation.java | 189 + .../sysdyn/modelImport/bpmn/TOutputSet.java | 207 + .../modelImport/bpmn/TParallelGateway.java | 40 + .../sysdyn/modelImport/bpmn/TParticipant.java | 192 + .../bpmn/TParticipantAssociation.java | 101 + .../bpmn/TParticipantMultiplicity.java | 103 + .../modelImport/bpmn/TPartnerEntity.java | 106 + .../sysdyn/modelImport/bpmn/TPartnerRole.java | 106 + .../sysdyn/modelImport/bpmn/TPerformer.java | 44 + .../modelImport/bpmn/TPotentialOwner.java | 40 + .../sysdyn/modelImport/bpmn/TProcess.java | 483 ++ .../sysdyn/modelImport/bpmn/TProcessType.java | 61 + .../sysdyn/modelImport/bpmn/TProperty.java | 126 + .../sysdyn/modelImport/bpmn/TReceiveTask.java | 158 + .../modelImport/bpmn/TRelationship.java | 168 + .../bpmn/TRelationshipDirection.java | 64 + .../sysdyn/modelImport/bpmn/TRendering.java | 40 + .../sysdyn/modelImport/bpmn/TResource.java | 105 + .../bpmn/TResourceAssignmentExpression.java | 75 + .../modelImport/bpmn/TResourceParameter.java | 123 + .../bpmn/TResourceParameterBinding.java | 104 + .../modelImport/bpmn/TResourceRole.java | 166 + .../sysdyn/modelImport/bpmn/TRootElement.java | 59 + .../sysdyn/modelImport/bpmn/TScript.java | 81 + .../sysdyn/modelImport/bpmn/TScriptTask.java | 98 + .../sysdyn/modelImport/bpmn/TSendTask.java | 127 + .../modelImport/bpmn/TSequenceFlow.java | 158 + .../sysdyn/modelImport/bpmn/TServiceTask.java | 100 + .../sysdyn/modelImport/bpmn/TSignal.java | 96 + .../bpmn/TSignalEventDefinition.java | 69 + .../bpmn/TStandardLoopCharacteristics.java | 130 + .../sysdyn/modelImport/bpmn/TStartEvent.java | 72 + .../modelImport/bpmn/TSubChoreography.java | 147 + .../modelImport/bpmn/TSubConversation.java | 83 + .../sysdyn/modelImport/bpmn/TSubProcess.java | 216 + .../sysdyn/modelImport/bpmn/TTask.java | 50 + .../bpmn/TTerminateEventDefinition.java | 40 + .../sysdyn/modelImport/bpmn/TText.java | 81 + .../modelImport/bpmn/TTextAnnotation.java | 102 + .../sysdyn/modelImport/bpmn/TThrowEvent.java | 220 + .../bpmn/TTimerEventDefinition.java | 124 + .../sysdyn/modelImport/bpmn/TTransaction.java | 72 + .../sysdyn/modelImport/bpmn/TUserTask.java | 109 + .../sysdyn/modelImport/bpmn/package-info.java | 9 + .../sysdyn/modelImport/mdl/Declaration.java | 65 + .../sysdyn/modelImport/mdl/Lookup.java | 125 + .../sysdyn/modelImport/mdl/MdlModel.java | 141 + .../sysdyn/modelImport/mdl/MdlVariable.java | 216 + .../sysdyn/modelImport/mdl/Sketch.java | 164 + .../sysdyn/modelImport/mdl/SketchComment.java | 74 + .../modelImport/mdl/SketchConnection.java | 173 + .../sysdyn/modelImport/mdl/SketchElement.java | 144 + .../sysdyn/modelImport/mdl/SketchObject.java | 39 + .../sysdyn/modelImport/mdl/SketchValve.java | 57 + .../modelImport/mdl/SketchVariable.java | 66 + .../sysdyn/modelImport/mdl/Subscript.java | 79 + .../modelImport/mdl/SubscriptVariable.java | 292 ++ .../sysdyn/modelImport/model/Auxiliary.java | 29 + .../sysdyn/modelImport/model/Cloud.java | 50 + .../sysdyn/modelImport/model/Comment.java | 57 + .../sysdyn/modelImport/model/Connection.java | 96 + .../sysdyn/modelImport/model/Dependency.java | 87 + .../sysdyn/modelImport/model/Flow.java | 46 + .../modelImport/model/IWriteableObject.java | 37 + .../sysdyn/modelImport/model/Model.java | 223 + .../sysdyn/modelImport/model/Shadow.java | 67 + .../sysdyn/modelImport/model/Stock.java | 29 + .../sysdyn/modelImport/model/Symbol.java | 101 + .../sysdyn/modelImport/model/Valve.java | 87 + .../sysdyn/modelImport/model/Variable.java | 125 + .../modelImport/model/WriteContext.java | 45 + .../model/expression/DelayExpression.java | 48 + .../expression/EnumerationExpression.java | 87 + .../model/expression/Expression.java | 49 + .../model/expression/IntegralExpression.java | 43 + .../model/expression/LookupExpression.java | 66 + .../model/expression/NormalExpression.java | 51 + .../model/support/Enumeration.java | 62 + .../modelImport/model/support/Function.java | 65 + .../modelImport/model/support/Range.java | 46 + .../sysdyn/modelParser/ModelParser.java | 3880 +++++++++++++++++ .../modelParser/ModelParserConstants.java | 131 + .../modelParser/ModelParserTokenManager.java | 1448 ++++++ .../sysdyn/modelParser/ModelicaParser.jj | 741 ++++ .../sysdyn/modelParser/ParseException.java | 187 + .../sysdyn/modelParser/SimpleCharStream.java | 471 ++ .../simantics/sysdyn/modelParser/Token.java | 131 + .../sysdyn/modelParser/TokenMgrError.java | 147 + .../sysdyn/modelica/ModelicaWriter.java | 506 +++ .../sysdyn/refactoring/TGRefactoring.java | 91 + .../sysdyn/refactoring/mappingSpec.txt | 38 + .../sysdyn/representation/Auxiliary.java | 24 + .../simantics/sysdyn/representation/Book.java | 58 + .../sysdyn/representation/Cloud.java | 24 + .../sysdyn/representation/Configuration.java | 98 + .../sysdyn/representation/Dependency.java | 44 + .../representation/DiagramContainerDummy.java | 26 + .../sysdyn/representation/Entity.java | 30 + .../sysdyn/representation/Enumeration.java | 112 + .../representation/EnumerationIndex.java | 29 + .../simantics/sysdyn/representation/Flow.java | 38 + .../sysdyn/representation/Function.java | 82 + .../representation/FunctionLibrary.java | 78 + .../sysdyn/representation/IElement.java | 18 + .../representation/IndependentVariable.java | 214 + .../sysdyn/representation/Input.java | 142 + .../sysdyn/representation/LibraryDummy.java | 43 + .../representation/LoadRepresentation.java | 102 + .../simantics/sysdyn/representation/Loop.java | 92 + .../sysdyn/representation/Model.java | 254 ++ .../sysdyn/representation/Module.java | 363 ++ .../sysdyn/representation/ModuleType.java | 67 + .../representation/ParameterOverride.java | 59 + .../sysdyn/representation/Redeclaration.java | 54 + .../sysdyn/representation/Shadow.java | 102 + .../representation/SharedFunctionLibrary.java | 26 + .../sysdyn/representation/Sheet.java | 329 ++ .../sysdyn/representation/Stock.java | 117 + .../sysdyn/representation/SysdynSchema.java | 71 + .../sysdyn/representation/Valve.java | 24 + .../sysdyn/representation/Variability.java | 298 ++ .../sysdyn/representation/Variable.java | 163 + .../annotations/BuiltinFunctions.java | 31 + .../annotations/BuiltinFunctionsAccessor.java | 57 + .../annotations/BuiltinFunctionsFactory.java | 36 + .../expressions/ConstantExpression.java | 41 + .../expressions/DelayExpression.java | 146 + .../expressions/Expression.java | 96 + .../expressions/IExpression.java | 87 + .../expressions/LookupExpression.java | 20 + .../expressions/NormalExpression.java | 51 + .../expressions/ParameterExpression.java | 62 + .../expressions/StockExpression.java | 157 + .../expressions/WithLookupExpression.java | 192 + .../representation/utils/FormatUtils.java | 157 + .../representation/utils/IndexUtils.java | 144 + .../utils/RepresentationUtils.java | 196 + .../utils/SheetFormatUtils.java | 113 + .../representation/utils/UnitUtils.java | 266 ++ .../visitors/ElementVisitorVoidAdapter.java | 91 + .../visitors/IElementVisitorVoid.java | 48 + .../sysdyn/simulation/SimulationJob.java | 108 + .../simulation/SimulationScheduler.java | 44 + .../org/simantics/sysdyn/solver/ISolver.java | 23 + .../sysdyn/solver/ISolverMonitor.java | 9 + .../sysdyn/solver/InternalSolver.java | 218 + .../sysdyn/solver/InternalSolverResult.java | 29 + .../sysdyn/solver/ModelicaSolver.java | 93 + .../sysdyn/solver/SolverParameters.java | 13 + .../sysdyn/solver/SolverSettings.java | 36 + .../sysdyn/solver/SysdynSimulationJob.java | 99 + .../sysdyn/tableParser/ParseException.java | 198 + .../sysdyn/tableParser/SimpleCharStream.java | 482 ++ .../sysdyn/tableParser/TableParser.java | 303 ++ .../sysdyn/tableParser/TableParser.jj | 104 + .../tableParser/TableParserConstants.java | 132 + .../tableParser/TableParserTokenManager.java | 1462 +++++++ .../simantics/sysdyn/tableParser/Token.java | 142 + .../sysdyn/tableParser/TokenMgrError.java | 158 + .../sysdyn/unitParser/JJTUnitParserState.java | 123 + .../org/simantics/sysdyn/unitParser/Node.java | 36 + .../sysdyn/unitParser/ParseException.java | 187 + .../sysdyn/unitParser/SimpleCharStream.java | 471 ++ .../sysdyn/unitParser/SimpleNode.java | 94 + .../simantics/sysdyn/unitParser/Token.java | 131 + .../sysdyn/unitParser/TokenMgrError.java | 147 + .../unitParser/UnitCheckingException.java | 21 + .../sysdyn/unitParser/UnitCheckingNode.java | 54 + .../unitParser/UnitCheckingNodeFactory.java | 110 + .../sysdyn/unitParser/UnitParser.java | 2723 ++++++++++++ .../simantics/sysdyn/unitParser/UnitParser.jj | 1250 ++++++ .../sysdyn/unitParser/UnitParser.jjt | 282 ++ .../unitParser/UnitParserConstants.java | 127 + .../unitParser/UnitParserTokenManager.java | 1408 ++++++ .../unitParser/UnitParserTreeConstants.java | 89 + .../sysdyn/unitParser/nodes/AddOp.java | 42 + .../sysdyn/unitParser/nodes/Arithmetic.java | 69 + .../unitParser/nodes/ArrayDefinition.java | 105 + .../unitParser/nodes/ComponentIdentity.java | 42 + .../unitParser/nodes/ComponentReference.java | 41 + .../nodes/ComponentReferenceFull.java | 85 + .../sysdyn/unitParser/nodes/Condition.java | 27 + .../sysdyn/unitParser/nodes/Divide.java | 42 + .../sysdyn/unitParser/nodes/Expression.java | 27 + .../sysdyn/unitParser/nodes/Factor.java | 121 + .../sysdyn/unitParser/nodes/ForIndex.java | 39 + .../unitParser/nodes/FunctionArguments.java | 27 + .../sysdyn/unitParser/nodes/FunctionCall.java | 204 + .../sysdyn/unitParser/nodes/IfThenElse.java | 69 + .../unitParser/nodes/LogicalExpression.java | 49 + .../unitParser/nodes/LogicalFactor.java | 49 + .../sysdyn/unitParser/nodes/LogicalTerm.java | 49 + .../unitParser/nodes/Multiplication.java | 42 + .../unitParser/nodes/NamedArguments.java | 27 + .../nodes/ParenthesisExpression.java | 39 + .../sysdyn/unitParser/nodes/Power.java | 40 + .../sysdyn/unitParser/nodes/RelOp.java | 42 + .../sysdyn/unitParser/nodes/Relation.java | 78 + .../sysdyn/unitParser/nodes/Term.java | 107 + .../sysdyn/unitParser/nodes/UnitResult.java | 289 ++ .../sysdyn/unitParser/nodes/Value.java | 41 + .../sysdyn/utils/DocumentationUtils.java | 664 +++ .../org/simantics/sysdyn/utils/Function.java | 562 +++ .../sysdyn/utils/GetConfigurationRequest.java | 42 + .../org/simantics/sysdyn/utils/LoopUtils.java | 336 ++ .../simantics/sysdyn/utils/ModelUtils.java | 216 + .../simantics/sysdyn/utils/ModuleSummary.java | 103 + .../sysdyn/utils/ModuleSummaryRequest.java | 146 + .../sysdyn/utils/ProfileEntries.java | 68 + .../sysdyn/utils/SelectionUtils.java | 24 + .../simantics/sysdyn/utils/SheetUtils.java | 126 + .../sysdyn/utils/imports/ImportUtils.java | 660 +++ .../SysdynFunctionLibraryImportAdvisor.java | 61 + .../imports/SysdynImportFormatHandler.java | 111 + .../testModels/MaintenanceModel_2012-12-03.tg | Bin 0 -> 369301 bytes .../testModels/Model1412Health.tg | Bin 0 -> 997397 bytes .../testModels/WorkModel_2012-12-03.tg | Bin 0 -> 49748 bytes .../testModels/openprod_demo_2012-12-03.tg | Bin 0 -> 187511 bytes .../testModels/references.txt | 5 + 427 files changed, 70804 insertions(+) create mode 100644 org.simantics.sysdyn/.classpath create mode 100644 org.simantics.sysdyn/.hgignore create mode 100644 org.simantics.sysdyn/.project create mode 100644 org.simantics.sysdyn/.settings/org.eclipse.jdt.core.prefs create mode 100644 org.simantics.sysdyn/META-INF/MANIFEST.MF create mode 100644 org.simantics.sysdyn/ModelicaParser.html create mode 100644 org.simantics.sysdyn/adapters.xml create mode 100644 org.simantics.sysdyn/bpmn/BPMN20.xsd create mode 100644 org.simantics.sysdyn/bpmn/BPMNDI.xsd create mode 100644 org.simantics.sysdyn/bpmn/DC.xsd create mode 100644 org.simantics.sysdyn/bpmn/DI.xsd create mode 100644 org.simantics.sysdyn/bpmn/Semantic.xsd create mode 100644 org.simantics.sysdyn/bpmn/generate.bat create mode 100644 org.simantics.sysdyn/bpmn/helloworld.xml create mode 100644 org.simantics.sysdyn/build.properties create mode 100644 org.simantics.sysdyn/plugin.xml create mode 100644 org.simantics.sysdyn/scl/Simantics/Sysdyn.scl create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/Activator.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/Functions.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/TestParser.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ActiveDatasetsIndexVariable.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/CustomMigrationStep.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/IndexVariable.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/NamesIndexVariable.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/SensitivityExperimentParameter.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/TimeIndexVariable.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/TimesIndexVariable.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariable.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariableBase.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariableI.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValuesIndexVariable.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/VariableRVIUtils.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/VariableValueSubscription.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/IDistribution.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/Interval.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/NormalDistribution.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/UniformDistribution.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/generator/HaltonSequenceGenerator.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/generator/IGenerator.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/generator/RandomGenerator.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/AdjacencyList.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/ElementaryCyclesSearch.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/SCCResult.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/StrongConnectedComponents.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/TestCycles.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/license.txt create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParser.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParser.jj create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParserConstants.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParserTokenManager.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ParseException.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/SimpleCharStream.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/TestExpressionParser.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/Token.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/TokenMgrError.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/ActiveResults.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/FileResult.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/FunctionUtils.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/GameResult.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/HistoryDatasetResult.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/HistoryDatasetUtils.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/MemoryResult.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/OldSysdynExperiment.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SaveResultJob.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SaveResultSetJob.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SimulateDurationJob.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynConsole.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynDataSet.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiment.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiments.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperiment.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperimentBase.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperimentInternal.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModel.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModelManager.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynPlaybackExperiment.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynResult.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynSensitivityAnalysisExperiment.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/manager/VariableSubscriptionManager.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelExport/ExportConstants.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelExport/SysdynModelExporter.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/BPMNParser.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/IModelParser.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/MdlParser.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/MdlUtil.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNDiagram.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNEdge.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNLabel.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNLabelStyle.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNPlane.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNShape.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Bounds.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Diagram.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/DiagramElement.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Edge.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Font.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Label.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/LabeledEdge.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/LabeledShape.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/MessageVisibleKind.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Node.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/ObjectFactory.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/ParticipantBandKind.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Plane.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Point.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Shape.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Style.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TActivity.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TAdHocOrdering.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TAdHocSubProcess.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TArtifact.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TAssignment.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TAssociation.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TAssociationDirection.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TAuditing.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TBaseElement.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TBaseElementWithMixedContent.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TBoundaryEvent.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TBusinessRuleTask.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TCallActivity.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TCallChoreography.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TCallConversation.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TCallableElement.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TCancelEventDefinition.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TCatchEvent.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TCategory.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TCategoryValue.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TChoreography.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TChoreographyActivity.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TChoreographyLoopType.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TChoreographyTask.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TCollaboration.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TCompensateEventDefinition.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TComplexBehaviorDefinition.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TComplexGateway.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TConditionalEventDefinition.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TConversation.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TConversationAssociation.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TConversationLink.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TConversationNode.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TCorrelationKey.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TCorrelationProperty.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TCorrelationPropertyBinding.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TCorrelationPropertyRetrievalExpression.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TCorrelationSubscription.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TDataAssociation.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TDataInput.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TDataInputAssociation.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TDataObject.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TDataObjectReference.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TDataOutput.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TDataOutputAssociation.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TDataState.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TDataStore.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TDataStoreReference.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TDefinitions.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TDocumentation.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TEndEvent.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TEndPoint.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TError.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TErrorEventDefinition.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TEscalation.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TEscalationEventDefinition.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TEvent.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TEventBasedGateway.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TEventBasedGatewayType.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TEventDefinition.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TExclusiveGateway.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TExpression.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TExtension.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TExtensionElements.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TFlowElement.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TFlowNode.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TFormalExpression.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TGateway.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TGatewayDirection.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TGlobalBusinessRuleTask.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TGlobalChoreographyTask.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TGlobalConversation.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TGlobalManualTask.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TGlobalScriptTask.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TGlobalTask.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TGlobalUserTask.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TGroup.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/THumanPerformer.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TImplicitThrowEvent.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TImport.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TInclusiveGateway.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TInputOutputBinding.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TInputOutputSpecification.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TInputSet.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TInterface.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TIntermediateCatchEvent.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TIntermediateThrowEvent.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TItemDefinition.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TItemKind.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TLane.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TLaneSet.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TLinkEventDefinition.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TLoopCharacteristics.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TManualTask.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TMessage.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TMessageEventDefinition.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TMessageFlow.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TMessageFlowAssociation.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TMonitoring.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TMultiInstanceFlowCondition.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TMultiInstanceLoopCharacteristics.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TOperation.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TOutputSet.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TParallelGateway.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TParticipant.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TParticipantAssociation.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TParticipantMultiplicity.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TPartnerEntity.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TPartnerRole.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TPerformer.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TPotentialOwner.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TProcess.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TProcessType.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TProperty.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TReceiveTask.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TRelationship.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TRelationshipDirection.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TRendering.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TResource.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TResourceAssignmentExpression.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TResourceParameter.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TResourceParameterBinding.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TResourceRole.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TRootElement.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TScript.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TScriptTask.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TSendTask.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TSequenceFlow.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TServiceTask.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TSignal.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TSignalEventDefinition.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TStandardLoopCharacteristics.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TStartEvent.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TSubChoreography.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TSubConversation.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TSubProcess.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TTask.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TTerminateEventDefinition.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TText.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TTextAnnotation.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TThrowEvent.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TTimerEventDefinition.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TTransaction.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/TUserTask.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/package-info.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/Declaration.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/Lookup.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/MdlModel.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/MdlVariable.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/Sketch.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchComment.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchConnection.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchElement.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchObject.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchValve.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchVariable.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/Subscript.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SubscriptVariable.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Auxiliary.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Cloud.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Comment.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Connection.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Dependency.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Flow.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/IWriteableObject.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Model.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Shadow.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Stock.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Symbol.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Valve.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Variable.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/WriteContext.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/DelayExpression.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/EnumerationExpression.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/Expression.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/IntegralExpression.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/LookupExpression.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/NormalExpression.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/support/Enumeration.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/support/Function.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/support/Range.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/ModelParser.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/ModelParserConstants.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/ModelParserTokenManager.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/ModelicaParser.jj create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/ParseException.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/SimpleCharStream.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/Token.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/TokenMgrError.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/modelica/ModelicaWriter.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/refactoring/TGRefactoring.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/refactoring/mappingSpec.txt create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Auxiliary.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Book.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Cloud.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Configuration.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Dependency.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/DiagramContainerDummy.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Entity.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Enumeration.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/EnumerationIndex.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Flow.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Function.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/FunctionLibrary.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/IElement.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/IndependentVariable.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Input.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/LibraryDummy.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/LoadRepresentation.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Loop.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Model.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Module.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/ModuleType.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/ParameterOverride.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Redeclaration.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Shadow.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/SharedFunctionLibrary.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Sheet.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Stock.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/SysdynSchema.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Valve.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Variability.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Variable.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/annotations/BuiltinFunctions.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/annotations/BuiltinFunctionsAccessor.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/annotations/BuiltinFunctionsFactory.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/ConstantExpression.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/DelayExpression.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/Expression.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/IExpression.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/LookupExpression.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/NormalExpression.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/ParameterExpression.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/StockExpression.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/WithLookupExpression.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/FormatUtils.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/IndexUtils.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/RepresentationUtils.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/SheetFormatUtils.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/UnitUtils.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/visitors/ElementVisitorVoidAdapter.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/representation/visitors/IElementVisitorVoid.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/simulation/SimulationJob.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/simulation/SimulationScheduler.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/solver/ISolver.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/solver/ISolverMonitor.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/solver/InternalSolver.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/solver/InternalSolverResult.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/solver/ModelicaSolver.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/solver/SolverParameters.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/solver/SolverSettings.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/solver/SysdynSimulationJob.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/ParseException.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/SimpleCharStream.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/TableParser.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/TableParser.jj create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/TableParserConstants.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/TableParserTokenManager.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/Token.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/TokenMgrError.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/JJTUnitParserState.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/Node.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/ParseException.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/SimpleCharStream.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/SimpleNode.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/Token.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/TokenMgrError.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitCheckingException.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitCheckingNode.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitCheckingNodeFactory.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParser.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParser.jj create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParser.jjt create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParserConstants.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParserTokenManager.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParserTreeConstants.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/AddOp.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Arithmetic.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ArrayDefinition.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ComponentIdentity.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ComponentReference.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ComponentReferenceFull.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Condition.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Divide.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Expression.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Factor.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ForIndex.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/FunctionArguments.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/FunctionCall.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/IfThenElse.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/LogicalExpression.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/LogicalFactor.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/LogicalTerm.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Multiplication.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/NamedArguments.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ParenthesisExpression.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Power.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/RelOp.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Relation.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Term.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/UnitResult.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Value.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/utils/DocumentationUtils.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/utils/Function.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/utils/GetConfigurationRequest.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/utils/LoopUtils.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/utils/ModelUtils.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/utils/ModuleSummary.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/utils/ModuleSummaryRequest.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/utils/ProfileEntries.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/utils/SelectionUtils.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/utils/SheetUtils.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/utils/imports/ImportUtils.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/utils/imports/SysdynFunctionLibraryImportAdvisor.java create mode 100644 org.simantics.sysdyn/src/org/simantics/sysdyn/utils/imports/SysdynImportFormatHandler.java create mode 100644 org.simantics.sysdyn/testModels/MaintenanceModel_2012-12-03.tg create mode 100644 org.simantics.sysdyn/testModels/Model1412Health.tg create mode 100644 org.simantics.sysdyn/testModels/WorkModel_2012-12-03.tg create mode 100644 org.simantics.sysdyn/testModels/openprod_demo_2012-12-03.tg create mode 100644 org.simantics.sysdyn/testModels/references.txt diff --git a/org.simantics.sysdyn/.classpath b/org.simantics.sysdyn/.classpath new file mode 100644 index 00000000..8a8f1668 --- /dev/null +++ b/org.simantics.sysdyn/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/org.simantics.sysdyn/.hgignore b/org.simantics.sysdyn/.hgignore new file mode 100644 index 00000000..73df90f6 --- /dev/null +++ b/org.simantics.sysdyn/.hgignore @@ -0,0 +1,5 @@ +syntax: regexp +^bin/ + +syntax: glob +*.svn/* \ No newline at end of file diff --git a/org.simantics.sysdyn/.project b/org.simantics.sysdyn/.project new file mode 100644 index 00000000..05d44396 --- /dev/null +++ b/org.simantics.sysdyn/.project @@ -0,0 +1,28 @@ + + + org.simantics.sysdyn + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/org.simantics.sysdyn/.settings/org.eclipse.jdt.core.prefs b/org.simantics.sysdyn/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000..785aae6f --- /dev/null +++ b/org.simantics.sysdyn/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Mon Nov 16 15:37:44 EET 2009 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/org.simantics.sysdyn/META-INF/MANIFEST.MF b/org.simantics.sysdyn/META-INF/MANIFEST.MF new file mode 100644 index 00000000..66b45852 --- /dev/null +++ b/org.simantics.sysdyn/META-INF/MANIFEST.MF @@ -0,0 +1,61 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Simantics System Dynamics +Bundle-SymbolicName: org.simantics.sysdyn;singleton:=true +Bundle-Version: 1.8.0.qualifier +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Require-Bundle: org.simantics.objmap;bundle-version="0.1.0", + org.simantics.db;bundle-version="0.6.2", + org.simantics.modelica;bundle-version="1.0.0", + org.simantics.db.common;bundle-version="0.8.0", + org.simantics.simulation;bundle-version="1.0.0", + org.eclipse.ui.console;bundle-version="3.4.0", + org.eclipse.core.runtime;bundle-version="3.5.0", + org.eclipse.jface;bundle-version="3.5.2", + org.simantics.project;bundle-version="1.0.0", + org.simantics.layer0.utils;bundle-version="0.8.0", + org.simantics.layer0;bundle-version="1.0.0", + org.simantics.structural.ontology;bundle-version="1.0.0", + org.simantics.sysdyn.ontology;bundle-version="1.0.0", + org.simantics.modeling;bundle-version="1.1.1", + org.simantics.diagram;bundle-version="1.1.1", + org.simantics.diagram.ontology;bundle-version="1.1.1", + org.simantics.scl.runtime;bundle-version="0.1.3", + org.simantics.db.layer0;bundle-version="1.1.0", + org.simantics.spreadsheet.common;bundle-version="1.1.0", + org.simantics.spreadsheet;bundle-version="1.1.0", + org.eclipse.jface.text;bundle-version="3.6.1", + org.simantics.spreadsheet.ontology;bundle-version="1.2.0", + org.simantics.fmu;bundle-version="1.0.0", + org.simantics.issues;bundle-version="1.1.0", + org.simantics.issues.common;bundle-version="1.1.0", + org.simantics.jfreechart;bundle-version="1.0.0", + org.jfree.jchart;bundle-version="1.0.13", + org.jfree.jcommon;bundle-version="1.0.16", + org.simantics.spreadsheet.graph;bundle-version="1.1.0", + fi.semantum.sysdyn.solver;bundle-version="0.1.0" +Export-Package: org.simantics.sysdyn, + org.simantics.sysdyn.adapter, + org.simantics.sysdyn.elementaryCycles, + org.simantics.sysdyn.expressionParser, + org.simantics.sysdyn.manager, + org.simantics.sysdyn.modelExport, + org.simantics.sysdyn.modelImport, + org.simantics.sysdyn.modelImport.model, + org.simantics.sysdyn.modelParser, + org.simantics.sysdyn.modelica, + org.simantics.sysdyn.representation, + org.simantics.sysdyn.representation.expressions, + org.simantics.sysdyn.representation.utils, + org.simantics.sysdyn.representation.visitors, + org.simantics.sysdyn.simulation, + org.simantics.sysdyn.solver, + org.simantics.sysdyn.tableParser, + org.simantics.sysdyn.utils, + org.simantics.sysdyn.utils.imports +Bundle-Activator: org.simantics.sysdyn.Activator +Bundle-ActivationPolicy: lazy +Import-Package: org.eclipse.ui, + org.simantics.sysdyn.utils, + org.simantics.ui +Bundle-Vendor: VTT Technical Reserarch Centre of Finland diff --git a/org.simantics.sysdyn/ModelicaParser.html b/org.simantics.sysdyn/ModelicaParser.html new file mode 100644 index 00000000..157b944c --- /dev/null +++ b/org.simantics.sysdyn/ModelicaParser.html @@ -0,0 +1,727 @@ + + + +BNF for ModelicaParser.jj + + +

BNF for ModelicaParser.jj

+

TOKENS

+ + + + + + + + + + + + + +
+
+/*** Lexer *********************************************************/
+
+
+<DEFAULT> SKIP : {
+<WHITESPACE: " " | "\n" | "\r" | "\t">
+| <COMMENT1: "/*" (~["*"] | "*" ~["/"])* "*/">
+| <COMMENT2: "//" (~["\n"])*>
+}
+
+   
+
+
+<DEFAULT> TOKEN : {
+"algorithm"
+| "discrete"
+| "false"
+| "model"
+| "redeclare"
+| "and"
+| "each"
+| "final"
+| "not"
+| "replaceable"
+| "annotation"
+| "else"
+| "flow"
+| "operator"
+| "return"
+| "assert"
+| "elseif"
+| "for"
+| "or"
+| "stream"
+| "block"
+| "elsewhen"
+| "function"
+| "outer"
+| "then"
+| "break"
+| "encapsulated"
+| "if"
+| "output"
+| "true"
+| "class"
+| "end"
+| "import"
+| "package"
+| "type"
+| "connect"
+| "enumeration"
+| "in"
+| "parameter"
+| "when"
+| "connector"
+| "equation"
+| "initial"
+| "partial"
+| "while"
+| "constant"
+| "expandable"
+| "inner"
+| "protected"
+| "within"
+| "constrainedby"
+| "extends"
+| "input"
+| "public"
+| "der"
+| "external"
+| "loop"
+| "record"
+| "("
+| ")"
+| "{"
+| "}"
+| "["
+| "]"
+| "."
+| ":"
+| ";"
+| ","
+| "<"
+| "<="
+| ">"
+| ">="
+| "=="
+| "<>"
+| "+"
+| "-"
+| ".+"
+| ".-"
+| "*"
+| "/"
+| ".*"
+| "./"
+| "^"
+| ".^"
+| "="
+| ":="
+| <IDENT: ["a"-"z","A"-"Z","_"] (["a"-"z","A"-"Z","_","0"-"9"])*>
+| <STRING: "\"" (~["\"","\\","\n"] | "\\" ~["\n"])* "\""> : {
+| <UNSIGNED_INTEGER: (["0"-"9"])+>
+| <UNSIGNED_NUMBER: <UNSIGNED_INTEGER> "." (<UNSIGNED_INTEGER>)? (["e","E"] <UNSIGNED_INTEGER>)? | "." <UNSIGNED_INTEGER> (["e","E"] <UNSIGNED_INTEGER>)? | <UNSIGNED_INTEGER> ["e","E"] <UNSIGNED_INTEGER>>
+}
+
+   
+
+

NON-TERMINALS

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+/*** Parser ********************************************************/
+
+// https://javacc.dev.java.net/doc/javaccgrm.html
+// add_op -> add_op()
+// [ add_op ] -> ( add_op() )?
+// { add_op term } -> ( add_op() term() )*
+
+
parse::=stored_definition <EOF>
+
+/*** Stored Definition - Within ************************************/
+
stored_definition::=( "within" ( name )? ";" )? ( ( "final" )? class_definition ";" )*
+
+/*** Class Definition **********************************************/
+
class_definition::=( "encapsulated" )? ( "partial" )? ( "class" | "model" | "record" | "block" | ( "expandable" )? "connector" | "type" | "package" | "function" | "operator" | "operator function" | "operator record" ) class_specifier
class_specifier::=<IDENT> string_comment composition "end" <IDENT>
|<IDENT> "=" base_prefix name ( array_subscripts )? ( class_modification )? comment
|<IDENT> "=" "enumeration" "(" ( ( enum_list )? | ":" ) ")" comment
|<IDENT> "=" "der" "(" name "," <IDENT> ( "," <IDENT> )* ")" comment
|"extends" <IDENT> ( class_modification )? string_comment composition "end" <IDENT>
base_prefix::=type_prefix
enum_list::=enumeration_literal ( "," enumeration_literal )*
enumeration_literal::=<IDENT> comment
parse_composition::=composition <EOF>
composition::=element_list ( "public" element_list | "protected" element_list | equation_section | algorithm_section )* ( "external" ( language_specification )? ( external_function_call )? ( annotation )? ";" )? ( annotation ";" )?
language_specification::=<STRING>
external_function_call::=( component_reference "=" )? <IDENT> "(" ( expression_list )? ")"
element_list::=( element ";" )*
element::=import_clause
|extends_clause
|( "redeclare" )? ( "final" )? ( "inner" )? ( "outer" )? ( ( class_definition | component_clause ) | "replaceable" ( class_definition | component_clause ) ( constraining_clause comment )? )
import_clause::="import" ( <IDENT> "=" name | name ( "." "*" )? ) comment
+
+/*** Extends *******************************************************/
+
extends_clause::="extends" name ( class_modification )? ( annotation )?
constraining_clause::="constrainedby" name ( class_modification )?
+
+/*** Component Clause **********************************************/
+
component_clause::=( type_prefix ) ( type_specifier ) ( array_subscripts )? ( component_list )
type_prefix::=( "flow" | "stream" )? ( "discrete" | "parameter" | "constant" )? ( "output" | "input" )?
type_specifier::=name
component_list::=component_declaration ( "," component_declaration )*
component_declaration::=declaration ( conditional_attribute )? comment
conditional_attribute::="if" expression
declaration::=<IDENT> ( array_subscripts )? ( modification )?
+
+/*** Modification **********************************************/
+
modification::=( class_modification ( "=" expression )? | "=" expression | ":=" expression )
class_modification::="(" ( argument_list )? ")"
argument_list::=argument ( "," argument )*
argument::=element_modification_or_replaceable
|element_redeclaration
element_modification_or_replaceable::=( "each" )? ( "final" )? ( element_modification | element_replaceable )
element_modification::=name ( modification )? string_comment
element_redeclaration::="redeclare" ( "each" )? ( "final" )? ( ( class_definition | component_clause1 ) | element_replaceable )
element_replaceable::="replaceable" ( class_definition | component_clause1 ) ( constraining_clause )?
component_clause1::=type_prefix type_specifier component_declaration1
component_declaration1::=declaration comment
+
+/*** Equations *************************************************/
+
equation_section::=( "initial" )? "equation" ( equation ";" )*
algorithm_section::=( "initial" )? "algorithm" ( statement ";" )*
equation::=( simple_expression "=" expression | if_equation | for_equation | connect_clause | when_equation | <IDENT> function_call_args ) comment
statement::=( component_reference ( ":=" expression | function_call_args ) | "(" output_expression_list ")" ":=" component_reference function_call_args | "break" | "return" | if_statement | for_statement | while_statement | when_statement ) comment
if_equation::="if" expression "then" ( equation ";" )* ( "elseif" expression "then" ( equation ";" )* )* ( "else" ( equation ";" )* )? "end" "if"
if_statement::="if" expression "then" ( statement ";" )* ( "elseif" expression "then" ( statement ";" )* )* ( "else" ( statement ";" )* )? "end" "if"
for_equation::="for" for_indices "loop" ( equation ";" )* "end" "for"
for_statement::="for" for_indices "loop" ( statement ";" )* "end" "for"
for_indices::=for_index ( "," for_index )*
for_index::=<IDENT> ( "in" expression )?
while_statement::="while" expression "loop" ( statement ";" )* "end" "while"
when_equation::="when" expression "then" ( equation ";" )* ( "elsewhen" expression "then" ( equation ";" )* )* "end" "when"
when_statement::="when" expression "then" ( statement ";" )* ( "elsewhen" expression "then" ( statement ";" )* )* "end" "when"
connect_clause::="connect" "(" component_reference "," component_reference ")"
+
+/*** Expressions ***************************************************/
+
expr::=simple_expression <EOF>
|"if" expression "then" expression ( "elseif" expression "then" expression )* "else" expression <EOF>
expression::=simple_expression
|"if" expression "then" expression ( "elseif" expression "then" expression )* "else" expression
simple_expression::=logical_expression ( ":" logical_expression ( ":" logical_expression )? )?
logical_expression::=logical_term ( "or" logical_term )*
logical_term::=logical_factor ( "and" logical_factor )*
logical_factor::=( "not" )? relation
relation::=arithmetic_expression ( rel_op arithmetic_expression )?
rel_op::="<"
|"<="
|">"
|">="
|"=="
|"<>"
arithmetic_expression::=( add_op )? term ( add_op term )*
add_op::="+"
|"-"
|".+"
|".-"
term::=factor ( mul_op factor )*
mul_op::="*"
|"/"
|".*"
|"./"
factor::=primary ( "^" | ".^" primary )?
primary::=<UNSIGNED_NUMBER>
|<UNSIGNED_INTEGER>
|<STRING>
|"false"
|"true"
|( name | "der" | "initial" ) function_call_args
|component_reference
|"(" expression ")"
|"[" expression_list ( ";" expression_list )* "]"
|"{" function_arguments "}"
|"end"
name::=( "." )? <IDENT> ( "." <IDENT> )*
component_reference::=( "." )? <IDENT> ( array_subscripts )? ( "." <IDENT> ( array_subscripts )? )*
function_call_args::="(" ( function_arguments )? ")"
function_arguments::=expression ( "," function_arguments | "for" for_indices )?
|named_arguments
named_arguments::=named_argument ( "," named_arguments )?
named_argument::=<IDENT> "=" expression
output_expression_list::=( expression )? ( "," ( expression )? )*
expression_list::=expression ( "," expression )*
array_subscripts::="[" subscript ( "," subscript )* "]"
subscript::=":"
|expression
comment::=string_comment ( annotation )?
string_comment::=( <STRING> ( "+" <STRING> )* )?
annotation::="annotation" class_modification
+ + diff --git a/org.simantics.sysdyn/adapters.xml b/org.simantics.sysdyn/adapters.xml new file mode 100644 index 00000000..c01c1f80 --- /dev/null +++ b/org.simantics.sysdyn/adapters.xml @@ -0,0 +1,109 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/org.simantics.sysdyn/bpmn/BPMN20.xsd b/org.simantics.sysdyn/bpmn/BPMN20.xsd new file mode 100644 index 00000000..463ef6e6 --- /dev/null +++ b/org.simantics.sysdyn/bpmn/BPMN20.xsd @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/org.simantics.sysdyn/bpmn/BPMNDI.xsd b/org.simantics.sysdyn/bpmn/BPMNDI.xsd new file mode 100644 index 00000000..615740f4 --- /dev/null +++ b/org.simantics.sysdyn/bpmn/BPMNDI.xsd @@ -0,0 +1,100 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/org.simantics.sysdyn/bpmn/DC.xsd b/org.simantics.sysdyn/bpmn/DC.xsd new file mode 100644 index 00000000..80e9fa8b --- /dev/null +++ b/org.simantics.sysdyn/bpmn/DC.xsd @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/org.simantics.sysdyn/bpmn/DI.xsd b/org.simantics.sysdyn/bpmn/DI.xsd new file mode 100644 index 00000000..97f1bcff --- /dev/null +++ b/org.simantics.sysdyn/bpmn/DI.xsd @@ -0,0 +1,100 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/org.simantics.sysdyn/bpmn/Semantic.xsd b/org.simantics.sysdyn/bpmn/Semantic.xsd new file mode 100644 index 00000000..1c611dad --- /dev/null +++ b/org.simantics.sysdyn/bpmn/Semantic.xsd @@ -0,0 +1,1562 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/org.simantics.sysdyn/bpmn/generate.bat b/org.simantics.sysdyn/bpmn/generate.bat new file mode 100644 index 00000000..ed17066a --- /dev/null +++ b/org.simantics.sysdyn/bpmn/generate.bat @@ -0,0 +1,2 @@ +"C:\Program Files\Java\jdk1.7.0_51\bin\xjc" -target 2.1 -d ../src -p org.simantics.sysdyn.modelImport.bpmn BPMN20.xsd +pause \ No newline at end of file diff --git a/org.simantics.sysdyn/bpmn/helloworld.xml b/org.simantics.sysdyn/bpmn/helloworld.xml new file mode 100644 index 00000000..1e1d5f2d --- /dev/null +++ b/org.simantics.sysdyn/bpmn/helloworld.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/org.simantics.sysdyn/build.properties b/org.simantics.sysdyn/build.properties new file mode 100644 index 00000000..26e468c9 --- /dev/null +++ b/org.simantics.sysdyn/build.properties @@ -0,0 +1,18 @@ +############################################################################### +# Copyright (c) 2010 Association for Decentralized Information Management in +# Industry THTH ry. +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v1.0 +# which accompanies this distribution, and is available at +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# VTT Technical Research Centre of Finland - initial API and implementation +############################################################################### +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + adapters.xml,\ + plugin.xml,\ + scl/ diff --git a/org.simantics.sysdyn/plugin.xml b/org.simantics.sysdyn/plugin.xml new file mode 100644 index 00000000..965913ce --- /dev/null +++ b/org.simantics.sysdyn/plugin.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/org.simantics.sysdyn/scl/Simantics/Sysdyn.scl b/org.simantics.sysdyn/scl/Simantics/Sysdyn.scl new file mode 100644 index 00000000..878dffb5 --- /dev/null +++ b/org.simantics.sysdyn/scl/Simantics/Sysdyn.scl @@ -0,0 +1,110 @@ +include "UI/Progress" +include "Simantics/DB" +include "Simantics/Variables" + +importJava "org.simantics.sysdyn.utils.DocumentationUtils" where + + @JavaName getModules + getModules :: Variable -> [Resource] + + @JavaName getExperimentVariables + getExperimentVariables :: Variable -> [Variable] + + @JavaName getRoleVariables + getRoleVariables :: Variable -> [Variable] + + @JavaName getDocumentVariables + getDocumentVariables :: Variable -> [Variable] + + @JavaName getIndexDocuments + getIndexDocuments :: Variable -> [Variable] + + @JavaName getResultVariables + getResultVariables :: Variable -> [Variable] + + @JavaName getConfiguration + getConfiguration :: Resource -> Resource + + @JavaName getConfigurationVariables + getConfigurationVariables :: Resource -> [Resource] + + @JavaName getName + getName :: Resource -> String + + @JavaName getType + getType :: Resource -> String + + @JavaName getUnit + getUnit :: Resource -> String + + @JavaName getVariability + getVariability :: Resource -> String + + @JavaName getDescription + getDescription :: Resource -> String + + @JavaName getDocumentationDefinition + getDocumentationDefinition :: Resource -> String + + + + @JavaName numberOfVariables + numberOfVariables :: Resource -> Boolean -> Integer + + @JavaName totalNumberOfVariables + totalNumberOfVariables :: Resource -> Boolean -> Integer + + @JavaName numberOfStocks + numberOfStocks :: Resource -> Boolean -> Integer + + @JavaName numberOfValves + numberOfValves :: Resource -> Boolean -> Integer + + @JavaName numberOfInputs + numberOfInputs :: Resource -> Boolean -> Integer + + @JavaName numberOfShadows + numberOfShadows :: Resource -> Boolean -> Integer + + @JavaName numberOfAuxiliaries + numberOfAuxiliaries :: Resource -> Boolean -> Integer + + @JavaName numberOfModules + numberOfModules :: Resource -> Boolean -> Integer + + @JavaName numberOfSheets + numberOfSheets :: Resource -> Boolean -> Integer + + @JavaName numberOfModuleTypes + numberOfModuleTypes :: Variable -> Integer + + @JavaName base64Encode + base64Encode :: Variable -> String -> String + + @JavaName formatDate + formatDate :: Long -> String + + @JavaName importModel + importModel :: String -> Resource + + @JavaName isParameter + isParameter :: Variable -> Boolean + + lastValue :: Resource -> String -> String -> Double + lastValue2 :: Variable -> String -> Variable + currentValue :: Variable -> String -> Variable + lastValueIndexed :: Variable -> String -> Variable + equation :: Variable -> String -> Variable + +importJava "org.simantics.sysdyn.manager.SysdynExperiments" where + + activateExperiment :: Resource -> String + run :: String -> () + saveIC :: Variable -> String -> Maybe Resource + assignIC :: Variable -> String -> () + deassignIC :: Variable -> () + applyIC :: Variable -> String -> () + deleteIC :: Variable -> String -> () + + setPublishResults :: Variable -> Boolean -> () + \ No newline at end of file diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/Activator.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/Activator.java new file mode 100644 index 00000000..640c85fe --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/Activator.java @@ -0,0 +1,64 @@ +/******************************************************************************* + * Copyright (c) 2010 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn; + +import java.io.File; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; + +public class Activator implements BundleActivator { + + private static BundleContext bundleContext; + + // The plug-in ID + public static final String PLUGIN_ID = "org.simantics.sysdyn"; + + // The shared instance + private static Activator plugin; + + @Override + public void start(BundleContext context) throws Exception { + bundleContext = context; + File modelsDir = Activator.getBundleContext().getDataFile("models"); + if (!modelsDir.exists()) { + modelsDir.mkdir(); + } + plugin = this; + } + + @Override + public void stop(BundleContext context) throws Exception { + File modelsDir = Activator.getBundleContext().getDataFile("models"); + if (modelsDir.exists()) { + recursiveDelete(modelsDir); + } + plugin = null; + + } + + public static Activator getDefault() { + return plugin; + } + + public static BundleContext getBundleContext() { + return bundleContext; + } + + private static boolean recursiveDelete(File fileOrDir) { + if(fileOrDir.isDirectory()) + for(File innerFile: fileOrDir.listFiles()) + if(!recursiveDelete(innerFile)) + return false; + return fileOrDir.delete(); + } +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/Functions.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/Functions.java new file mode 100644 index 00000000..04c2b623 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/Functions.java @@ -0,0 +1,269 @@ +package org.simantics.sysdyn; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import org.simantics.databoard.Bindings; +import org.simantics.databoard.binding.Binding; +import org.simantics.databoard.binding.mutable.Variant; +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.WriteGraph; +import org.simantics.db.common.request.ResourceRead; +import org.simantics.db.common.uri.UnescapedChildMapOfResource; +import org.simantics.db.common.utils.ListUtils; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.function.All; +import org.simantics.db.layer0.variable.StandardGraphChildVariable; +import org.simantics.db.layer0.variable.ValueAccessor; +import org.simantics.db.layer0.variable.Variable; +import org.simantics.db.layer0.variable.VariableMap; +import org.simantics.db.layer0.variable.VariableMapImpl; +import org.simantics.layer0.Layer0; +import org.simantics.operation.Layer0X; +import org.simantics.scl.reflection.annotations.SCLValue; +import org.simantics.structural.stubs.StructuralResource2; +import org.simantics.sysdyn.adapter.ActiveDatasetsIndexVariable; +import org.simantics.sysdyn.adapter.NamesIndexVariable; +import org.simantics.sysdyn.adapter.TimeIndexVariable; +import org.simantics.sysdyn.adapter.TimesIndexVariable; +import org.simantics.sysdyn.adapter.ValueIndexVariable; +import org.simantics.sysdyn.adapter.ValueIndexVariableI; +import org.simantics.sysdyn.adapter.ValuesIndexVariable; + +public class Functions { + + public static String VALUE = "value"; + public static String VALUES = "values"; + public static String TIME = "time"; + public static String TIMES = "times"; + public static String NAMES = "names"; + public static String ACTIVE_DATASETS = "activeDatasets"; + + @SCLValue(type = "ValueAccessor") + public static ValueAccessor valuePropertyValue = new ValueAccessor() { + + @Override + public Object getValue(ReadGraph graph, Variable context) + throws DatabaseException { + // TODO Auto-generated method stub + return null; + } + + @Override + public Object getValue(ReadGraph graph, Variable context, + Binding binding) throws DatabaseException { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setValue(WriteGraph graph, Variable context, Object value) + throws DatabaseException { + // TODO Auto-generated method stub + + } + + @Override + public void setValue(WriteGraph graph, Variable context, Object value, + Binding binding) throws DatabaseException { + // TODO Auto-generated method stub + + } + + }; + + @SCLValue(type = "ValueAccessor") + public static ValueAccessor equationPropertyValue = new ValueAccessor() { + + @Override + public Object getValue(ReadGraph graph, Variable context) throws DatabaseException { + return getValue(graph, context, Bindings.STRING); + } + + @Override + public Object getValue(ReadGraph graph, Variable context, Binding binding) throws DatabaseException { + + Variable v = context.getParent(graph); + + Resource represents = v.getPossibleRepresents(graph); + if(represents != null) { + SysdynResource SYSDYN = SysdynResource.getInstance(graph); + Collection res = ListUtils.toList(graph, graph.getSingleObject(represents, SYSDYN.Variable_expressionList)); + if(res.size() == 1) { + Resource exp = res.iterator().next(); + String text = graph.getRelatedValue(exp, SYSDYN.Expression_equation, Bindings.STRING); + return text; + } + } + + return null; + + } + + @Override + public void setValue(WriteGraph graph, Variable context, Object value) throws DatabaseException { + + if(value instanceof Variant) value = ((Variant)value).getValue(); + + if(!(value instanceof String)) throw new DatabaseException("Unexpected value " + value + ", expected String"); + + setValue(graph, context, value, Bindings.STRING); + + } + + @Override + public void setValue(WriteGraph graph, Variable context, Object value, Binding binding) throws DatabaseException { + + if(value instanceof Variant) value = ((Variant)value).getValue(); + + if(!(value instanceof String)) throw new DatabaseException("Unexpected value " + value + ", expected String"); + + Variable v = context.getParent(graph); + + Resource represents = v.getPossibleRepresents(graph); + if(represents != null) { + SysdynResource SYSDYN = SysdynResource.getInstance(graph); + Collection res = ListUtils.toList(graph, graph.getSingleObject(represents, SYSDYN.Variable_expressionList)); + if(res.size() == 1) { + Resource exp = res.iterator().next(); + graph.claimLiteral(exp, SYSDYN.Expression_equation, value, Bindings.STRING); + } + } + + } + + }; + + + @SCLValue(type = "VariableMap") + public static VariableMap runProperties = new VariableMapImpl() { + + @Override + public Variable getVariable(ReadGraph graph, Variable context, String name) throws DatabaseException { + + String property = context.getName(graph); + if(TIME.equals(property)) + return new TimeIndexVariable(graph, context, name); + else + return null; + } + + @Override + public Map getVariables(ReadGraph graph, Variable context, Map map) throws DatabaseException { + return map; + } + }; + + @SCLValue(type = "VariableMap") + public static VariableMap valuePropertyProperties = new VariableMapImpl() { + + @Override + public Variable getVariable(ReadGraph graph, Variable context, String name) throws DatabaseException { + + String property = context.getName(graph); + if(VALUE.equals(property)) + if(name.startsWith("$")) { + Integer index = Integer.parseInt(name.substring(1)); + return new ValueIndexVariableI(graph, context, index); + } else { + return new ValueIndexVariable(graph, context, name); + } + else if(VALUES.equals(property)) + return new ValuesIndexVariable(graph, context, name); + else if(TIMES.equals(property)) + return new TimesIndexVariable(graph, context, name); + else if(TIME.equals(property)) + return new TimeIndexVariable(graph, context, name); + else if(NAMES.equals(property)) + return new NamesIndexVariable(graph, context, name); + else if(ACTIVE_DATASETS.equals(property)) + return new ActiveDatasetsIndexVariable(graph, context, name); + else + return null; + } + + @Override + public Map getVariables(ReadGraph graph, Variable context, Map map) throws DatabaseException { + return map; +// Collections.emptyList(); +// StandardGraphChildVariable variable = (StandardGraphChildVariable)context; +// collectPropertiesFromContext(graph, variable, variable.resource, map); + } + + }; + + + @SCLValue(type = "VariableMap") + public static VariableMap runChildren = new VariableMapImpl() { + + @Override + public Variable getVariable(ReadGraph graph, Variable context, String name) throws DatabaseException { + StandardGraphChildVariable variable = (StandardGraphChildVariable)context; + Map children = graph.syncRequest(new StructuralChildMapOfResource(getConfiguration(graph, variable))); + Resource child = children.get(name); + if(child == null) return All.getStandardChildDomainChildVariable(graph, context, name); + return graph.getPossibleContextualAdapter(child, variable, Variable.class, Variable.class); + } + + @Override + public Map getVariables(ReadGraph graph, Variable context, Map map) throws DatabaseException { + + StandardGraphChildVariable variable = (StandardGraphChildVariable)context; + + map = All.getStandardChildDomainChildVariables(graph, context, map); + + for(Map.Entry entry : graph.syncRequest(new StructuralChildMapOfResource(getConfiguration(graph, variable))).entrySet()) { + String name = entry.getKey(); + Resource child = entry.getValue(); + Variable var = graph.getPossibleContextualAdapter(child, variable, Variable.class, Variable.class); + if(var != null) { + if(map == null) map = new HashMap(); + map.put(name, var); + } else { + System.err.println("No adapter for " + child + " in " + variable.getURI(graph)); + } + } + + return map; + + } + + Resource getConfiguration(ReadGraph graph, Variable run) throws DatabaseException { + Layer0 L0 = Layer0.getInstance(graph); + Layer0X L0X = Layer0X.getInstance(graph); + Resource experiment = graph.getPossibleObject(run.getRepresents(graph), L0.PartOf); + Resource model = graph.getPossibleObject(experiment, L0.PartOf); + return graph.getPossibleObject(model, L0X.HasBaseRealization); + } + + }; + + + static class StructuralChildMapOfResource extends ResourceRead> { + + public StructuralChildMapOfResource(Resource resource) { + super(resource); + } + + @Override + public Map perform(ReadGraph graph) throws DatabaseException { + + StructuralResource2 STR = StructuralResource2.getInstance(graph); + Map directChildren = graph.syncRequest(new UnescapedChildMapOfResource(resource)); + Resource type = graph.getPossibleType(resource, STR.Component); + if(type != null) { + Resource definition = graph.getPossibleObject(type, STR.IsDefinedBy); + if(definition != null) { + return graph.syncRequest(new UnescapedChildMapOfResource(definition)); + } + } + + return directChildren; + + } + + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/TestParser.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/TestParser.java new file mode 100644 index 00000000..86b3245c --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/TestParser.java @@ -0,0 +1,233 @@ +/******************************************************************************* + * Copyright (c) 2013-2014 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Semantum Oy - initial API and implementation + * VTT Technical Research Centre of Finland + *******************************************************************************/ +package org.simantics.sysdyn; + +import java.io.StringReader; +import java.util.HashMap; + +import org.simantics.sysdyn.unitParser.ParseException; +import org.simantics.sysdyn.unitParser.UnitCheckingException; +import org.simantics.sysdyn.unitParser.UnitCheckingNode; +import org.simantics.sysdyn.unitParser.UnitParser; +import org.simantics.sysdyn.unitParser.nodes.UnitResult; +import org.simantics.sysdyn.utils.Function; + +public class TestParser { + + /** + * @param args + */ + public static void main(String[] args) { + + HashMap units = new HashMap(); + boolean allowEquivalents = true; + + doScenario(scenario1(units), units, allowEquivalents); + doScenario(scenario2(units), units, allowEquivalents); + doScenario(scenario3(units), units, allowEquivalents); + doScenario(scenario4(units), units, allowEquivalents); + doScenario(scenario5(units), units, allowEquivalents); + doScenario(scenario6(units), units, allowEquivalents); + doScenario(scenario7(units), units, allowEquivalents); + doScenario(scenario8(units), units, allowEquivalents); + doScenario(scenario9(units), units, allowEquivalents); + doScenario(scenario10(units), units, allowEquivalents); + doScenario(scenario11(units), units, allowEquivalents); + doScenario(scenario12(units), units, allowEquivalents); + doScenario(scenario13(units), units, allowEquivalents); + + } + + private static void doScenario(String expression, HashMap units, boolean allowEquivalents) { + System.out.println("-----------------------------------"); + System.out.println("Expression: " + expression); + System.out.println("Units: "); + for(String key : units.keySet()) { + System.out.println(" " + key + " -> " + units.get(key)); + } + StringReader sr = new StringReader(expression); + UnitParser parser = new UnitParser(sr); + try { + UnitCheckingNode node = (UnitCheckingNode) parser.expr(); + + try { + UnitResult u = node.getUnits(units, Function.getAllBuiltInFunctions(), allowEquivalents); + System.out.println("Result: " + u.getCleanFullUnit()); + } catch (UnitCheckingException e) { + e.printStackTrace(); + } + +// node.dump(""); + } catch (ParseException e) { + e.printStackTrace(); + } + } + + private static String scenario1(HashMap units) { + units.clear(); + + units.put("a", "m"); + units.put("b", "m"); + units.put("c", "m"); + + StringBuilder sb = new StringBuilder(); + sb.append("a*b*c"); + return sb.toString(); + } + + private static String scenario2(HashMap units) { + units.clear(); + + units.put("a", "m"); + units.put("b", "m"); + units.put("c", "m"); + + StringBuilder sb = new StringBuilder(); + sb.append("a+b+c"); + return sb.toString(); + } + + private static String scenario3(HashMap units) { + units.clear(); + + units.put("a", "m"); + units.put("b", "m"); + units.put("c", "m"); + + StringBuilder sb = new StringBuilder(); + sb.append("a/b+b/c"); + return sb.toString(); + } + + private static String scenario4(HashMap units) { + units.clear(); + + units.put("a", "m"); + units.put("b", "m"); + units.put("c", "m"); + + StringBuilder sb = new StringBuilder(); + sb.append("if a == b then a+b else b + c + a"); + return sb.toString(); + } + + private static String scenario5(HashMap units) { + units.clear(); + + units.put("a", "m"); + units.put("b", "s"); + units.put("c", "m"); + units.put("d", "s"); + + StringBuilder sb = new StringBuilder(); +// sb.append("a / b + (c*a)/(b*a)"); + sb.append("c/(b*a)"); + + return sb.toString(); + } + + private static String scenario6(HashMap units) { + units.clear(); + + units.put("a", "m"); + units.put("b", "s"); + units.put("c", "m"); + units.put("d", "m/s"); + + StringBuilder sb = new StringBuilder(); + sb.append("if a > c then c*a/b else a*d"); + return sb.toString(); + } + + private static String scenario7(HashMap units) { + units.clear(); + + units.put("a", "m/s"); + units.put("b.e", "s"); + units.put("c", "m"); + units.put("d", "s"); + + StringBuilder sb = new StringBuilder(); + sb.append("a[1] + c[1] / b.e[1]"); + return sb.toString(); + } + + private static String scenario8(HashMap units) { + units.clear(); + + units.put("a", "m"); + units.put("b", "s"); + units.put("c", "s*m"); + + StringBuilder sb = new StringBuilder(); + sb.append("c + {a[i] * b[i] for i in 1:3}"); + return sb.toString(); + } + + private static String scenario9(HashMap units) { + units.clear(); + units.put("a", "m"); + units.put("b", "m"); + + StringBuilder sb = new StringBuilder(); + sb.append("1+a+1+b"); + return sb.toString(); + } + + private static String scenario10(HashMap units) { + units.clear(); + units.put("a", "m"); + + StringBuilder sb = new StringBuilder(); + sb.append("1*a*1*a"); + return sb.toString(); + } + + private static String scenario11(HashMap units) { + units.clear(); + units.put("a", "m"); + units.put("b", "m"); + + StringBuilder sb = new StringBuilder(); + sb.append("-a+b"); + return sb.toString(); + } + + private static String scenario12(HashMap units) { + units.clear(); + units.put("a", "m"); + units.put("b", "s"); + units.put("c", "m/s"); + + + StringBuilder sb = new StringBuilder(); + sb.append("1/a/b + 1/c"); + return sb.toString(); + } + + private static String scenario13(HashMap units) { + units.clear(); + + units.put("a", "m"); + units.put("b", "m"); + units.put("c", "m"); + units.put("d", "s"); + + StringBuilder sb = new StringBuilder(); + sb.append("(a/b+b/c)/d"); + return sb.toString(); + } + +} + + diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ActiveDatasetsIndexVariable.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ActiveDatasetsIndexVariable.java new file mode 100644 index 00000000..4b57b97d --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ActiveDatasetsIndexVariable.java @@ -0,0 +1,56 @@ +package org.simantics.sysdyn.adapter; + +import java.util.ArrayList; +import java.util.Collection; + +import org.simantics.db.ReadGraph; +import org.simantics.db.WriteGraph; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.variable.Variable; +import org.simantics.modelica.data.DataSet; +import org.simantics.sysdyn.manager.SysdynDataSet; +import org.simantics.sysdyn.manager.SysdynResult; + +public class ActiveDatasetsIndexVariable extends IndexVariable< ArrayList> { + + public ActiveDatasetsIndexVariable(ReadGraph graph, Variable parent, String indexes) + throws DatabaseException { + super(graph, parent, indexes); + } + + @Override + public ArrayList getValue() { + ArrayList datasets = new ArrayList(); + + if(experiment == null) + return datasets; + + Collection results = experiment.getActiveResults(); + ArrayList variableNamesWithIndexes = getVariableNamesWithIndexNumbers(); + ArrayList variableNames = getVariableNames(); + + for(int i = 0; i < variableNamesWithIndexes.size(); i++) { + for(SysdynResult result : results) { + SysdynDataSet ds = result.getDataSet(variableNamesWithIndexes.get(i)); + if(ds != null) { + // NOTE: this method was changed to no longer remove + // remove enumeration indices from variable names as it + // seems unnecessary and makes different instances of the + // same variable with different enumeration indices + // indistinguishable from each other in simulation results + ds.name = variableNames.get(i); + + datasets.add(ds); + } + } + } + return datasets; + } + + @Override + public void setIndexedValue(WriteGraph graph, Object value) + throws DatabaseException { + + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/CustomMigrationStep.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/CustomMigrationStep.java new file mode 100644 index 00000000..dce49fa4 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/CustomMigrationStep.java @@ -0,0 +1,58 @@ +package org.simantics.sysdyn.adapter; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.simantics.db.Resource; +import org.simantics.db.Session; +import org.simantics.db.WriteGraph; +import org.simantics.db.common.request.ObjectsWithType; +import org.simantics.db.common.request.WriteRequest; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.migration.MigrationState; +import org.simantics.db.layer0.migration.MigrationStateKeys; +import org.simantics.db.layer0.migration.MigrationStep; +import org.simantics.db.layer0.util.Layer0Utils; +import org.simantics.layer0.Layer0; +import org.simantics.layer0.utils.direct.GraphUtils; +import org.simantics.simulation.ontology.SimulationResource; +import org.simantics.spreadsheet.resource.SpreadsheetResource; + +public class CustomMigrationStep implements MigrationStep { + + @Override + public void applyTo(IProgressMonitor monitor, Session session, MigrationState state) throws DatabaseException { + + final Resource res = state.getProperty(MigrationStateKeys.CURRENT_RESOURCE); + + session.syncRequest(new WriteRequest() { + + @Override + public void perform(WriteGraph graph) throws DatabaseException { + + Layer0 l0 = Layer0.getInstance(graph); + SimulationResource SIMU = SimulationResource.getInstance(graph); + + for(Resource model : graph.syncRequest(new ObjectsWithType(res, l0.ConsistsOf, SIMU.Model))) { + + Resource sheetExperiment = Layer0Utils.getPossibleChild(graph, model, "SheetExperiment"); + if(sheetExperiment != null) return; + + SpreadsheetResource SHEET = SpreadsheetResource.getInstance(graph); + sheetExperiment = GraphUtils.create2(graph, SHEET.Experiment, + l0.HasName, "SheetExperiment", + l0.HasLabel, "Sheet Experiment", + l0.PartOf, model); + + Resource sheetRun = GraphUtils.create2(graph, SHEET.Run, + l0.HasName, "Default", + l0.PartOf, sheetExperiment); + + + } + + } + + }); + + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/IndexVariable.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/IndexVariable.java new file mode 100644 index 00000000..0b03a5b4 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/IndexVariable.java @@ -0,0 +1,272 @@ +package org.simantics.sysdyn.adapter; + +import java.util.ArrayList; +import java.util.HashMap; + +import org.simantics.Simantics; +import org.simantics.databoard.Bindings; +import org.simantics.databoard.binding.Binding; +import org.simantics.databoard.type.Datatype; +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.WriteGraph; +import org.simantics.db.common.request.ParametrizedPrimitiveRead; +import org.simantics.db.common.utils.NameUtils; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.variable.AbstractPropertyVariable; +import org.simantics.db.layer0.variable.Variable; +import org.simantics.db.layer0.variable.Variables; +import org.simantics.db.procedure.Listener; +import org.simantics.db.request.ExternalRead; +import org.simantics.modeling.ModelingResources; +import org.simantics.project.IProject; +import org.simantics.simulation.experiment.IExperiment; +import org.simantics.simulation.ontology.SimulationResource; +import org.simantics.simulation.project.IExperimentManager; +import org.simantics.sysdyn.manager.SysdynExperiment; +import org.simantics.sysdyn.manager.SysdynModel; +import org.simantics.sysdyn.manager.SysdynModelManager; +import org.simantics.sysdyn.manager.VariableSubscriptionManager; +import org.simantics.utils.datastructures.Pair; + +public abstract class IndexVariable extends AbstractPropertyVariable { + + protected Variable parent; + protected SysdynModel model; + protected SysdynExperiment experiment; + protected String rvi; + protected HashMap rvis; + protected String indexes; + protected VariableSubscriptionManager subscriptionManager; + + public IndexVariable(ReadGraph graph, Variable parent, String indexes) throws DatabaseException { + this.parent = parent; + this.indexes = indexes; + } + + + protected VariableSubscriptionManager getSubscriptionManager() { + return this.experiment; + } + + public String getIndexes() { + return this.indexes; + } + + /** + * Register a property subscription + * + * @param request PropertyRequest + * @param procedure + * @return + */ + protected VariableValueSubscription registerSubscription(ExternalRead request, Listener procedure) { + // Other properties are requested from model (they listen to new simulation results) + VariableValueSubscription subscription = new VariableValueSubscription(request, this, procedure); + if(subscriptionManager != null) { + subscriptionManager.addVariableValueSubscription(subscription); + } + subscription.update(); + return subscription; + } + + /** + * Unregisters a subscription + * @param subscription + */ + protected void unregisterSubscription(VariableValueSubscription subscription) { + subscription.setListener(null); + if(subscriptionManager != null) + subscriptionManager.removeVariableValueSubscription(subscription); + } + + + + /** + * Class for supporting requests with different property parameters. Equals-method has been modified + * from ParametrizedPrivimiteRead to check also the property value. + * + * @author Teemu Lempinen + * + */ + class PropertyRequest extends ParametrizedPrimitiveRead { + + + public PropertyRequest(Variable indexVariable) { + super(indexVariable); + } + + VariableValueSubscription subscription; + + @Override + public void register(ReadGraph graph, Listener procedure) { + subscription = registerSubscription(this, procedure); + } + @Override + public void unregistered() { + if(subscription != null) { + unregisterSubscription(subscription); + subscription = null; + } + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(Object object) { + if(object instanceof IndexVariable.PropertyRequest && super.equals(object)) { + return this.parameter.equals(((PropertyRequest)object).parameter); + } else { + return super.equals(object); + } + } + + } + + @Override + public Resource getPropertyResource(ReadGraph graph) throws DatabaseException { + return null; + } + + @Override + public Resource getContainerResource(ReadGraph graph) throws DatabaseException { + return null; + } + + @Override + public Datatype getDatatype(ReadGraph graph) throws DatabaseException { + return null; + } + + @Override + public Variable getPredicate(ReadGraph graph) throws DatabaseException { + return null; + } + + @SuppressWarnings("unchecked") + @Override + public U getValue(ReadGraph graph) throws DatabaseException { + return (U) getValue(graph, Bindings.DOUBLE); + } + + @SuppressWarnings("unchecked") + @Override + public U getValue(ReadGraph graph, Binding binding) throws DatabaseException { + ensureInformationAvailable(graph); + // Do something before request, e.g. calculate some variables used in the request + beforeRequest(graph); + + return (U) graph.syncRequest(new PropertyRequest(this)); + + } + + protected void beforeRequest(ReadGraph graph) throws DatabaseException { + + } + + protected void ensureInformationAvailable(ReadGraph graph) throws DatabaseException { + SimulationResource SIMU = SimulationResource.getInstance(graph); + ModelingResources MOD = ModelingResources.getInstance(graph); + + if(model == null) { + Resource modelResource = Variables.getModel(graph, parent); + Resource configuration = graph.getPossibleObject(modelResource, SIMU.HasConfiguration); + model = SysdynModelManager.getInstance(graph.getSession()).getModel(graph, configuration); + } + + Variable var = parent.getParent(graph); + Resource represents = var.getRepresents(graph); + + Resource activeRun = null; + if(represents != null) { + do { + if(graph.isInstanceOf(represents, SIMU.Run)) { + activeRun = represents; + break; + } + var = var.getParent(graph); + represents = var.getRepresents(graph); + } while(represents != null && !graph.isInstanceOf(represents, MOD.StructuralModel)); + } + + IProject project = Simantics.peekProject(); + if(activeRun != null && project != null) { + IExperimentManager expMan = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER); + IExperiment e = expMan.getExperiment(NameUtils.getSafeName(graph, activeRun)); + if(e instanceof SysdynExperiment) + this.experiment = (SysdynExperiment)e; + } + + this.subscriptionManager = getSubscriptionManager(); + rvi = Variables.getPossibleRVI(graph, this); + if(rvi != null) + rvis = graph.syncRequest(new VariableRVIUtils.GetActiveRVIs(parent.getParent(graph))); //VariableRVIUtils.getActiveRVIs(graph, parent.getParent(graph)); + } + + private Pair,ArrayList> getVariableNameArrays() { + Pair,ArrayList> result = new Pair,ArrayList>(new ArrayList(), new ArrayList()); + if(rvi == null || rvis == null) + return result; + + if(rvi.indexOf('#') > 0) + rvi = rvi.substring(0, rvi.indexOf('#')); + + String test = rvi; + if(indexes != null && !indexes.isEmpty()) { + String regexIndexes = indexes.trim().replaceAll(":", "[a-zA-Z0-9_]*"); // Why was there was ".replace('.', ',')" ? - Removed by Teemu 2.9.2012 + test = rvi + "\\[" + regexIndexes + "\\]"; + } else { + test = rvi + "(\\[.*\\])?"; + } + for(String k : rvis.keySet()) { + String value = rvis.get(k); + if(k.matches(test) || value.matches(test)) { + result.first.add(k.substring(1).replace("/", ".").replace("%20", "_")); + result.second.add(value.substring(1).replace("/", ".").replace("%20", " ")); + } + } + + return result; + + } + + protected ArrayList getVariableNames() { + return getVariableNameArrays().second; + } + + protected ArrayList getVariableNamesWithIndexNumbers() { + return getVariableNameArrays().first; + } + + abstract public T getValue(); + + @Override + public void setValue(WriteGraph graph, Object value, Binding binding) throws DatabaseException { + setValue(graph, value); + } + + @Override + public void setValue(WriteGraph graph, Object value) throws DatabaseException { + ensureInformationAvailable(graph); + setIndexedValue(graph, value); + } + + abstract protected void setIndexedValue(WriteGraph graph, Object value) throws DatabaseException; + + + + @Override + public String getName(ReadGraph graph) throws DatabaseException { + return indexes; + } + + @Override + public Object getSerialized(ReadGraph graph) throws DatabaseException { + return indexes; + } + + @Override + public Variable getParent(ReadGraph graph) throws DatabaseException { + return parent; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/NamesIndexVariable.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/NamesIndexVariable.java new file mode 100644 index 00000000..7e32bbad --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/NamesIndexVariable.java @@ -0,0 +1,29 @@ +package org.simantics.sysdyn.adapter; + +import java.util.ArrayList; + +import org.simantics.db.ReadGraph; +import org.simantics.db.WriteGraph; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.variable.Variable; + +public class NamesIndexVariable extends IndexVariable { + + public NamesIndexVariable(ReadGraph graph, Variable parent, String indexes) + throws DatabaseException { + super(graph, parent, indexes); + } + + @Override + public String[] getValue() { + ArrayList names = getVariableNames(); + return names.toArray(new String[names.size()]); + } + + @Override + public void setIndexedValue(WriteGraph graph, Object value) + throws DatabaseException { + // TODO Auto-generated method stub + + } +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/SensitivityExperimentParameter.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/SensitivityExperimentParameter.java new file mode 100644 index 00000000..73098986 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/SensitivityExperimentParameter.java @@ -0,0 +1,105 @@ +/******************************************************************************* + * Copyright (c) 2013 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Semantum Oy - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.adapter; + +import org.simantics.databoard.Bindings; +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.request.PossibleModel; +import org.simantics.simulation.ontology.SimulationResource; +import org.simantics.sysdyn.SysdynResource; +import org.simantics.sysdyn.adapter.distribution.IDistribution; +import org.simantics.sysdyn.manager.SysdynModel; +import org.simantics.sysdyn.manager.SysdynModelManager; +import org.simantics.sysdyn.representation.Enumeration; +import org.simantics.sysdyn.representation.Variable; +import org.simantics.sysdyn.representation.utils.IndexUtils; +import org.simantics.sysdyn.representation.utils.RepresentationUtils; + +public class SensitivityExperimentParameter { + + private String variableName; + private String[] indexes; + private String fullName; + private IDistribution distribution; + + public SensitivityExperimentParameter(ReadGraph graph, Resource parameter) { + + try { + SysdynResource SR = SysdynResource.getInstance(graph); + Resource distributionResource = graph.getPossibleObject(parameter, SR.SensitivityAnalysisExperiment_Parameter_propabilityDistribution); + distribution = graph.adapt(distributionResource, IDistribution.class); + variableName = graph.getPossibleRelatedValue(parameter, SR.SensitivityAnalysisExperiment_Parameter_variable, Bindings.STRING); + indexes = graph.getPossibleRelatedValue(parameter, SR.SensitivityAnalysisExperiment_Parameter_indexes, Bindings.STRING_ARRAY); + + Resource model = graph.syncRequest(new PossibleModel(parameter)); + SysdynModelManager smm = SysdynModelManager.getInstance(graph.getSession()); + SysdynModel sm = smm.getModel(graph, graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration)); + + Variable variable = RepresentationUtils.getVariable(sm.getConfiguration(), variableName); + + if (variable != null) { + if(indexes == null && (variable.getArrayIndexes() != null & variable.getArrayIndexes().size() > 0)) { + indexes = new String[variable.getArrayIndexes().size()]; + + for(int i = 0; i < variable.getArrayIndexes().size(); i++) { + Enumeration e = variable.getArrayIndexes().get(i); + indexes[i] = e.getEnumerationIndexes().get(0).getName(); + } + } + + if(indexes != null) { + StringBuilder sb = new StringBuilder(); + sb.append("["); + for(int i = 0; i < indexes.length; i++) { + if(i > 0) + sb.append(","); + + String index = indexes[i]; + sb.append(index); + } + sb.append("]"); + String result = IndexUtils.rangeToIndexes(variable, sb.toString()); + fullName = variableName + result; + } else { + fullName = variableName; + } + } + } catch (DatabaseException e) { + + } + } + + public String getVariableName() { + return variableName; + } + + public String[] getIndexes() { + return indexes; + } + + public String getFullName() { + return fullName; + } + + public IDistribution getDistribution() { + return distribution; + } + + public String getFullModelicaName() { + if (this.fullName == null) + return null; + return this.fullName.replace(' ', '_'); + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/TimeIndexVariable.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/TimeIndexVariable.java new file mode 100644 index 00000000..9a44eacf --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/TimeIndexVariable.java @@ -0,0 +1,32 @@ +package org.simantics.sysdyn.adapter; + +import org.simantics.db.ReadGraph; +import org.simantics.db.WriteGraph; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.variable.Variable; +import org.simantics.sysdyn.manager.SysdynGameExperimentBase; +import org.simantics.sysdyn.manager.SysdynPlaybackExperiment; + +public class TimeIndexVariable extends IndexVariable { + + public TimeIndexVariable(ReadGraph graph, Variable parent, String indexes) + throws DatabaseException { + super(graph, parent, indexes); + } + + @Override + public Double getValue() { + if(experiment != null && experiment instanceof SysdynPlaybackExperiment) + return ((SysdynPlaybackExperiment)experiment).getTime(); + if(experiment != null && experiment instanceof SysdynGameExperimentBase) + return ((SysdynGameExperimentBase)experiment).getSolver().getTime(); + return null; + } + + @Override + public void setIndexedValue(WriteGraph graph, Object value) + throws DatabaseException { + + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/TimesIndexVariable.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/TimesIndexVariable.java new file mode 100644 index 00000000..329e4cd2 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/TimesIndexVariable.java @@ -0,0 +1,52 @@ +package org.simantics.sysdyn.adapter; + +import java.util.ArrayList; +import java.util.Collection; + +import org.simantics.db.ReadGraph; +import org.simantics.db.WriteGraph; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.variable.Variable; +import org.simantics.sysdyn.manager.SysdynDataSet; +import org.simantics.sysdyn.manager.SysdynResult; + +public class TimesIndexVariable extends IndexVariable { + + public TimesIndexVariable(ReadGraph graph, Variable parent, String indexes) + throws DatabaseException { + super(graph, parent, indexes); + // TODO Auto-generated constructor stub + } + + @Override + public double[][] getValue() { + if(experiment == null) + return new double[0][0]; + + Collection results = experiment.getActiveResults(); + ArrayList variableNames = getVariableNamesWithIndexNumbers(); + + double[][] result = new double[variableNames.size()][]; + for(int i = 0; i < variableNames.size(); i++) { + for(SysdynResult r : results) { + SysdynDataSet ds = r.getDataSet(variableNames.get(i)); + if(ds != null && ds.times != null) { + result[i] = new double[ds.times.length]; + for(int j = 0; j < ds.times.length; j++) { + result[i][j] = ds.times[j]; + } + break; // Show the first result found. (i.e. do not show history datasets) + } + } + if(result[i] == null) + result[i] = new double[0]; + } + return result; + } + + @Override + public void setIndexedValue(WriteGraph graph, Object value) + throws DatabaseException { + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariable.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariable.java new file mode 100644 index 00000000..e2ab2e44 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariable.java @@ -0,0 +1,42 @@ +package org.simantics.sysdyn.adapter; + +import org.simantics.databoard.Datatypes; +import org.simantics.databoard.type.Datatype; +import org.simantics.db.ReadGraph; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.variable.Variable; + +public class ValueIndexVariable extends ValueIndexVariableBase { + + private final boolean scalar; + + public ValueIndexVariable(ReadGraph graph, Variable parent, String indexes) + throws DatabaseException { + super(graph, parent, indexes); + scalar = indexes.indexOf(":") == -1; + } + + @Override + public Object getValue() { + double[] value = getValueFull(); + if (scalar) { + if (value == UNRESOLVED) { + return Double.NaN; + } else { + return value[0]; + } + } else { + return value; + } + } + + @Override + public Datatype getDatatype(ReadGraph graph) throws DatabaseException { + if (scalar) { + return Datatypes.DOUBLE; + } else { + return Datatypes.DOUBLE_ARRAY; + } + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariableBase.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariableBase.java new file mode 100644 index 00000000..cbb948bc --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariableBase.java @@ -0,0 +1,140 @@ +package org.simantics.sysdyn.adapter; + +import java.util.ArrayList; +import java.util.Collection; + +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.WriteGraph; +import org.simantics.db.common.utils.Logger; +import org.simantics.db.common.utils.NameUtils; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.variable.Variable; +import org.simantics.simulation.experiment.ExperimentState; +import org.simantics.sysdyn.SysdynResource; +import org.simantics.sysdyn.manager.SysdynDataSet; +import org.simantics.sysdyn.manager.SysdynGameExperimentBase; +import org.simantics.sysdyn.manager.SysdynGameExperimentBase.Subscription; +import org.simantics.sysdyn.manager.SysdynResult; +import org.simantics.sysdyn.solver.ISolver; + +abstract public class ValueIndexVariableBase extends IndexVariable { + + public ValueIndexVariableBase(ReadGraph graph, Variable parent, String indexes) + throws DatabaseException { + super(graph, parent, indexes); + ensureInformationAvailable(graph); + if(experiment instanceof SysdynGameExperimentBase) { + s = ((SysdynGameExperimentBase) experiment).subscribe(getVariableNamesWithIndexNumbers()); + } + } + + public static double[] UNRESOLVED = new double[0]; + + public Subscription s; + + public double[] getValueFull() { + + if(experiment == null) + return UNRESOLVED; + + if(experiment instanceof SysdynGameExperimentBase) { + double[] arr = new double[s.indexes.length]; + s.getValues(arr); + return arr; + } + + + Collection results = experiment.getActiveResults(); + ArrayList variableNames = getVariableNamesWithIndexNumbers(); + + double[] result = new double[variableNames.size()]; + for(int i = 0; i < variableNames.size(); i++) { + for(SysdynResult r : results) { +// if(experiment instanceof SysdynGameExperimentBase) { +// Double d = ((SysdynGameExperimentBase)experiment).getCurrentValue(variableNames.get(i)); +// result[i] = d != null ? d : 0; +// } else { + SysdynDataSet ds = r.getDataSet(variableNames.get(i)); + if(ds != null && ds.values != null && ds.values.length > 0) { + result[i] = ds.values[ds.values.length-1]; + } else { + return UNRESOLVED; + } +// } + } + } + return result; + } + + @Override + public void setIndexedValue(WriteGraph graph, Object value) + throws DatabaseException { + Variable var = parent.getParent(graph); + Resource resource = var.getRepresents(graph); + + if(!(value instanceof Double || value instanceof double[]) || resource == null) + return; + + double[] values = null; + if (value instanceof Double) { + values = new double[1]; + values[0] = (Double)value; + } else if (value instanceof double[]) { + values = (double[]) value; + } + +// FMUControlJNI control = null; + if(experiment instanceof SysdynGameExperimentBase) { // Support only game experiments for now.. + + SysdynGameExperimentBase exp = (SysdynGameExperimentBase)experiment; + ExperimentState state = exp.getSysdynExperimentState(); + // Set value to control only if the simulation is running or stopped, not before initialization + if(!(ExperimentState.RUNNING.equals(state) || ExperimentState.STOPPED.equals(state))) + return; + +// control = ((SysdynGameExperimentBase)this.experiment).getFMUControl(); +// if(control == null) +// return; + + ISolver solver = exp.getSolver(); + + try { + + ArrayList variableNames = getVariableNamesWithIndexNumbers(); + for(int i = 0; i < variableNames.size() && i < values.length; i++) { + + if(values[i] == Double.NaN) + continue; + + String name = variableNames.get(i); + solver.setRealValue(name, values[i]); + + // Set value for all referred variables in modules + SysdynResource sr = SysdynResource.getInstance(graph); + for(Resource dependency : graph.getObjects(resource, sr.Variable_isTailOf)) { + Resource head = graph.getPossibleObject(dependency, sr.Variable_HasHead); + Resource ref = graph.getPossibleObject(dependency, sr.Dependency_refersTo); + if(ref != null && head != null) { + String module = ""; + if(name.indexOf(".") > 0) + module = name.substring(0, name.lastIndexOf(".") + 1); + String refName = module + NameUtils.getSafeName(graph, head) + "." + NameUtils.getSafeName(graph, ref); + solver.setRealValue(refName, values[i]); + } + } + + } + exp.refresh(); + exp.updateSubscriptions(); + + } catch (Exception e) { + + Logger.defaultLogError(e); + + } + + } + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariableI.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariableI.java new file mode 100644 index 00000000..baed93ed --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariableI.java @@ -0,0 +1,58 @@ +package org.simantics.sysdyn.adapter; + +import java.util.Arrays; + +import org.simantics.databoard.Datatypes; +import org.simantics.databoard.binding.Binding; +import org.simantics.databoard.type.Datatype; +import org.simantics.db.ReadGraph; +import org.simantics.db.WriteGraph; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.variable.Variable; + +public class ValueIndexVariableI extends ValueIndexVariableBase { + + final int index; + + public ValueIndexVariableI(ReadGraph graph, Variable parent, int index) throws DatabaseException { + super(graph, parent, ""); + this.index = index; + } + + @Override + public Double getValue() { + double[] array = getValueFull(); + if(array == null || index < 0 || array.length < index+1) return Double.NaN; + return array[index]; + } + + @Override + public void setValue(WriteGraph graph, Object value) throws DatabaseException { + ensureInformationAvailable(graph); + double[] existing = getValueFull(); + double[] newValue = Arrays.copyOf(existing, existing.length); + newValue[index] = (Double)value; + super.setValue(graph, newValue); + } + + @Override + public void setValue(WriteGraph graph, Object value, Binding binding) throws DatabaseException { + setValue(graph, value); + } + + @Override + public String getName(ReadGraph graph) throws DatabaseException { + return "$" + index; + } + + @Override + public Object getSerialized(ReadGraph graph) throws DatabaseException { + return "$" + index; + } + + @Override + public Datatype getDatatype(ReadGraph graph) throws DatabaseException { + return Datatypes.DOUBLE; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValuesIndexVariable.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValuesIndexVariable.java new file mode 100644 index 00000000..d0eb2032 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValuesIndexVariable.java @@ -0,0 +1,62 @@ +package org.simantics.sysdyn.adapter; + +import java.util.ArrayList; +import java.util.Collection; + +import org.simantics.db.ReadGraph; +import org.simantics.db.WriteGraph; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.variable.Variable; +import org.simantics.sysdyn.manager.SysdynDataSet; +import org.simantics.sysdyn.manager.SysdynGameExperimentBase; +import org.simantics.sysdyn.manager.SysdynResult; + +public class ValuesIndexVariable extends IndexVariable { + + public ValuesIndexVariable(ReadGraph graph, Variable parent, String indexes) + throws DatabaseException { + super(graph, parent, indexes); + } + + @Override + public double[][] getValue() { + ArrayList variableNames = getVariableNamesWithIndexNumbers(); + double[][] result = new double[variableNames.size()][]; + + if (experiment != null) { + Collection results = experiment.getActiveResults(); + for(int i = 0; i < variableNames.size(); i++) { + for(SysdynResult r : results) { + SysdynDataSet ds = r.getDataSet(variableNames.get(i)); + if(ds != null && ds.values != null) { + result[i] = new double[ds.values.length]; + for(int j = 0; j < ds.values.length; j++) { + result[i][j] = ds.values[j]; + } + + /* + * If this is the actual simulation result and experiment is game experiment, + * get the last value from experiment. It might be different from the result + * file, if it has been modified in current time step + */ + if(experiment instanceof SysdynGameExperimentBase && ds.result == null) { + double d = ((SysdynGameExperimentBase)experiment).getCurrentValue(variableNames.get(i)); + result[i][ds.values.length - 1] = d; + } + break; // Show the first result found. (i.e. do not show history datasets) + } + + if(result[i] == null) + result[i] = new double[0]; + } + } + } + return result; + } + + @Override + public void setIndexedValue(WriteGraph graph, Object value) + throws DatabaseException { + + } +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/VariableRVIUtils.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/VariableRVIUtils.java new file mode 100644 index 00000000..7b6a68bc --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/VariableRVIUtils.java @@ -0,0 +1,345 @@ +/******************************************************************************* + * Copyright (c) 2007, 2011 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.adapter; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; + +import org.simantics.databoard.Bindings; +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.common.request.ObjectsWithType; +import org.simantics.db.common.utils.ListUtils; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.request.VariableRead; +import org.simantics.db.layer0.variable.Variable; +import org.simantics.db.layer0.variable.Variables; +import org.simantics.layer0.Layer0; +import org.simantics.sysdyn.SysdynResource; +import org.simantics.sysdyn.manager.SysdynDataSet; + +/** + * Utils for finding all active rvis for a single variable. A variable can have multiple + * rvis, if it is an array variable. Active rvis can be limited using a boolean value sr.ShowEnumerationIndexInCharts + * + * Example rvis for a variable with two enumerations (/ModuleInstance1/ModuleInstance2/Variable[Enumeration, Enumeration2]): + * + * /ModuleInstance1/ModuleInstance2/Variable[index1, index1] + * /ModuleInstance1/ModuleInstance2/Variable[index1, index2] + * /ModuleInstance1/ModuleInstance2/Variable[index2, index1] + * /ModuleInstance1/ModuleInstance2/Variable[index2, index2] + * + * + * + * @author Teemu Lempinen + * + */ +public class VariableRVIUtils { + + /** + * Recursive function for finding number format and label for the set of rvis. (rvis.put("Variable[1]", "Variable[index1]"); + * At the end of the recursive calls, rvis contains all possible combinations of enumeration indexes that are + * set to be shown in charts + * + * @param g ReadGraph + * @param rvi RVI of the variable + * @param rvis RVI map containing the full rvi with enumerations. Key contains numerical + * value of the enumeration and value contains the name of the enumeration (e.g. ["Variable[1]", "Variable[index1]"]) + * @param arrayIndexes ArrayIndex resources, Enumerations. + * @throws DatabaseException + */ + private static void traverseIndexes(ReadGraph g, String rvi, HashMap rvis, List arrayIndexes) throws DatabaseException { + traverseIndexes(g, rvi, rvis, arrayIndexes, 0, "", ""); + } + + /** + * Recursive function for finding number format and label for the set of rvis. (rvis.put("Variable[1]", "Variable[index1]"); + * At the end of the recursive calls, rvis contains all possible combinations of enumeration indexes that are + * set to be shown in charts + * + * @param g ReadGraph + * @param rvi RVI of the variable + * @param rvis RVI map containing the full rvi with enumerations. Key contains numerical + * @param arrayIndexes ArrayIndex resources, Enumerations. + * @param currentEnumeration Currently evaluated enumeration index (in arrayIndexes list) + * @param indexesSoFar String representation of the indexes so far in numerical format + * @param indexNamesSoFar String representation of the indexes so far in name format + * @throws DatabaseException + */ + private static void traverseIndexes(ReadGraph g, String rvi, HashMap rvis, List arrayIndexes, int currentIndex, String indexesSoFar, String indexNamesSoFar) throws DatabaseException { + SysdynResource sr = SysdynResource.getInstance(g); + // Enumeration indexes of the current enumeration (e.g. the first EnumIndexes in Var[EnumIndexes, EnumIndexes, EnumIndexes]) + Resource enumerationIndexes = g.getPossibleObject(arrayIndexes.get(currentIndex), sr.Enumeration_enumerationIndexList); + if(enumerationIndexes == null) + return; + List indexes = ListUtils.toList(g, enumerationIndexes); + for(int i = 0; i < indexes.size(); i++) { + Boolean b = g.getPossibleRelatedValue(indexes.get(i), sr.EnumerationIndex_showEnumerationIndexInCharts, Bindings.BOOLEAN); + // If this index is not wanted to be shown in charts, the recursion does not go any further and rvis.put() is not called for this enumeration + if(Boolean.TRUE.equals(b)) { + // Get the name of the index + String name = g.getRelatedValue(indexes.get(i), Layer0.getInstance(g).HasName); + if(currentIndex < arrayIndexes.size() - 1) + // If there are still more EnumIndexes, recursively call the function and add current index to indexesSoFar and indexNamesSoFar + traverseIndexes(g, rvi, rvis, arrayIndexes, currentIndex + 1, + indexesSoFar + (i + 1) +",", indexNamesSoFar + (name) +","); + else { + // The last enumeration. Add [rvi[1, 1, 1] = rvi[index1, index1, index1]}and so on to the rvis map + rvis.put( + rvi + "[" + indexesSoFar + (i + 1) + "]", + rvi + "[" + indexNamesSoFar + (name) + "]"); + } + } + } + } + + /** + * Resolves and replaces all overridden enumerations in enumerations -list + * + * @param graph ReadGraph + * @param variable Selected variable + * @param enumerations List of array indexes of the variable + * @return + */ + private static List resolveActiveArrayIndexes(ReadGraph graph, Variable variable, List enumerations) { + try { + Layer0 l0 = Layer0.getInstance(graph); + SysdynResource sr = SysdynResource.getInstance(graph); + String uri = variable.getURI(graph); + uri = uri.substring(0, uri.lastIndexOf("/")); + // The parent configuration or module + Variable v = Variables.getPossibleVariable(graph, uri); + if(v != null) { + Resource module = v.getRepresents(graph); + if(module != null && graph.isInheritedFrom(graph.getSingleObject(module, l0.InstanceOf), sr.Module)) { + // If the variable is located in a module, it might have overridden (redeclared) enumerations + boolean somethingIsReplaced = false; + // Find all redeclarations + for(Resource redeclaration : graph.syncRequest(new ObjectsWithType(module, sr.Module_redeclaration, sr.Redeclaration))) { + Resource replaced = graph.getSingleObject(redeclaration, sr.Redeclaration_replacedEnumeration); + while(enumerations.contains(replaced)) { + // Replace the redelcared enumeration in enumerations -list with the replacing enumeration + enumerations.add(enumerations.indexOf(replaced), graph.getSingleObject(redeclaration, sr.Redeclaration_replacingEnumeration)); + enumerations.remove(replaced); + somethingIsReplaced = true; + } + } + + if(somethingIsReplaced) { + // If something was replaced, do the same again for the parent configuration. The + // enumerations may be replaced throughout the whole model hierarchy + resolveActiveArrayIndexes(graph, v, enumerations); + } + } + } + } catch (DatabaseException e) { + e.printStackTrace(); + + } + return enumerations; + } + + + /** + * Returns rvis in a map in format /ModuleInstance/Variable[1] = /ModuleInstance/Variable[index1] + * @param graph ReadGraph + * @param variable Variable for the rvis + * @return rvis in a map. Keys are numerical formatted array indexes and values are textual. + * @throws DatabaseException + */ + public static HashMap getActiveRVIs(ReadGraph graph, Variable variable) throws DatabaseException { + return graph.syncRequest(new GetActiveRVIs(variable)); + } + + public static class GetActiveRVIs extends VariableRead> { + + public GetActiveRVIs(Variable variable) { + super(variable); + } + + @Override + public HashMap perform(ReadGraph graph) throws DatabaseException { + HashMap rvis = new LinkedHashMap(); + + SysdynResource sr = SysdynResource.getInstance(graph); + String rvi = Variables.getRVI(graph, variable); + Resource r = variable.getRepresents(graph); + + Resource arrayIndexes = graph.getPossibleObject(r, sr.Variable_arrayIndexesList); + if(arrayIndexes == null) { + // If variable is single-dimensional, use the same rvi + rvis.put(rvi, rvi); + } else { + // If variable is multidimensional, get all indexes that are active and add them to rvis-map + List arrayIndexList = ListUtils.toList(graph, arrayIndexes); + resolveActiveArrayIndexes(graph, variable, arrayIndexList); + + if(arrayIndexList.size() > 0) + traverseIndexes(graph, rvi, rvis, arrayIndexList); + else + rvis.put(rvi, rvi); + } + return rvis; + } + } + + + /** + * Filters a list of datasets of a single variable with a given filter. Filter should contain + * as many entries as the variable has enumerations. If the variable is Var[Enum1, Enum2, Enum3] + * the filter length should be 3. + * + * Allowed filter entries are All, Sum and a name of an index. + * + * Example filtering for variable Var[Enum1, Enum2, Enum3] where all enumerations have indexes {1, 2} + * + * filter: {All, Sum, 1} + * + * Filters are applied from back to front + * + * 1 1 1 + * 1 1 2 + * 1 2 1 1 1 1 + * 1 2 2 => 1 2 1 => 1 SUM(1 1, 2 1) + * 2 1 1 2 1 1 2 SUM(1 1, 2 1) + * 2 1 2 2 2 1 + * 2 2 1 + * 2 2 2 + * + * @param datasets List of SysdynDatasets for a single multidimensional variable + * @param filter filter for the datasets + * @return filtered list of SysdynDatasets + */ + public static ArrayList getDataset(ArrayList datasets, String[] filter) { + // If all filters are "All", no filtering is required. + boolean doFiltering = false; + for(String f : filter) { + if(!f.equalsIgnoreCase("All")) { + // One of the filters is not All -> do filtering + doFiltering = true; + break; + } + } + + if(doFiltering == false) + return datasets; + + // Start filtering with the complete set of datasets + ArrayList result = datasets; + + // Go through the filter from end to start + for(int i = filter.length - 1; i >= 0; i--) { + // Get the current filter + String currentFilter = filter[i].trim(); + + ArrayList tempResult = new ArrayList(); + HashMap sums = new HashMap(); + for(SysdynDataSet dataset : result) { + String tempIndexes = dataset.name.substring(dataset.name.indexOf('[') + 1, dataset.name.indexOf(']')); + String[] indexes = tempIndexes.split(","); + if(currentFilter.equals("All")) { + /* + * If the filter is "All", all datasets + * are kept for the next filtering + */ + tempResult.add(dataset); + } else if(currentFilter.equals(indexes[i].trim())) { + /* + * If the filter equals the index of the dataset + * at the same location, the dataset is kept for the next filtering + * + * e.g. + * dataset = Var[index3, index1, index2] + * filter = {All, index1, ALL} + * i = 1 (from 0 to 2) + * + * dataset's index and filter match at location 1 (the middle index) + */ + tempResult.add(dataset); + } else if(currentFilter.equals("Sum")) { + /* + * Whenever Sum is used as the filter, all datasets having the + * same indexes before the sum filter location are summed. + * + * e.g. + * filter = {1, 1, SUM} + * 1, 1, 1 + * 1, 1, 2 => 1, 1, SUM(1, 1, 1; 1, 1, 2) + * 1, 2, 1 1, 2, SUM(1, 2, 1; 1, 2, 2) + * 1, 2, 2 + */ + + // Find the preceding range (e.g. index1index2index2) + String rangeBefore = ""; + for(int j = 0; j < i; j++) + rangeBefore += indexes[j].trim(); + + // Find if there are any datasets for that preceding range in sums + SysdynDataSet sum = sums.get(rangeBefore); + if(sum != null) { + // A sum dataset was found. Add values from this dataset to the sum dataset + for(int j = 0; j < sum.values.length; j++) + sum.values[j] = sum.values[j] + dataset.values[j]; + } else { + // The first occurence of this preceding range, create a new dataset for the sum + + // Copy times and values + double[] times = new double[dataset.times.length]; + for(int j = 0; j < dataset.times.length; j++) + times[j] = dataset.times[j]; + double[] values = new double[dataset.values.length]; + for(int j = 0; j < dataset.values.length; j++) + values[j] = dataset.values[j]; + + // Create the dataset and add it to both tempResult and sums map + SysdynDataSet newDataset = new SysdynDataSet(dataset.name, dataset.result, times, values); + tempResult.add(newDataset); + sums.put(rangeBefore, newDataset); + + // Modify the name of the dataset by adding "Sum" to the current index location. + String name = newDataset.name.substring(0, newDataset.name.indexOf('[') + 1); + for(int j = 0; j < indexes.length; j++) { + if(j < i) + // Indexes before "Sum" stay the same + name += indexes[j].trim(); + else if(j >= i) + // Current "Sum" index and indexes after "Sum" are copied from filter + name += filter[j].trim(); + + if(j < indexes.length - 1) + name += ", "; + } + name += "]"; + + // Replace the sum dataset's name + newDataset.name = name; + } + + } else { + // Discard the series + } + } + + /* + * Replace result list with the filtered results and move on to next + * filter index or return the list + */ + result.clear(); + for(SysdynDataSet dataset : tempResult) + result.add(dataset); + } + return result; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/VariableValueSubscription.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/VariableValueSubscription.java new file mode 100644 index 00000000..716fd588 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/VariableValueSubscription.java @@ -0,0 +1,111 @@ +/******************************************************************************* + * Copyright (c) 2007, 2011 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.adapter; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.simantics.db.Session; +import org.simantics.db.WriteGraph; +import org.simantics.db.common.request.WriteRequest; +import org.simantics.db.common.utils.Logger; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.procedure.Listener; +import org.simantics.db.request.ExternalRead; +import org.simantics.db.service.QueryControl; +import org.simantics.utils.datastructures.Callback; + +public class VariableValueSubscription { + + public static final long SUBSCRIPTION_COLLECTION_INTERVAL = 2000L; + + protected ExternalRead request; + protected IndexVariable variable; + protected Listener listener; + + /** + * To protect against invoking listener.exception multiple times which is + * forbidden. + */ + protected AtomicBoolean excepted = new AtomicBoolean(false); + + public VariableValueSubscription(ExternalRead request, IndexVariable variable, Listener listener) { + this.request = request; + this.variable = variable; + this.listener = listener; + } + + public ExternalRead getRequest() { + return request; + } + + public void update() { + try { + T value = variable.getValue(); + fireValue(value); + } catch (Throwable e) { + fireException(e); + } + } + + void fireValue(T value) { + if (listener != null) + listener.execute(value); + } + + void fireException(Throwable t) { + if (listener != null && excepted.compareAndSet(false, true)) + listener.exception(t); + else + // Can't invoke listener.exception multiple times, but logging + // further exceptions anyway. + Logger.defaultLogError(t); + } + + public void setListener(Listener listener) { + this.listener = listener; + } + + /** + * This makes sure that subscriptions regarding performed DB external reads + * are abolished from DB client caches when no longer needed. + * + * @param session + * @param subscriptions + */ + @SuppressWarnings("rawtypes") + public static void collectSubscriptions(Session session, final VariableValueSubscription[] subscriptions, final ExternalRead... extraReads) { + if (subscriptions.length == 0 && extraReads.length == 0) + return; + + session.asyncRequest(new WriteRequest() { + @Override + public void perform(WriteGraph graph) throws DatabaseException { + Collection> requests = new ArrayList>(subscriptions.length + extraReads.length); + for (VariableValueSubscription subscription : subscriptions) + requests.add(subscription.getRequest()); + for (ExternalRead read : extraReads) + requests.add(read); + graph.getService(QueryControl.class).gc(graph, requests); + } + }, new Callback() { + @Override + public void run(DatabaseException e) { + if (e != null) + e.printStackTrace(); + } + }); + } + + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/IDistribution.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/IDistribution.java new file mode 100644 index 00000000..a0949854 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/IDistribution.java @@ -0,0 +1,27 @@ +/******************************************************************************* + * Copyright (c) 2013 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Semantum Oy - initial API and implementation + * VTT Technical Research Centre of Finland + *******************************************************************************/ +package org.simantics.sysdyn.adapter.distribution; + +public interface IDistribution { + + /** + * Map a probability to the random variable. + * When random numbers are used to generate the Monte Carlo simulation parameters, the probability + * is itself selected randomly (between (0,1); at the domain endpoints the value is undefined). + * + * @param probability + * @return Inverse cumulative distribution function at probability, i.e. the random variable at the + * point where the cumulative distribution function yields probability. + */ + public double inverseCDF(double probability); +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/Interval.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/Interval.java new file mode 100644 index 00000000..39fd8760 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/Interval.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (c) 2013 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Semantum Oy - initial API and implementation + * VTT Technical Research Centre of Finland + *******************************************************************************/ +package org.simantics.sysdyn.adapter.distribution; + +import org.simantics.databoard.Bindings; +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.exception.DatabaseException; +import org.simantics.layer0.Layer0; +import org.simantics.sysdyn.SysdynResource; + +public class Interval implements IDistribution { + + private double min = 0; + private double max = 10; + private double intervalLength = 1; + private int numberOfValues = 10; + private int index = 0; + + public Interval(ReadGraph graph, Resource distribution) { + + try { + SysdynResource SR = SysdynResource.getInstance(graph); + + Double minValue = graph.getPossibleRelatedValue(distribution, SR.Interval_minValue, Bindings.DOUBLE); + if(minValue != null) + this.min = minValue; + + Double maxValue = graph.getPossibleRelatedValue(distribution, SR.Interval_maxValue, Bindings.DOUBLE); + if(maxValue != null) + this.max = maxValue; + + Resource parameter = graph.getPossibleObject(distribution, SR.SensitivityAnalysisExperiment_Parameter_propabilityDistribution_Inverse); + + Resource experiment = graph.getPossibleObject(parameter, Layer0.getInstance(graph).PartOf); + + Integer numberOfValues = graph.getPossibleRelatedValue(experiment, SR.SensitivityAnalysisExperiment_numberOfValues, Bindings.INTEGER); + if(numberOfValues != null) + this.numberOfValues = numberOfValues; + + intervalLength = (maxValue - minValue) / (this.numberOfValues - 1); + + } catch (DatabaseException e) { + + } + } + + public double getMin() { + return min; + } + + public double getMax() { + return max; + } + + public int getNumberOfValues() { + return numberOfValues; + } + + public double getIntervalLength() { + return intervalLength; + } + + @Override + public double inverseCDF(double probability) { + // This is a bit awkward... + double value = min + (intervalLength * index); + index++; + if (index >= numberOfValues) + index = 0; + return value; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/NormalDistribution.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/NormalDistribution.java new file mode 100644 index 00000000..7887a62a --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/NormalDistribution.java @@ -0,0 +1,404 @@ +/******************************************************************************* + * Copyright (c) 2013 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Semantum Oy - initial API and implementation + * VTT Technical Research Centre of Finland + *******************************************************************************/ +package org.simantics.sysdyn.adapter.distribution; + + +import org.simantics.databoard.Bindings; +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.exception.DatabaseException; +import org.simantics.sysdyn.SysdynResource; + +public class NormalDistribution implements IDistribution { + + private Double min = null; + private Double max = null; + private double minProbability = 0; + private double maxProbability = 1; + private double mean; + private double stdDeviation; + + public NormalDistribution(ReadGraph graph, Resource distribution) { + + try { + + SysdynResource SR = SysdynResource.getInstance(graph); + + min = graph.getPossibleRelatedValue(distribution, SR.NormalDistribution_minValue, Bindings.DOUBLE); + max = graph.getPossibleRelatedValue(distribution, SR.NormalDistribution_maxValue, Bindings.DOUBLE); + stdDeviation = graph.getPossibleRelatedValue(distribution, SR.NormalDistribution_stdDeviation, Bindings.DOUBLE); + mean = graph.getPossibleRelatedValue(distribution, SR.NormalDistribution_mean, Bindings.DOUBLE); + + // Determine the max and min probabilities. + if (min != null) + minProbability = cdf(min, mean, stdDeviation, false); + if (max != null) + maxProbability = cdf(max, mean, stdDeviation, false); + + } catch (DatabaseException e) { + + } + } + + public double getMin() { + return min; + } + + public double getMax() { + return max; + } + + @Override + public double inverseCDF(double probability) { + // Map probability to [min,max] + double mappedProbability = minProbability + (maxProbability - minProbability) * probability; + // Calculate the inverse CDF + return quantile(mappedProbability, mean, stdDeviation); + } + + //The following is from BEAST-MCMC (https://code.google.com/p/beast-mcmc/) + + /* + * NormalDistribution.java + * + * Copyright (c) 2002-2011 Alexei Drummond, Andrew Rambaut and Marc Suchard + * + * This file is part of BEAST. + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership and licensing. + * + * BEAST is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * BEAST is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BEAST; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301 USA + */ + + /** + * quantiles (=inverse cumulative density function) + * + * @param z argument + * @param m mean + * @param sd standard deviation + * @return icdf at z + */ + public static double quantile(double z, double m, double sd) { + return m + Math.sqrt(2.0) * sd * inverseErf(2.0 * z - 1.0); + } + + /** A more accurate and faster implementation of the cdf (taken from function pnorm in the R statistical language) + * This implementation has discrepancies depending on the programming language and system architecture + * In Java, returned values become zero once z reaches -37.5193 exactly on the machine tested + * In the other implementation, the returned value 0 at about z = -8 + * In C, this 0 value is reached approximately z = -37.51938 + * + * Will later need to be optimised for BEAST + * + * @param x argument + * @param mu mean + * @param sigma standard deviation + * @param log_p is p logged + * @return cdf at x + */ + public static double cdf(double x, double mu, double sigma, boolean log_p) { + boolean i_tail=false; + double p, cp = Double.NaN; + + if(Double.isNaN(x) || Double.isNaN(mu) || Double.isNaN(sigma)) { + return Double.NaN; + } + if(Double.isInfinite(x) && mu == x) { /* x-mu is NaN */ + return Double.NaN; + } + if (sigma <= 0) { + if(sigma < 0) { + return Double.NaN; + } + return (x < mu) ? 0.0 : 1.0; + } + p = (x - mu) / sigma; + if(Double.isInfinite(p)) { + return (x < mu) ? 0.0 : 1.0; + } + x = p; + if(Double.isNaN(x)) { + return Double.NaN; + } + + double xden, xnum, temp, del, eps, xsq, y; + int i; + boolean lower, upper; + eps = DBL_EPSILON * 0.5; + lower = !i_tail; + upper = i_tail; + + y = Math.abs(x); + if (y <= 0.67448975) { /* Normal.quantile(3/4, 1, 0) = 0.67448975 */ + if (y > eps) { + xsq = x * x; + xnum = a[4] * xsq; + xden = xsq; + for (i = 0; i < 3; i++) { + xnum = (xnum + a[i]) * xsq; + xden = (xden + b[i]) * xsq; + } + } + else { + xnum = xden = 0.0; + } + temp = x * (xnum + a[3]) / (xden + b[3]); + if(lower) { + p = 0.5 + temp; + } + if(upper) { + cp = 0.5 - temp; + } + if(log_p) { + if(lower) { + p = Math.log(p); + } + if(upper) { + cp = Math.log(cp); + } + } + } + + + else if (y <= M_SQRT_32) { + /* Evaluate pnorm for 0.67448975 = Normal.quantile(3/4, 1, 0) < |x| <= sqrt(32) ~= 5.657 */ + + xnum = c[8] * y; + xden = y; + for (i = 0; i < 7; i++) { + xnum = (xnum + c[i]) * y; + xden = (xden + d[i]) * y; + } + temp = (xnum + c[7]) / (xden + d[7]); + + //do_del(y); + //swap_tail; + //#define do_del(X) \ + xsq = ((int) (y * CUTOFF)) * 1.0 / CUTOFF; + del = (y - xsq) * (y + xsq); + if(log_p) { + p = (-xsq * xsq * 0.5) + (-del * 0.5) + Math.log(temp); + if((lower && x > 0.0) || (upper && x <= 0.0)) { + cp = Math.log(1.0-Math.exp(-xsq * xsq * 0.5) * Math.exp(-del * 0.5) * temp); + } + } + else { + p = Math.exp(-xsq * xsq * 0.5) * Math.exp(-del * 0.5) * temp; + cp = 1.0 - p; + } + //#define swap_tail \ + if (x > 0.0) { + temp = p; + if(lower) { + p = cp; + } + cp = temp; + } + } + /* else |x| > sqrt(32) = 5.657 : + * the next two case differentiations were really for lower=T, log=F + * Particularly *not* for log_p ! + * Cody had (-37.5193 < x && x < 8.2924) ; R originally had y < 50 + * Note that we do want symmetry(0), lower/upper -> hence use y + */ + else if(log_p || (lower && -37.5193 < x && x < 8.2924) + || (upper && -8.2924 < x && x < 37.5193)) { + + /* Evaluate pnorm for x in (-37.5, -5.657) union (5.657, 37.5) */ + xsq = 1.0 / (x * x); + xnum = p_[5] * xsq; + xden = xsq; + for (i = 0; i < 4; i++) { + xnum = (xnum + p_[i]) * xsq; + xden = (xden + q[i]) * xsq; + } + temp = xsq * (xnum + p_[4]) / (xden + q[4]); + temp = (M_1_SQRT_2PI - temp) / y; + + //do_del(x); + xsq = ((int) (x * CUTOFF)) * 1.0 / CUTOFF; + del = (x - xsq) * (x + xsq); + if(log_p) { + p = (-xsq * xsq * 0.5) + (-del * 0.5) + Math.log(temp); + if((lower && x > 0.0) || (upper && x <= 0.0)) { + cp = Math.log(1.0-Math.exp(-xsq * xsq * 0.5) * Math.exp(-del * 0.5) * temp); + } + } + else { + p = Math.exp(-xsq * xsq * 0.5) * Math.exp(-del * 0.5) * temp; + cp = 1.0 - p; + } + //swap_tail; + if (x > 0.0) { + temp = p; + if(lower) { + p = cp; + } + cp = temp; + } + } + else { /* no log_p , large x such that probs are 0 or 1 */ + if(x > 0) { + p = 1.0; + cp = 0.0; + } + else { + p = 0.0; + cp = 1.0; + } + } + return p; + + } + + // Private + + protected double m, sd; + + private static final double[] a = { + 2.2352520354606839287, + 161.02823106855587881, + 1067.6894854603709582, + 18154.981253343561249, + 0.065682337918207449113 + }; + private static final double[] b = { + 47.20258190468824187, + 976.09855173777669322, + 10260.932208618978205, + 45507.789335026729956 + }; + private static final double[] c = { + 0.39894151208813466764, + 8.8831497943883759412, + 93.506656132177855979, + 597.27027639480026226, + 2494.5375852903726711, + 6848.1904505362823326, + 11602.651437647350124, + 9842.7148383839780218, + 1.0765576773720192317e-8 + }; + private static final double[] d = { + 22.266688044328115691, + 235.38790178262499861, + 1519.377599407554805, + 6485.558298266760755, + 18615.571640885098091, + 34900.952721145977266, + 38912.003286093271411, + 19685.429676859990727 + }; + private static final double[] p_ = { + 0.21589853405795699, + 0.1274011611602473639, + 0.022235277870649807, + 0.001421619193227893466, + 2.9112874951168792e-5, + 0.02307344176494017303 + }; + private static final double[] q = { + 1.28426009614491121, + 0.468238212480865118, + 0.0659881378689285515, + 0.00378239633202758244, + 7.29751555083966205e-5 + }; + + private static final int CUTOFF = 16; /* Cutoff allowing exact "*" and "/" */ + + private static final double M_SQRT_32 = 5.656854249492380195206754896838; /* The square root of 32 */ + private static final double M_1_SQRT_2PI = 0.398942280401432677939946059934; + private static final double DBL_EPSILON = 2.2204460492503131e-016; + + /* + * ErrorFunction.java + * + * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut + * + * This file is part of BEAST. + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership and licensing. + * + * BEAST is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * BEAST is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BEAST; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301 USA + */ + + /** + * inverse error function + * + * @param z argument + * + * @return function value + */ + public static double inverseErf(double z) + { + return pointNormal(0.5*z+0.5)/Math.sqrt(2.0); + } + + // Private + + // Returns z so that Prob{x primes; + + private void getPrimes() { + int newPrime = 2; + while (primes.size() < dimension) { + boolean isPrime = true; + for (int p : primes) { + if (newPrime % p == 0) { + ++newPrime; + isPrime = false; + break; + } + } + if (isPrime) { + primes.add(newPrime); + } + } + } + + public HaltonSequenceGenerator(ReadGraph graph, Resource method) { + + try { + SysdynResource SR = SysdynResource.getInstance(graph); + Resource experiment = graph.getPossibleObject(method, SR.SensitivityAnalysisExperiment_method_Inverse); + Resource parameterListResource = graph.getPossibleObject(experiment, SR.SensitivityAnalysisExperiment_parameterList); + dimension = ListUtils.getListNodes(graph, parameterListResource).size(); + + primes = new ArrayList(); + getPrimes(); + + initialize(); + } catch (DatabaseException e) { + + } + } + + public static double getHalton(int index, int base) { + ++index; // Map indexes to start from 1; + double result = 0; + double f = 1.0 / base; + while (index > 0) { + result = result + f * (index % base); + index = index / base; + f = f / base; + } + return result; + } + + public List next() { + ArrayList retval = new ArrayList(); + for (int i = 0; i < dimension; ++i) { + int base = primes.get(i); + double halton = getHalton(index, base); + retval.add(halton); + } + ++index; + return retval; + } + + public void initialize() { + index = 0; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/generator/IGenerator.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/generator/IGenerator.java new file mode 100644 index 00000000..59792648 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/generator/IGenerator.java @@ -0,0 +1,34 @@ +/******************************************************************************* + * Copyright (c) 2013 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.adapter.generator; + +import java.util.List; + +/** + * Interface for parameter value generators. + * + * @author Tuomas Miettinen + * + */ +public interface IGenerator { + + /** + * Get the next parameter combination. + * @return list of generated parameter values + */ + public List next(); + + /** + * Initialize the generator. + */ + public void initialize(); +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/generator/RandomGenerator.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/generator/RandomGenerator.java new file mode 100644 index 00000000..e4a920fe --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/generator/RandomGenerator.java @@ -0,0 +1,64 @@ +/******************************************************************************* + * Copyright (c) 2013 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.adapter.generator; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +import org.simantics.databoard.Bindings; +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.common.utils.ListUtils; +import org.simantics.db.exception.DatabaseException; +import org.simantics.sysdyn.SysdynResource; + +/** + * Random generator that creates ArrayLists of random Doubles between 0 and 1. + * + * @author Tuomas Miettinen + */ + +public class RandomGenerator implements IGenerator { + + private int seed; + private int dimension; + private Random random; + + public RandomGenerator(ReadGraph graph, Resource method) { + + try { + SysdynResource SR = SysdynResource.getInstance(graph); + Resource experiment = graph.getPossibleObject(method, SR.SensitivityAnalysisExperiment_method_Inverse); + seed = graph.getPossibleRelatedValue(experiment, SR.SensitivityAnalysisExperiment_randomSeed, Bindings.INTEGER); + + Resource parameterListResource = graph.getPossibleObject(experiment, SR.SensitivityAnalysisExperiment_parameterList); + dimension = ListUtils.getListNodes(graph, parameterListResource).size(); + + initialize(); + } catch (DatabaseException e) { + + } + } + + public List next() { + ArrayList randoms = new ArrayList(); + for (int i = 0; i < dimension; ++i) + randoms.add(random.nextDouble()); + return randoms; + } + + public void initialize() { + random = new Random(this.seed); + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/AdjacencyList.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/AdjacencyList.java new file mode 100644 index 00000000..47c784c2 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/AdjacencyList.java @@ -0,0 +1,46 @@ +package org.simantics.sysdyn.elementaryCycles; + +import java.util.Vector; + + +/** + * Calculates the adjacency-list for a given adjacency-matrix. + * + * + * @author Frank Meyer, web@normalisiert.de + * @version 1.0, 26.08.2006 + * + */ +public class AdjacencyList { + /** + * Calculates a adjacency-list for a given array of an adjacency-matrix. + * + * @param adjacencyMatrix array with the adjacency-matrix that represents + * the graph + * @return int[][]-array of the adjacency-list of given nodes. The first + * dimension in the array represents the same node as in the given + * adjacency, the second dimension represents the indicies of those nodes, + * that are direct successornodes of the node. + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + public static int[][] getAdjacencyList(boolean[][] adjacencyMatrix) { + int[][] list = new int[adjacencyMatrix.length][]; + + for (int i = 0; i < adjacencyMatrix.length; i++) { + Vector v = new Vector(); + for (int j = 0; j < adjacencyMatrix[i].length; j++) { + if (adjacencyMatrix[i][j]) { + v.add(new Integer(j)); + } + } + + list[i] = new int[v.size()]; + for (int j = 0; j < v.size(); j++) { + Integer in = (Integer) v.get(j); + list[i][j] = in.intValue(); + } + } + + return list; + } +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/ElementaryCyclesSearch.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/ElementaryCyclesSearch.java new file mode 100644 index 00000000..641682f4 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/ElementaryCyclesSearch.java @@ -0,0 +1,167 @@ +package org.simantics.sysdyn.elementaryCycles; + +import java.util.List; +import java.util.Vector; + + + +/** + * Searchs all elementary cycles in a given directed graph. The implementation + * is independent from the concrete objects that represent the graphnodes, it + * just needs an array of the objects representing the nodes the graph + * and an adjacency-matrix of type boolean, representing the edges of the + * graph. It then calculates based on the adjacency-matrix the elementary + * cycles and returns a list, which contains lists itself with the objects of the + * concrete graphnodes-implementation. Each of these lists represents an + * elementary cycle.

+ * + * The implementation uses the algorithm of Donald B. Johnson for the search of + * the elementary cycles. For a description of the algorithm see:
+ * Donald B. Johnson: Finding All the Elementary Circuits of a Directed Graph. + * SIAM Journal on Computing. Volumne 4, Nr. 1 (1975), pp. 77-84.

+ * + * The algorithm of Johnson is based on the search for strong connected + * components in a graph. For a description of this part see:
+ * Robert Tarjan: Depth-first search and linear graph algorithms. In: SIAM + * Journal on Computing. Volume 1, Nr. 2 (1972), pp. 146-160.
+ * + * @author Frank Meyer, web_at_normalisiert_dot_de + * @version 1.2, 22.03.2009 + * + */ +@SuppressWarnings("rawtypes") +public class ElementaryCyclesSearch { + /** List of cycles */ + private List cycles = null; + + /** Adjacency-list of graph */ + private int[][] adjList = null; + + /** Graphnodes */ + private Object[] graphNodes = null; + + /** Blocked nodes, used by the algorithm of Johnson */ + private boolean[] blocked = null; + + /** B-Lists, used by the algorithm of Johnson */ + private Vector[] B = null; + + /** Stack for nodes, used by the algorithm of Johnson */ + private Vector stack = null; + + /** + * Constructor. + * + * @param matrix adjacency-matrix of the graph + * @param graphNodes array of the graphnodes of the graph; this is used to + * build sets of the elementary cycles containing the objects of the original + * graph-representation + */ + public ElementaryCyclesSearch(boolean[][] matrix, Object[] graphNodes) { + this.graphNodes = graphNodes; + this.adjList = AdjacencyList.getAdjacencyList(matrix); + } + + /** + * Returns List::List::Object with the Lists of nodes of all elementary + * cycles in the graph. + * + * @return List::List::Object with the Lists of the elementary cycles. + */ + public List getElementaryCycles() { + this.cycles = new Vector(); + this.blocked = new boolean[this.adjList.length]; + this.B = new Vector[this.adjList.length]; + this.stack = new Vector(); + StrongConnectedComponents sccs = new StrongConnectedComponents(this.adjList); + int s = 0; + + while (true) { + SCCResult sccResult = sccs.getAdjacencyList(s); + if (sccResult != null && sccResult.getAdjList() != null) { + Vector[] scc = sccResult.getAdjList(); + s = sccResult.getLowestNodeId(); + for (int j = 0; j < scc.length; j++) { + if ((scc[j] != null) && (scc[j].size() > 0)) { + this.blocked[j] = false; + this.B[j] = new Vector(); + } + } + + this.findCycles(s, s, scc); + s++; + } else { + break; + } + } + + return this.cycles; + } + + /** + * Calculates the cycles containing a given node in a strongly connected + * component. The method calls itself recursivly. + * + * @param v + * @param s + * @param adjList adjacency-list with the subgraph of the strongly + * connected component s is part of. + * @return true, if cycle found; false otherwise + */ + @SuppressWarnings("unchecked") + private boolean findCycles(int v, int s, Vector[] adjList) { + boolean f = false; + this.stack.add(new Integer(v)); + this.blocked[v] = true; + + for (int i = 0; i < adjList[v].size(); i++) { + int w = ((Integer) adjList[v].get(i)).intValue(); + // found cycle + if (w == s) { + Vector cycle = new Vector(); + for (int j = 0; j < this.stack.size(); j++) { + int index = ((Integer) this.stack.get(j)).intValue(); + cycle.add(this.graphNodes[index]); + } + this.cycles.add(cycle); + f = true; + } else if (!this.blocked[w]) { + if (this.findCycles(w, s, adjList)) { + f = true; + } + } + } + + if (f) { + this.unblock(v); + } else { + for (int i = 0; i < adjList[v].size(); i++) { + int w = ((Integer) adjList[v].get(i)).intValue(); + if (!this.B[w].contains(new Integer(v))) { + this.B[w].add(new Integer(v)); + } + } + } + + this.stack.remove(new Integer(v)); + return f; + } + + /** + * Unblocks recursivly all blocked nodes, starting with a given node. + * + * @param node node to unblock + */ + private void unblock(int node) { + this.blocked[node] = false; + Vector Bnode = this.B[node]; + while (Bnode.size() > 0) { + Integer w = (Integer) Bnode.get(0); + Bnode.remove(0); + if (this.blocked[w.intValue()]) { + this.unblock(w.intValue()); + } + } + } +} + diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/SCCResult.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/SCCResult.java new file mode 100644 index 00000000..c8787cd4 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/SCCResult.java @@ -0,0 +1,34 @@ +package org.simantics.sysdyn.elementaryCycles; + +import java.util.HashSet; +import java.util.Set; +import java.util.Vector; + +@SuppressWarnings("rawtypes") +public class SCCResult { + private Set nodeIDsOfSCC = null; + private Vector[] adjList = null; + private int lowestNodeId = -1; + + @SuppressWarnings("unchecked") + public SCCResult(Vector[] adjList, int lowestNodeId) { + this.adjList = adjList; + this.lowestNodeId = lowestNodeId; + this.nodeIDsOfSCC = new HashSet(); + if (this.adjList != null) { + for (int i = this.lowestNodeId; i < this.adjList.length; i++) { + if (this.adjList[i].size() > 0) { + this.nodeIDsOfSCC.add(new Integer(i)); + } + } + } + } + + public Vector[] getAdjList() { + return adjList; + } + + public int getLowestNodeId() { + return lowestNodeId; + } +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/StrongConnectedComponents.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/StrongConnectedComponents.java new file mode 100644 index 00000000..8c966d31 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/StrongConnectedComponents.java @@ -0,0 +1,280 @@ +package org.simantics.sysdyn.elementaryCycles; + + +import java.util.Vector; + +/** + * This is a helpclass for the search of all elementary cycles in a graph + * with the algorithm of Johnson. For this it searches for strong connected + * components, using the algorithm of Tarjan. The constructor gets an + * adjacency-list of a graph. Based on this graph, it gets a nodenumber s, + * for which it calculates the subgraph, containing all nodes + * {s, s + 1, ..., n}, where n is the highest nodenumber in the original + * graph (e.g. it builds a subgraph with all nodes with higher or same + * nodenumbers like the given node s). It returns the strong connected + * component of this subgraph which contains the lowest nodenumber of all + * nodes in the subgraph.

+ * + * For a description of the algorithm for calculating the strong connected + * components see:
+ * Robert Tarjan: Depth-first search and linear graph algorithms. In: SIAM + * Journal on Computing. Volume 1, Nr. 2 (1972), pp. 146-160.
+ * For a description of the algorithm for searching all elementary cycles in + * a directed graph see:
+ * Donald B. Johnson: Finding All the Elementary Circuits of a Directed Graph. + * SIAM Journal on Computing. Volumne 4, Nr. 1 (1975), pp. 77-84.

+ * + * @author Frank Meyer, web_at_normalisiert_dot_de + * @version 1.1, 22.03.2009 + * + */ +@SuppressWarnings({"rawtypes", "unchecked"}) +public class StrongConnectedComponents { + /** Adjacency-list of original graph */ + private int[][] adjListOriginal = null; + + /** Adjacency-list of currently viewed subgraph */ + private int[][] adjList = null; + + /** Helpattribute for finding scc's */ + private boolean[] visited = null; + + /** Helpattribute for finding scc's */ + private Vector stack = null; + + /** Helpattribute for finding scc's */ + private int[] lowlink = null; + + /** Helpattribute for finding scc's */ + private int[] number = null; + + /** Helpattribute for finding scc's */ + private int sccCounter = 0; + + /** Helpattribute for finding scc's */ + private Vector currentSCCs = null; + + /** + * Constructor. + * + * @param adjList adjacency-list of the graph + */ + public StrongConnectedComponents(int[][] adjList) { + this.adjListOriginal = adjList; + } + + /** + * This method returns the adjacency-structure of the strong connected + * component with the least vertex in a subgraph of the original graph + * induced by the nodes {s, s + 1, ..., n}, where s is a given node. Note + * that trivial strong connected components with just one node will not + * be returned. + * + * @param node node s + * @return SCCResult with adjacency-structure of the strong + * connected component; null, if no such component exists + */ + public SCCResult getAdjacencyList(int node) { + this.visited = new boolean[this.adjListOriginal.length]; + this.lowlink = new int[this.adjListOriginal.length]; + this.number = new int[this.adjListOriginal.length]; + this.visited = new boolean[this.adjListOriginal.length]; + this.stack = new Vector(); + this.currentSCCs = new Vector(); + + this.makeAdjListSubgraph(node); + + for (int i = node; i < this.adjListOriginal.length; i++) { + if (!this.visited[i]) { + this.getStrongConnectedComponents(i); + Vector nodes = this.getLowestIdComponent(); + if (nodes != null && !nodes.contains(new Integer(node)) && !nodes.contains(new Integer(node + 1))) { + return this.getAdjacencyList(node + 1); + } else { + Vector[] adjacencyList = this.getAdjList(nodes); + if (adjacencyList != null) { + for (int j = 0; j < this.adjListOriginal.length; j++) { + if (adjacencyList[j].size() > 0) { + return new SCCResult(adjacencyList, j); + } + } + } + } + } + } + + return null; + } + + /** + * Builds the adjacency-list for a subgraph containing just nodes + * >= a given index. + * + * @param node Node with lowest index in the subgraph + */ + private void makeAdjListSubgraph(int node) { + this.adjList = new int[this.adjListOriginal.length][0]; + + for (int i = node; i < this.adjList.length; i++) { + Vector successors = new Vector(); + for (int j = 0; j < this.adjListOriginal[i].length; j++) { + if (this.adjListOriginal[i][j] >= node) { + successors.add(new Integer(this.adjListOriginal[i][j])); + } + } + if (successors.size() > 0) { + this.adjList[i] = new int[successors.size()]; + for (int j = 0; j < successors.size(); j++) { + Integer succ = (Integer) successors.get(j); + this.adjList[i][j] = succ.intValue(); + } + } + } + } + + /** + * Calculates the strong connected component out of a set of scc's, that + * contains the node with the lowest index. + * + * @return Vector::Integer of the scc containing the lowest nodenumber + */ + private Vector getLowestIdComponent() { + int min = this.adjList.length; + Vector currScc = null; + + for (int i = 0; i < this.currentSCCs.size(); i++) { + Vector scc = (Vector) this.currentSCCs.get(i); + for (int j = 0; j < scc.size(); j++) { + Integer node = (Integer) scc.get(j); + if (node.intValue() < min) { + currScc = scc; + min = node.intValue(); + } + } + } + + return currScc; + } + + /** + * @return Vector[]::Integer representing the adjacency-structure of the + * strong connected component with least vertex in the currently viewed + * subgraph + */ + private Vector[] getAdjList(Vector nodes) { + Vector[] lowestIdAdjacencyList = null; + + if (nodes != null) { + lowestIdAdjacencyList = new Vector[this.adjList.length]; + for (int i = 0; i < lowestIdAdjacencyList.length; i++) { + lowestIdAdjacencyList[i] = new Vector(); + } + for (int i = 0; i < nodes.size(); i++) { + int node = ((Integer) nodes.get(i)).intValue(); + for (int j = 0; j < this.adjList[node].length; j++) { + int succ = this.adjList[node][j]; + if (nodes.contains(new Integer(succ))) { + lowestIdAdjacencyList[node].add(new Integer(succ)); + } + } + } + } + + return lowestIdAdjacencyList; + } + + /** + * Searchs for strong connected components reachable from a given node. + * + * @param root node to start from. + */ + private void getStrongConnectedComponents(int root) { + this.sccCounter++; + this.lowlink[root] = this.sccCounter; + this.number[root] = this.sccCounter; + this.visited[root] = true; + this.stack.add(new Integer(root)); + + for (int i = 0; i < this.adjList[root].length; i++) { + int w = this.adjList[root][i]; + if (!this.visited[w]) { + this.getStrongConnectedComponents(w); + this.lowlink[root] = Math.min(lowlink[root], lowlink[w]); + } else if (this.number[w] < this.number[root]) { + if (this.stack.contains(new Integer(w))) { + lowlink[root] = Math.min(this.lowlink[root], this.number[w]); + } + } + } + + // found scc + if ((lowlink[root] == number[root]) && (stack.size() > 0)) { + int next = -1; + Vector scc = new Vector(); + + do { + next = ((Integer) this.stack.get(stack.size() - 1)).intValue(); + this.stack.remove(stack.size() - 1); + scc.add(new Integer(next)); + } while (this.number[next] > this.number[root]); + + // simple scc's with just one node will not be added + if (scc.size() > 1) { + this.currentSCCs.add(scc); + } + } + } + + public static void main(String[] args) { + boolean[][] adjMatrix = new boolean[10][]; + + for (int i = 0; i < 10; i++) { + adjMatrix[i] = new boolean[10]; + } + + /*adjMatrix[0][1] = true; + adjMatrix[1][2] = true; + adjMatrix[2][0] = true; + adjMatrix[2][4] = true; + adjMatrix[1][3] = true; + adjMatrix[3][6] = true; + adjMatrix[6][5] = true; + adjMatrix[5][3] = true; + adjMatrix[6][7] = true; + adjMatrix[7][8] = true; + adjMatrix[7][9] = true; + adjMatrix[9][6] = true;*/ + + adjMatrix[0][1] = true; + adjMatrix[1][2] = true; + adjMatrix[2][0] = true; adjMatrix[2][6] = true; + adjMatrix[3][4] = true; + adjMatrix[4][5] = true; adjMatrix[4][6] = true; + adjMatrix[5][3] = true; + adjMatrix[6][7] = true; + adjMatrix[7][8] = true; + adjMatrix[8][6] = true; + + adjMatrix[6][1] = true; + + int[][] adjList = AdjacencyList.getAdjacencyList(adjMatrix); + StrongConnectedComponents scc = new StrongConnectedComponents(adjList); + for (int i = 0; i < adjList.length; i++) { + System.out.print("i: " + i + "\n"); + SCCResult r = scc.getAdjacencyList(i); + if (r != null) { + Vector[] al = scc.getAdjacencyList(i).getAdjList(); + for (int j = i; j < al.length; j++) { + if (al[j].size() > 0) { + System.out.print("j: " + j); + for (int k = 0; k < al[j].size(); k++) { + System.out.print(" _" + al[j].get(k).toString()); + } + System.out.print("\n"); + } + } + System.out.print("\n"); + } + } + } +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/TestCycles.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/TestCycles.java new file mode 100644 index 00000000..e846272e --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/TestCycles.java @@ -0,0 +1,68 @@ +package org.simantics.sysdyn.elementaryCycles; + + +import java.util.List; + + +/** + * Testfile for elementary cycle search. + * + * @author Frank Meyer + * + */ +public class TestCycles { + + /** + * @param args + */ + @SuppressWarnings("rawtypes") + public static void main(String[] args) { + String nodes[] = new String[10]; + boolean adjMatrix[][] = new boolean[10][10]; + + for (int i = 0; i < 10; i++) { + nodes[i] = "Node " + i; + } + + adjMatrix[0][1] = true; + adjMatrix[1][2] = true; + adjMatrix[2][0] = true; + adjMatrix[2][4] = true; + adjMatrix[1][3] = true; + adjMatrix[3][6] = true; + adjMatrix[6][5] = true; + adjMatrix[5][3] = true; + adjMatrix[6][7] = true; + adjMatrix[7][8] = true; + adjMatrix[7][9] = true; + adjMatrix[9][6] = true; + /* + adjMatrix[0][1] = true; + adjMatrix[1][2] = true; + adjMatrix[2][0] = true; adjMatrix[2][6] = true; + adjMatrix[3][4] = true; + adjMatrix[4][5] = true; adjMatrix[4][6] = true; + adjMatrix[5][3] = true; + adjMatrix[6][7] = true; + adjMatrix[7][8] = true; + adjMatrix[8][6] = true; + + adjMatrix[6][1] = true; +*/ + ElementaryCyclesSearch ecs = new ElementaryCyclesSearch(adjMatrix, nodes); + List cycles = ecs.getElementaryCycles(); + for (int i = 0; i < cycles.size(); i++) { + List cycle = (List) cycles.get(i); + for (int j = 0; j < cycle.size(); j++) { + String node = (String) cycle.get(j); + if (j < cycle.size() - 1) { + System.out.print(node + " -> "); + } else { + System.out.print(node); + } + } + System.out.print("\n"); + } + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/license.txt b/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/license.txt new file mode 100644 index 00000000..0ed76f9c --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/license.txt @@ -0,0 +1,11 @@ +(BSD-2 license) + +Copyright (c) 2012, Frank Meyer +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParser.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParser.java new file mode 100644 index 00000000..5b37fb68 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParser.java @@ -0,0 +1,1862 @@ +/* Generated By:JavaCC: Do not edit this line. ExpressionParser.java */ +package org.simantics.sysdyn.expressionParser; + +import java.util.Set; +import java.util.HashSet; +import java.util.List; +import java.util.ArrayList; +import java.util.HashMap; + +@SuppressWarnings({"unused", "serial"}) +public class ExpressionParser implements ExpressionParserConstants { + + public class ForRange { + public Token start; + public Token end; + } + + boolean forIndex = false; + Token firstToken; + + public Token getFirstToken() { + return firstToken; + } + + List forRanges = new ArrayList(); + + public List getForRanges() { + return forRanges; + } + + HashMap> references = new HashMap>(); + + public HashMap> getReferences() { + return references; + } + + HashMap>> ranges = new HashMap>>(); + + public HashMap>> getRanges() { + return ranges; + } + + List currentRange = null; + + HashMap> forIndices = new HashMap>(); + + public HashMap> getForIndices() { + return forIndices; + } + + HashMap> enumerationReferences = new HashMap>(); + + public HashMap> getEnumerationReferences() { + return enumerationReferences; + } + +/* + Collect EACH function call and all references that are inside the call brackets. + These are later used to exclude spread sheet references out of the normal functions. +*/ + String functionCall = null; + HashMap> functionCallReferences = new HashMap>(); + + public HashMap> getFunctionCallReferences() { + return functionCallReferences; + } + +/*** Parser ********************************************************/ + +// https://javacc.dev.java.net/doc/javaccgrm.html +// add_op -> add_op() +// [ add_op ] -> ( add_op() )? +// { add_op term } -> ( add_op() term() )* + final public void expr() throws ParseException { + jj_input_stream.setTabSize(1); + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 6: + case 12: + case 33: + case 35: + case 60: + case 62: + case 64: + case 76: + case 77: + case 78: + case 79: + case IDENT: + case QIDENT: + case STRING: + case UNSIGNED_INTEGER: + case UNSIGNED_NUMBER: + firstToken = token; + simple_expression(); + jj_consume_token(0); + break; + case 31: + firstToken = token; + jj_consume_token(31); + expression(); + jj_consume_token(28); + expression(); + label_1: + while (true) { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 20: + ; + break; + default: + jj_la1[0] = jj_gen; + break label_1; + } + jj_consume_token(20); + expression(); + jj_consume_token(28); + expression(); + } + jj_consume_token(15); + expression(); + jj_consume_token(0); + break; + default: + jj_la1[1] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + } + + final public void expression() throws ParseException { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 6: + case 12: + case 33: + case 35: + case 60: + case 62: + case 64: + case 76: + case 77: + case 78: + case 79: + case IDENT: + case QIDENT: + case STRING: + case UNSIGNED_INTEGER: + case UNSIGNED_NUMBER: + simple_expression(); + break; + case 31: + jj_consume_token(31); + expression(); + jj_consume_token(28); + expression(); + label_2: + while (true) { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 20: + ; + break; + default: + jj_la1[2] = jj_gen; + break label_2; + } + jj_consume_token(20); + expression(); + jj_consume_token(28); + expression(); + } + jj_consume_token(15); + expression(); + break; + default: + jj_la1[3] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + } + + final public void simple_expression() throws ParseException { + logical_expression(); + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 67: + jj_consume_token(67); + logical_expression(); + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 67: + jj_consume_token(67); + logical_expression(); + break; + default: + jj_la1[4] = jj_gen; + ; + } + break; + default: + jj_la1[5] = jj_gen; + ; + } + } + + final public void logical_expression() throws ParseException { + logical_term(); + label_3: + while (true) { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 22: + ; + break; + default: + jj_la1[6] = jj_gen; + break label_3; + } + jj_consume_token(22); + logical_term(); + } + } + + final public void logical_term() throws ParseException { + logical_factor(); + label_4: + while (true) { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 9: + ; + break; + default: + jj_la1[7] = jj_gen; + break label_4; + } + jj_consume_token(9); + logical_factor(); + } + } + + final public void logical_factor() throws ParseException { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 12: + jj_consume_token(12); + break; + default: + jj_la1[8] = jj_gen; + ; + } + relation(); + } + + final public void relation() throws ParseException { + arithmetic_expression(); + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 70: + case 71: + case 72: + case 73: + case 74: + case 75: + rel_op(); + arithmetic_expression(); + break; + default: + jj_la1[9] = jj_gen; + ; + } + } + + final public void rel_op() throws ParseException { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 70: + jj_consume_token(70); + break; + case 71: + jj_consume_token(71); + break; + case 72: + jj_consume_token(72); + break; + case 73: + jj_consume_token(73); + break; + case 74: + jj_consume_token(74); + break; + case 75: + jj_consume_token(75); + break; + default: + jj_la1[10] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + } + + final public void arithmetic_expression() throws ParseException { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 76: + case 77: + case 78: + case 79: + add_op(); + break; + default: + jj_la1[11] = jj_gen; + ; + } + term(); + label_5: + while (true) { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 76: + case 77: + case 78: + case 79: + ; + break; + default: + jj_la1[12] = jj_gen; + break label_5; + } + add_op(); + term(); + } + } + + final public void add_op() throws ParseException { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 76: + jj_consume_token(76); + break; + case 77: + jj_consume_token(77); + break; + case 78: + jj_consume_token(78); + break; + case 79: + jj_consume_token(79); + break; + default: + jj_la1[13] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + } + + final public void term() throws ParseException { + factor(); + label_6: + while (true) { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 80: + case 81: + case 82: + case 83: + ; + break; + default: + jj_la1[14] = jj_gen; + break label_6; + } + mul_op(); + factor(); + } + } + + final public void factor() throws ParseException { + primary(); + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 84: + case 85: + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 84: + jj_consume_token(84); + break; + case 85: + jj_consume_token(85); + break; + default: + jj_la1[15] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + primary(); + break; + default: + jj_la1[16] = jj_gen; + ; + } + } + + final public void mul_op() throws ParseException { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 80: + jj_consume_token(80); + break; + case 81: + jj_consume_token(81); + break; + case 82: + jj_consume_token(82); + break; + case 83: + jj_consume_token(83); + break; + default: + jj_la1[17] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + } + + final public void primary() throws ParseException { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case UNSIGNED_NUMBER: + jj_consume_token(UNSIGNED_NUMBER); + break; + case UNSIGNED_INTEGER: + jj_consume_token(UNSIGNED_INTEGER); + break; + case STRING: + jj_consume_token(STRING); + break; + case 6: + jj_consume_token(6); + break; + case 33: + jj_consume_token(33); + break; + default: + jj_la1[19] = jj_gen; + if (jj_2_1(2147483647)) { + functionCall = null; + name(); + function_call_args(); + functionCall = null; + } else { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case IDENT: + case QIDENT: + component_reference(null); + break; + case 60: + jj_consume_token(60); + expression(); + jj_consume_token(61); + break; + case 64: + jj_consume_token(64); + expression_list(); + label_7: + while (true) { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 68: + ; + break; + default: + jj_la1[18] = jj_gen; + break label_7; + } + jj_consume_token(68); + expression_list(); + } + jj_consume_token(65); + break; + case 62: + jj_consume_token(62); + function_arguments(); + jj_consume_token(63); + break; + case 35: + jj_consume_token(35); + break; + default: + jj_la1[20] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + } + } + } + + final public Token ident() throws ParseException { + Token concatToken = null; + Token continuationToken = null; + String fullStr = null; + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case IDENT: + jj_consume_token(IDENT); + concatToken = token; + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case IDENT: + case QIDENT: + continuationToken = ident(); + fullStr = new String(""); + // Replace whitespace sequence with a single space character. + fullStr += concatToken.image + " " + continuationToken.image; + + Token tempToken = new Token(concatToken.kind, fullStr); + tempToken.beginLine = concatToken.beginLine; + tempToken.beginColumn = concatToken.beginColumn; + tempToken.endLine = token.endLine; + tempToken.endColumn = token.endColumn; + concatToken = tempToken; + break; + default: + jj_la1[21] = jj_gen; + ; + } + {if (true) return concatToken;} + break; + case QIDENT: + jj_consume_token(QIDENT); + {if (true) return token;} + break; + default: + jj_la1[22] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + throw new Error("Missing return statement in function"); + } + + final public void name() throws ParseException { + Token identToken = null; + identToken = ident(); + if (functionCall == null) + functionCall = identToken.image; + else + functionCall += "." + identToken.image; + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 66: + jj_consume_token(66); + name(); + break; + default: + jj_la1[23] = jj_gen; + ; + } + } + + final public void component_reference(String prevToken) throws ParseException { + Token identToken = null; + //IDENT [ array_subscripts ] [ "." component_reference ] + identToken = ident(); + String name = identToken.image; + // forIndex == true and prevToken != null => this is the second part of an enumeration in for-index + if(forIndex == true) { + if(prevToken != null) { + if(enumerationReferences.get(prevToken) == null) { + enumerationReferences.put(prevToken, new ArrayList()); + } + List list = enumerationReferences.get(prevToken); + list.add(identToken); + + // forIndex == true and prevToken == null => this is the enumeration in for-index + } else { + if(enumerationReferences.get(name) == null) { + enumerationReferences.put(name, new ArrayList()); + } + List list = enumerationReferences.get(name); + list.add(identToken); + } + } else { + if(prevToken != null) + name = prevToken + "." + name; + if(references.get(name) == null) { + references.put(name, new ArrayList()); + } + List list = references.get(name); + list.add(identToken); + + if(functionCall != null) { + if(!functionCallReferences.containsKey(functionCall)) + functionCallReferences.put(functionCall, new ArrayList()); + List functionReferencelist = getFunctionCallReferences().get(functionCall); + functionReferencelist.add(identToken); + } + } + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 64: + array_subscripts(identToken); + break; + default: + jj_la1[24] = jj_gen; + ; + } + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 66: + jj_consume_token(66); + component_reference(name); + break; + default: + jj_la1[25] = jj_gen; + ; + } + } + + final public void function_call_args() throws ParseException { + jj_consume_token(60); + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 6: + case 12: + case 31: + case 33: + case 35: + case 60: + case 62: + case 64: + case 76: + case 77: + case 78: + case 79: + case IDENT: + case QIDENT: + case STRING: + case UNSIGNED_INTEGER: + case UNSIGNED_NUMBER: + function_arguments(); + break; + default: + jj_la1[26] = jj_gen; + ; + } + jj_consume_token(61); + if(functionCall != null) { + if(!functionCallReferences.containsKey(functionCall)) + functionCallReferences.put(functionCall, new ArrayList()); + } + } + + final public void function_arguments() throws ParseException { + if (jj_2_2(2147483647)) { + named_argument(); + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 69: + jj_consume_token(69); + function_arguments(); + break; + default: + jj_la1[27] = jj_gen; + ; + } + } else { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 6: + case 12: + case 31: + case 33: + case 35: + case 60: + case 62: + case 64: + case 76: + case 77: + case 78: + case 79: + case IDENT: + case QIDENT: + case STRING: + case UNSIGNED_INTEGER: + case UNSIGNED_NUMBER: + expression(); + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 21: + case 69: + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 69: + jj_consume_token(69); + function_arguments(); + break; + case 21: + jj_consume_token(21); + for_indices(); + break; + default: + jj_la1[28] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + break; + default: + jj_la1[29] = jj_gen; + ; + } + break; + default: + jj_la1[30] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + } + } + + final public void for_indices() throws ParseException { + for_index(); + label_8: + while (true) { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 69: + ; + break; + default: + jj_la1[31] = jj_gen; + break label_8; + } + jj_consume_token(69); + for_index(); + } + } + + final public void for_index() throws ParseException { + Token identToken = null; + //IDENT [ in expression ] + identToken = ident(); + forIndices.put(identToken, currentRange); + forIndex = true; + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 41: + jj_consume_token(41); + ForRange forRange = new ForRange(); + forRange.start = token; + expression(); + forRange.start = forRange.start.next; + forRange.end = token; + forRanges.add(forRange); + break; + default: + jj_la1[32] = jj_gen; + ; + } + forIndex = false; + } + +/* Removed by Teemu. Refactored in function_arguments) +void named_arguments() : { +} { + named_argument() ( "," named_arguments() )? +} +*/ + final public void named_argument() throws ParseException { + ident(); + jj_consume_token(86); + expression(); + } + + final public void output_expression_list() throws ParseException { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 6: + case 12: + case 31: + case 33: + case 35: + case 60: + case 62: + case 64: + case 76: + case 77: + case 78: + case 79: + case IDENT: + case QIDENT: + case STRING: + case UNSIGNED_INTEGER: + case UNSIGNED_NUMBER: + expression(); + break; + default: + jj_la1[33] = jj_gen; + ; + } + label_9: + while (true) { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 69: + ; + break; + default: + jj_la1[34] = jj_gen; + break label_9; + } + jj_consume_token(69); + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 6: + case 12: + case 31: + case 33: + case 35: + case 60: + case 62: + case 64: + case 76: + case 77: + case 78: + case 79: + case IDENT: + case QIDENT: + case STRING: + case UNSIGNED_INTEGER: + case UNSIGNED_NUMBER: + expression(); + break; + default: + jj_la1[35] = jj_gen; + ; + } + } + } + + final public void expression_list() throws ParseException { + expression(); + label_10: + while (true) { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 69: + ; + break; + default: + jj_la1[36] = jj_gen; + break label_10; + } + jj_consume_token(69); + expression(); + } + } + + final public void array_subscripts(Token prevToken) throws ParseException { + if(ranges.get(prevToken.image) == null) { + ranges.put(prevToken.image, new ArrayList>()); + } + List> rangesList = ranges.get(prevToken.image); + currentRange = new ArrayList(); + jj_consume_token(64); + subscript(currentRange); + label_11: + while (true) { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 69: + ; + break; + default: + jj_la1[37] = jj_gen; + break label_11; + } + jj_consume_token(69); + subscript(currentRange); + } + jj_consume_token(65); + rangesList.add(currentRange); + } + + final public void subscript(List currentRange) throws ParseException { + Token rangeToken = new Token(token.kind, ""); + rangeToken.beginColumn = token.beginColumn + 1; + rangeToken.beginLine = token.beginLine; + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 67: + jj_consume_token(67); + currentRange.add(token); + break; + default: + jj_la1[40] = jj_gen; + if (jj_2_3(2147483647)) { + functionCall = null; + name(); + function_call_args(); + functionCall = null; + rangeToken.image = ""; + rangeToken.endColumn = token.endColumn; + rangeToken.endLine = token.endLine; + currentRange.add(rangeToken); + } else { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case IDENT: + case QIDENT: + case UNSIGNED_INTEGER: + rangeIndex(rangeToken, true, ":"); + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 67: + jj_consume_token(67); + rangeIndex(rangeToken, false, ":"); + break; + default: + jj_la1[38] = jj_gen; + ; + } + rangeToken.endColumn = token.endColumn; + rangeToken.endLine = token.endLine; + currentRange.add(rangeToken); + break; + case 62: + jj_consume_token(62); + rangeToken.image = rangeToken.image + token.image; + rangeIndex(rangeToken, true, ","); + label_12: + while (true) { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case 69: + ; + break; + default: + jj_la1[39] = jj_gen; + break label_12; + } + jj_consume_token(69); + rangeIndex(rangeToken, false, ","); + } + rangeToken.endColumn = token.endColumn; + rangeToken.endLine = token.endLine; + currentRange.add(rangeToken); + jj_consume_token(63); + rangeToken.image = rangeToken.image + token.image; + break; + default: + jj_la1[41] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + } + } + } + + final public void rangeIndex(Token rangeToken, boolean first, String delim) throws ParseException { + Token identToken = null; + if(!first) + rangeToken.image = rangeToken.image + delim; + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case UNSIGNED_INTEGER: + jj_consume_token(UNSIGNED_INTEGER); + rangeToken.image = rangeToken.image + token.image; + break; + case IDENT: + case QIDENT: + identToken = ident(); + rangeToken.image = rangeToken.image + identToken; + break; + default: + jj_la1[42] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + } + + private boolean jj_2_1(int xla) { + jj_la = xla; jj_lastpos = jj_scanpos = token; + try { return !jj_3_1(); } + catch(LookaheadSuccess ls) { return true; } + finally { jj_save(0, xla); } + } + + private boolean jj_2_2(int xla) { + jj_la = xla; jj_lastpos = jj_scanpos = token; + try { return !jj_3_2(); } + catch(LookaheadSuccess ls) { return true; } + finally { jj_save(1, xla); } + } + + private boolean jj_2_3(int xla) { + jj_la = xla; jj_lastpos = jj_scanpos = token; + try { return !jj_3_3(); } + catch(LookaheadSuccess ls) { return true; } + finally { jj_save(2, xla); } + } + + private boolean jj_3R_74() { + if (jj_scan_token(67)) return true; + if (jj_3R_73()) return true; + return false; + } + + private boolean jj_3R_35() { + if (jj_3R_39()) return true; + return false; + } + + private boolean jj_3R_33() { + Token xsp; + xsp = jj_scanpos; + if (jj_3R_35()) jj_scanpos = xsp; + if (jj_3R_36()) return true; + while (true) { + xsp = jj_scanpos; + if (jj_3R_37()) { jj_scanpos = xsp; break; } + } + return false; + } + + private boolean jj_3R_38() { + Token xsp; + xsp = jj_scanpos; + if (jj_scan_token(70)) { + jj_scanpos = xsp; + if (jj_scan_token(71)) { + jj_scanpos = xsp; + if (jj_scan_token(72)) { + jj_scanpos = xsp; + if (jj_scan_token(73)) { + jj_scanpos = xsp; + if (jj_scan_token(74)) { + jj_scanpos = xsp; + if (jj_scan_token(75)) return true; + } + } + } + } + } + return false; + } + + private boolean jj_3R_16() { + if (jj_scan_token(66)) return true; + if (jj_3R_13()) return true; + return false; + } + + private boolean jj_3R_26() { + if (jj_scan_token(67)) return true; + if (jj_3R_25()) return true; + Token xsp; + xsp = jj_scanpos; + if (jj_3R_29()) jj_scanpos = xsp; + return false; + } + + private boolean jj_3R_79() { + if (jj_3R_15()) return true; + return false; + } + + private boolean jj_3R_28() { + if (jj_scan_token(22)) return true; + if (jj_3R_27()) return true; + return false; + } + + private boolean jj_3R_80() { + if (jj_scan_token(41)) return true; + if (jj_3R_17()) return true; + return false; + } + + private boolean jj_3R_32() { + if (jj_3R_33()) return true; + Token xsp; + xsp = jj_scanpos; + if (jj_3R_34()) jj_scanpos = xsp; + return false; + } + + private boolean jj_3R_78() { + if (jj_scan_token(UNSIGNED_INTEGER)) return true; + return false; + } + + private boolean jj_3R_73() { + Token xsp; + xsp = jj_scanpos; + if (jj_3R_78()) { + jj_scanpos = xsp; + if (jj_3R_79()) return true; + } + return false; + } + + private boolean jj_3R_30() { + Token xsp; + xsp = jj_scanpos; + if (jj_scan_token(12)) jj_scanpos = xsp; + if (jj_3R_32()) return true; + return false; + } + + private boolean jj_3R_13() { + if (jj_3R_15()) return true; + Token xsp; + xsp = jj_scanpos; + if (jj_3R_16()) jj_scanpos = xsp; + return false; + } + + private boolean jj_3R_77() { + if (jj_scan_token(69)) return true; + if (jj_3R_76()) return true; + return false; + } + + private boolean jj_3R_27() { + if (jj_3R_30()) return true; + Token xsp; + while (true) { + xsp = jj_scanpos; + if (jj_3R_31()) { jj_scanpos = xsp; break; } + } + return false; + } + + private boolean jj_3R_66() { + if (jj_scan_token(69)) return true; + if (jj_3R_54()) return true; + return false; + } + + private boolean jj_3R_63() { + Token xsp; + xsp = jj_scanpos; + if (jj_3R_66()) { + jj_scanpos = xsp; + if (jj_3R_67()) return true; + } + return false; + } + + private boolean jj_3R_57() { + if (jj_scan_token(66)) return true; + if (jj_3R_51()) return true; + return false; + } + + private boolean jj_3R_76() { + if (jj_3R_15()) return true; + Token xsp; + xsp = jj_scanpos; + if (jj_3R_80()) jj_scanpos = xsp; + return false; + } + + private boolean jj_3R_25() { + if (jj_3R_27()) return true; + Token xsp; + while (true) { + xsp = jj_scanpos; + if (jj_3R_28()) { jj_scanpos = xsp; break; } + } + return false; + } + + private boolean jj_3_2() { + if (jj_3R_14()) return true; + return false; + } + + private boolean jj_3R_23() { + if (jj_3R_25()) return true; + Token xsp; + xsp = jj_scanpos; + if (jj_3R_26()) jj_scanpos = xsp; + return false; + } + + private boolean jj_3R_19() { + if (jj_scan_token(QIDENT)) return true; + return false; + } + + private boolean jj_3R_72() { + if (jj_3R_76()) return true; + Token xsp; + while (true) { + xsp = jj_scanpos; + if (jj_3R_77()) { jj_scanpos = xsp; break; } + } + return false; + } + + private boolean jj_3R_71() { + if (jj_scan_token(62)) return true; + if (jj_3R_73()) return true; + Token xsp; + while (true) { + xsp = jj_scanpos; + if (jj_3R_75()) { jj_scanpos = xsp; break; } + } + if (jj_scan_token(63)) return true; + return false; + } + + private boolean jj_3R_53() { + if (jj_scan_token(68)) return true; + if (jj_3R_52()) return true; + return false; + } + + private boolean jj_3R_21() { + if (jj_scan_token(31)) return true; + if (jj_3R_17()) return true; + if (jj_scan_token(28)) return true; + if (jj_3R_17()) return true; + Token xsp; + while (true) { + xsp = jj_scanpos; + if (jj_3R_24()) { jj_scanpos = xsp; break; } + } + if (jj_scan_token(15)) return true; + if (jj_3R_17()) return true; + return false; + } + + private boolean jj_3R_60() { + if (jj_3R_17()) return true; + Token xsp; + xsp = jj_scanpos; + if (jj_3R_63()) jj_scanpos = xsp; + return false; + } + + private boolean jj_3R_65() { + if (jj_scan_token(69)) return true; + if (jj_3R_64()) return true; + return false; + } + + private boolean jj_3R_20() { + if (jj_3R_23()) return true; + return false; + } + + private boolean jj_3R_17() { + Token xsp; + xsp = jj_scanpos; + if (jj_3R_20()) { + jj_scanpos = xsp; + if (jj_3R_21()) return true; + } + return false; + } + + private boolean jj_3_3() { + if (jj_3R_13()) return true; + if (jj_scan_token(60)) return true; + return false; + } + + private boolean jj_3R_70() { + if (jj_3R_73()) return true; + Token xsp; + xsp = jj_scanpos; + if (jj_3R_74()) jj_scanpos = xsp; + return false; + } + + private boolean jj_3R_59() { + if (jj_3R_14()) return true; + Token xsp; + xsp = jj_scanpos; + if (jj_3R_62()) jj_scanpos = xsp; + return false; + } + + private boolean jj_3R_54() { + Token xsp; + xsp = jj_scanpos; + if (jj_3R_59()) { + jj_scanpos = xsp; + if (jj_3R_60()) return true; + } + return false; + } + + private boolean jj_3R_55() { + if (jj_3R_54()) return true; + return false; + } + + private boolean jj_3R_22() { + if (jj_3R_15()) return true; + return false; + } + + private boolean jj_3R_69() { + if (jj_3R_13()) return true; + if (jj_3R_50()) return true; + return false; + } + + private boolean jj_3R_18() { + if (jj_scan_token(IDENT)) return true; + Token xsp; + xsp = jj_scanpos; + if (jj_3R_22()) jj_scanpos = xsp; + return false; + } + + private boolean jj_3R_15() { + Token xsp; + xsp = jj_scanpos; + if (jj_3R_18()) { + jj_scanpos = xsp; + if (jj_3R_19()) return true; + } + return false; + } + + private boolean jj_3R_50() { + if (jj_scan_token(60)) return true; + Token xsp; + xsp = jj_scanpos; + if (jj_3R_55()) jj_scanpos = xsp; + if (jj_scan_token(61)) return true; + return false; + } + + private boolean jj_3R_56() { + if (jj_3R_61()) return true; + return false; + } + + private boolean jj_3R_68() { + if (jj_scan_token(67)) return true; + return false; + } + + private boolean jj_3R_64() { + Token xsp; + xsp = jj_scanpos; + if (jj_3R_68()) { + jj_scanpos = xsp; + if (jj_3R_69()) { + jj_scanpos = xsp; + if (jj_3R_70()) { + jj_scanpos = xsp; + if (jj_3R_71()) return true; + } + } + } + return false; + } + + private boolean jj_3_1() { + if (jj_3R_13()) return true; + if (jj_scan_token(60)) return true; + return false; + } + + private boolean jj_3R_49() { + if (jj_scan_token(62)) return true; + if (jj_3R_54()) return true; + if (jj_scan_token(63)) return true; + return false; + } + + private boolean jj_3R_48() { + if (jj_scan_token(64)) return true; + if (jj_3R_52()) return true; + Token xsp; + while (true) { + xsp = jj_scanpos; + if (jj_3R_53()) { jj_scanpos = xsp; break; } + } + if (jj_scan_token(65)) return true; + return false; + } + + private boolean jj_3R_47() { + if (jj_scan_token(60)) return true; + if (jj_3R_17()) return true; + if (jj_scan_token(61)) return true; + return false; + } + + private boolean jj_3R_46() { + if (jj_3R_51()) return true; + return false; + } + + private boolean jj_3R_58() { + if (jj_scan_token(69)) return true; + if (jj_3R_17()) return true; + return false; + } + + private boolean jj_3R_61() { + if (jj_scan_token(64)) return true; + if (jj_3R_64()) return true; + Token xsp; + while (true) { + xsp = jj_scanpos; + if (jj_3R_65()) { jj_scanpos = xsp; break; } + } + if (jj_scan_token(65)) return true; + return false; + } + + private boolean jj_3R_45() { + if (jj_3R_13()) return true; + if (jj_3R_50()) return true; + return false; + } + + private boolean jj_3R_43() { + Token xsp; + xsp = jj_scanpos; + if (jj_scan_token(84)) { + jj_scanpos = xsp; + if (jj_scan_token(85)) return true; + } + if (jj_3R_42()) return true; + return false; + } + + private boolean jj_3R_42() { + Token xsp; + xsp = jj_scanpos; + if (jj_scan_token(92)) { + jj_scanpos = xsp; + if (jj_scan_token(91)) { + jj_scanpos = xsp; + if (jj_scan_token(90)) { + jj_scanpos = xsp; + if (jj_scan_token(6)) { + jj_scanpos = xsp; + if (jj_scan_token(33)) { + jj_scanpos = xsp; + if (jj_3R_45()) { + jj_scanpos = xsp; + if (jj_3R_46()) { + jj_scanpos = xsp; + if (jj_3R_47()) { + jj_scanpos = xsp; + if (jj_3R_48()) { + jj_scanpos = xsp; + if (jj_3R_49()) { + jj_scanpos = xsp; + if (jj_scan_token(35)) return true; + } + } + } + } + } + } + } + } + } + } + return false; + } + + private boolean jj_3R_29() { + if (jj_scan_token(67)) return true; + if (jj_3R_25()) return true; + return false; + } + + private boolean jj_3R_41() { + if (jj_3R_44()) return true; + if (jj_3R_40()) return true; + return false; + } + + private boolean jj_3R_34() { + if (jj_3R_38()) return true; + if (jj_3R_33()) return true; + return false; + } + + private boolean jj_3R_37() { + if (jj_3R_39()) return true; + if (jj_3R_36()) return true; + return false; + } + + private boolean jj_3R_44() { + Token xsp; + xsp = jj_scanpos; + if (jj_scan_token(80)) { + jj_scanpos = xsp; + if (jj_scan_token(81)) { + jj_scanpos = xsp; + if (jj_scan_token(82)) { + jj_scanpos = xsp; + if (jj_scan_token(83)) return true; + } + } + } + return false; + } + + private boolean jj_3R_40() { + if (jj_3R_42()) return true; + Token xsp; + xsp = jj_scanpos; + if (jj_3R_43()) jj_scanpos = xsp; + return false; + } + + private boolean jj_3R_52() { + if (jj_3R_17()) return true; + Token xsp; + while (true) { + xsp = jj_scanpos; + if (jj_3R_58()) { jj_scanpos = xsp; break; } + } + return false; + } + + private boolean jj_3R_75() { + if (jj_scan_token(69)) return true; + if (jj_3R_73()) return true; + return false; + } + + private boolean jj_3R_62() { + if (jj_scan_token(69)) return true; + if (jj_3R_54()) return true; + return false; + } + + private boolean jj_3R_14() { + if (jj_3R_15()) return true; + if (jj_scan_token(86)) return true; + if (jj_3R_17()) return true; + return false; + } + + private boolean jj_3R_67() { + if (jj_scan_token(21)) return true; + if (jj_3R_72()) return true; + return false; + } + + private boolean jj_3R_24() { + if (jj_scan_token(20)) return true; + if (jj_3R_17()) return true; + if (jj_scan_token(28)) return true; + if (jj_3R_17()) return true; + return false; + } + + private boolean jj_3R_36() { + if (jj_3R_40()) return true; + Token xsp; + while (true) { + xsp = jj_scanpos; + if (jj_3R_41()) { jj_scanpos = xsp; break; } + } + return false; + } + + private boolean jj_3R_39() { + Token xsp; + xsp = jj_scanpos; + if (jj_scan_token(76)) { + jj_scanpos = xsp; + if (jj_scan_token(77)) { + jj_scanpos = xsp; + if (jj_scan_token(78)) { + jj_scanpos = xsp; + if (jj_scan_token(79)) return true; + } + } + } + return false; + } + + private boolean jj_3R_51() { + if (jj_3R_15()) return true; + Token xsp; + xsp = jj_scanpos; + if (jj_3R_56()) jj_scanpos = xsp; + xsp = jj_scanpos; + if (jj_3R_57()) jj_scanpos = xsp; + return false; + } + + private boolean jj_3R_31() { + if (jj_scan_token(9)) return true; + if (jj_3R_30()) return true; + return false; + } + + /** Generated Token Manager. */ + public ExpressionParserTokenManager token_source; + SimpleCharStream jj_input_stream; + /** Current token. */ + public Token token; + /** Next token. */ + public Token jj_nt; + private int jj_ntk; + private Token jj_scanpos, jj_lastpos; + private int jj_la; + private int jj_gen; + final private int[] jj_la1 = new int[43]; + static private int[] jj_la1_0; + static private int[] jj_la1_1; + static private int[] jj_la1_2; + static { + jj_la1_init_0(); + jj_la1_init_1(); + jj_la1_init_2(); + } + private static void jj_la1_init_0() { + jj_la1_0 = new int[] {0x100000,0x80001040,0x100000,0x80001040,0x0,0x0,0x400000,0x200,0x1000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x40,0x0,0x0,0x0,0x0,0x0,0x0,0x80001040,0x0,0x200000,0x200000,0x80001040,0x0,0x0,0x80001040,0x0,0x80001040,0x0,0x0,0x0,0x0,0x0,0x0,0x0,}; + } + private static void jj_la1_init_1() { + jj_la1_1 = new int[] {0x0,0x5000000a,0x0,0x5000000a,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x2,0x50000008,0x0,0x0,0x0,0x0,0x0,0x5000000a,0x0,0x0,0x0,0x5000000a,0x0,0x200,0x5000000a,0x0,0x5000000a,0x0,0x0,0x0,0x0,0x0,0x40000000,0x0,}; + } + private static void jj_la1_init_2() { + jj_la1_2 = new int[] {0x0,0x1f00f001,0x0,0x1f00f001,0x8,0x8,0x0,0x0,0x0,0xfc0,0xfc0,0xf000,0xf000,0xf000,0xf0000,0x300000,0x300000,0xf0000,0x10,0x1c000000,0x3000001,0x3000000,0x3000000,0x4,0x1,0x4,0x1f00f001,0x20,0x20,0x20,0x1f00f001,0x20,0x0,0x1f00f001,0x20,0x1f00f001,0x20,0x20,0x8,0x20,0x8,0xb000000,0xb000000,}; + } + final private JJCalls[] jj_2_rtns = new JJCalls[3]; + private boolean jj_rescan = false; + private int jj_gc = 0; + + /** Constructor with InputStream. */ + public ExpressionParser(java.io.InputStream stream) { + this(stream, null); + } + /** Constructor with InputStream and supplied encoding */ + public ExpressionParser(java.io.InputStream stream, String encoding) { + try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } + token_source = new ExpressionParserTokenManager(jj_input_stream); + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 43; i++) jj_la1[i] = -1; + for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + } + + /** Reinitialise. */ + public void ReInit(java.io.InputStream stream) { + ReInit(stream, null); + } + /** Reinitialise. */ + public void ReInit(java.io.InputStream stream, String encoding) { + try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } + token_source.ReInit(jj_input_stream); + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 43; i++) jj_la1[i] = -1; + for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + } + + /** Constructor. */ + public ExpressionParser(java.io.Reader stream) { + jj_input_stream = new SimpleCharStream(stream, 1, 1); + token_source = new ExpressionParserTokenManager(jj_input_stream); + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 43; i++) jj_la1[i] = -1; + for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + } + + /** Reinitialise. */ + public void ReInit(java.io.Reader stream) { + jj_input_stream.ReInit(stream, 1, 1); + token_source.ReInit(jj_input_stream); + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 43; i++) jj_la1[i] = -1; + for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + } + + /** Constructor with generated Token Manager. */ + public ExpressionParser(ExpressionParserTokenManager tm) { + token_source = tm; + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 43; i++) jj_la1[i] = -1; + for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + } + + /** Reinitialise. */ + public void ReInit(ExpressionParserTokenManager tm) { + token_source = tm; + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 43; i++) jj_la1[i] = -1; + for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + } + + private Token jj_consume_token(int kind) throws ParseException { + Token oldToken; + if ((oldToken = token).next != null) token = token.next; + else token = token.next = token_source.getNextToken(); + jj_ntk = -1; + if (token.kind == kind) { + jj_gen++; + if (++jj_gc > 100) { + jj_gc = 0; + for (int i = 0; i < jj_2_rtns.length; i++) { + JJCalls c = jj_2_rtns[i]; + while (c != null) { + if (c.gen < jj_gen) c.first = null; + c = c.next; + } + } + } + return token; + } + token = oldToken; + jj_kind = kind; + throw generateParseException(); + } + + static private final class LookaheadSuccess extends java.lang.Error { } + final private LookaheadSuccess jj_ls = new LookaheadSuccess(); + private boolean jj_scan_token(int kind) { + if (jj_scanpos == jj_lastpos) { + jj_la--; + if (jj_scanpos.next == null) { + jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken(); + } else { + jj_lastpos = jj_scanpos = jj_scanpos.next; + } + } else { + jj_scanpos = jj_scanpos.next; + } + if (jj_rescan) { + int i = 0; Token tok = token; + while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; } + if (tok != null) jj_add_error_token(kind, i); + } + if (jj_scanpos.kind != kind) return true; + if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls; + return false; + } + + +/** Get the next Token. */ + final public Token getNextToken() { + if (token.next != null) token = token.next; + else token = token.next = token_source.getNextToken(); + jj_ntk = -1; + jj_gen++; + return token; + } + +/** Get the specific Token. */ + final public Token getToken(int index) { + Token t = token; + for (int i = 0; i < index; i++) { + if (t.next != null) t = t.next; + else t = t.next = token_source.getNextToken(); + } + return t; + } + + private int jj_ntk() { + if ((jj_nt=token.next) == null) + return (jj_ntk = (token.next=token_source.getNextToken()).kind); + else + return (jj_ntk = jj_nt.kind); + } + + private java.util.List jj_expentries = new java.util.ArrayList(); + private int[] jj_expentry; + private int jj_kind = -1; + private int[] jj_lasttokens = new int[100]; + private int jj_endpos; + + private void jj_add_error_token(int kind, int pos) { + if (pos >= 100) return; + if (pos == jj_endpos + 1) { + jj_lasttokens[jj_endpos++] = kind; + } else if (jj_endpos != 0) { + jj_expentry = new int[jj_endpos]; + for (int i = 0; i < jj_endpos; i++) { + jj_expentry[i] = jj_lasttokens[i]; + } + jj_entries_loop: for (java.util.Iterator it = jj_expentries.iterator(); it.hasNext();) { + int[] oldentry = (int[])(it.next()); + if (oldentry.length == jj_expentry.length) { + for (int i = 0; i < jj_expentry.length; i++) { + if (oldentry[i] != jj_expentry[i]) { + continue jj_entries_loop; + } + } + jj_expentries.add(jj_expentry); + break jj_entries_loop; + } + } + if (pos != 0) jj_lasttokens[(jj_endpos = pos) - 1] = kind; + } + } + + /** Generate ParseException. */ + public ParseException generateParseException() { + jj_expentries.clear(); + boolean[] la1tokens = new boolean[93]; + if (jj_kind >= 0) { + la1tokens[jj_kind] = true; + jj_kind = -1; + } + for (int i = 0; i < 43; i++) { + if (jj_la1[i] == jj_gen) { + for (int j = 0; j < 32; j++) { + if ((jj_la1_0[i] & (1< jj_gen) { + jj_la = p.arg; jj_lastpos = jj_scanpos = p.first; + switch (i) { + case 0: jj_3_1(); break; + case 1: jj_3_2(); break; + case 2: jj_3_3(); break; + } + } + p = p.next; + } while (p != null); + } catch(LookaheadSuccess ls) { } + } + jj_rescan = false; + } + + private void jj_save(int index, int xla) { + JJCalls p = jj_2_rtns[index]; + while (p.gen > jj_gen) { + if (p.next == null) { p = p.next = new JJCalls(); break; } + p = p.next; + } + p.gen = jj_gen + xla - jj_la; p.first = token; p.arg = xla; + } + + static final class JJCalls { + int gen; + Token first; + int arg; + JJCalls next; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParser.jj b/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParser.jj new file mode 100644 index 00000000..ce3aa44a --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParser.jj @@ -0,0 +1,430 @@ +options { + JDK_VERSION = "1.6"; + STATIC = false; +} + +PARSER_BEGIN(ExpressionParser) +package org.simantics.sysdyn.expressionParser; + +import java.util.Set; +import java.util.HashSet; +import java.util.List; +import java.util.ArrayList; +import java.util.HashMap; + +@SuppressWarnings({"unused", "serial"}) +public class ExpressionParser { + + public class ForRange { public Token start; + public Token end; + } + + boolean forIndex = false; + Token firstToken; + + public Token getFirstToken() { return firstToken; + } + List forRanges = new ArrayList(); + + public List getForRanges() { + return forRanges; + } + + HashMap> references = new HashMap>(); + + public HashMap> getReferences() { + return references; + } + + HashMap>> ranges = new HashMap>>(); + + public HashMap>> getRanges() { + return ranges; + } + + List currentRange = null; + + HashMap> forIndices = new HashMap>(); + + public HashMap> getForIndices() { + return forIndices; + } + + HashMap> enumerationReferences = new HashMap>(); + + public HashMap> getEnumerationReferences() { + return enumerationReferences; + } + +/* + Collect EACH function call and all references that are inside the call brackets. + These are later used to exclude spread sheet references out of the normal functions. +*/ + String functionCall = null; + HashMap> functionCallReferences = new HashMap>(); + + public HashMap> getFunctionCallReferences() { + return functionCallReferences; + } + + +} +PARSER_END(ExpressionParser) + +/*** Lexer *********************************************************/ + +SKIP: +{ +| +| +} + +TOKEN: +{ +"algorithm" | "discrete" | "false" | "model" | "redeclare" +| "and" | "each" | "final" | "not" | "replaceable" +| "annotation" | "else" | "flow" | "operator" | "return" +|"assert" | "elseif" | "for" | "or" | "stream" +| "block" | "elsewhen" | "function" | "outer" | "then" +| "break" | "encapsulated" | "if" | "output" | "true" +| "class" | "end" | "import" | "package" | "type" +| "connect" | "enumeration" | "in" | "parameter" | "when" +| "connector" | "equation" | /*"initial" |*/ "partial" | "while" +| "constant" | "expandable" | "inner" | "protected" | "within" +| "constrainedby" | "extends" | "input" | "public" +| /*"der" |*/ "external" | "loop" | "record" +| "(" | ")" | "{" | "}" | "[" | "]" | "." | ":" | ";" | "," +| "<" | "<=" | ">" | ">=" | "==" | "<>" +| "+" | "-" | ".+" | ".-" +| "*" | "/" | ".*" | "./" +| "^" | ".^" +| "=" | ":=" +| +| + /* Excluded "#","$","%","&","(",")","<",">","[","]","{","}","|", and "\"" because of Sysdyn */ + /* Excluded "\?", "\a", and "\v" because of JavaCC */ + /* Excluded "\n","\r", and "\t" just in case */ +| + { matchedToken.image = matchedToken.image.substring(1,matchedToken.image.length()-1); } +| +| "." ()? (["e","E"] (["+","-"])? )? + | "." (["e","E"] (["+","-"])? )? + | ["e","E"] (["+","-"])? + ) > +} + +/*** Parser ********************************************************/ + +// https://javacc.dev.java.net/doc/javaccgrm.html +// add_op -> add_op() +// [ add_op ] -> ( add_op() )? +// { add_op term } -> ( add_op() term() )* + +void expr() : { + jj_input_stream.setTabSize(1); +} { + { + firstToken = token; + } + simple_expression() + | + { + firstToken = token; + } + "if" expression() "then" expression() ( "elseif" expression() "then" expression() )* + "else" expression() +} + +void expression() : { +} { + simple_expression() + | "if" expression() "then" expression() ( "elseif" expression() "then" expression() )* + "else" expression() +} + +void simple_expression() : { +} { + logical_expression() ( ":" logical_expression() ( ":" logical_expression() )? )? +} + +void logical_expression() : { +} { + logical_term() ( "or" logical_term() )* +} + +void logical_term() : { +} { + logical_factor() ( "and" logical_factor() )* +} + +void logical_factor() : { +} { + ( "not" )? relation() +} + +void relation() : { +} { + arithmetic_expression() ( rel_op() arithmetic_expression() )? +} + +void rel_op() : { +} { + "<" | "<=" | ">" | ">=" | "==" | "<>" +} + +void arithmetic_expression() : { +} { + (add_op())? term() (add_op() term())* +} + +void add_op() : { +} { + "+" | "-" | ".+" | ".-" +} + +void term() : { +} { + factor() ( mul_op() factor() )* +} + +void factor() : { +} { + primary() ( ( "^" | ".^" ) primary() )? +} + +void mul_op() : { +} { + "*" | "/" | ".*" | "./" +} + +void primary() : { +} { + + | + | + | "false" + | "true" + | LOOKAHEAD( name() "(" ) { functionCall = null; + } + name() function_call_args() { functionCall = null; + } + | component_reference(null) + /*| "(" output_expression_list() ")"*/ // Not needed, replaced with following: + | "(" expression() ")" + | "[" expression_list() ( ";" expression_list() )* "]" + | "{" function_arguments() "}" + | "end" +} + +Token ident() : { + Token concatToken = null; + Token continuationToken = null; + String fullStr = null; +} { + + { concatToken = token; } + ( continuationToken = ident() + { + fullStr = new String(""); + // Replace whitespace sequence with a single space character. + fullStr += concatToken.image + " " + continuationToken.image; + + Token tempToken = new Token(concatToken.kind, fullStr); + tempToken.beginLine = concatToken.beginLine; + tempToken.beginColumn = concatToken.beginColumn; + tempToken.endLine = token.endLine; + tempToken.endColumn = token.endColumn; + concatToken = tempToken; + } + )? + { return concatToken; + } + | + + { + return token; + } +} +void name() : { + Token identToken = null; +} { + identToken = ident() + { if (functionCall == null) + functionCall = identToken.image; + else + functionCall += "." + identToken.image; + } + ( "." name() )? +} + +void component_reference(String prevToken) : { + Token identToken = null; +} { + //IDENT [ array_subscripts ] [ "." component_reference ] + identToken = ident() + { + String name = identToken.image; + // forIndex == true and prevToken != null => this is the second part of an enumeration in for-index + if(forIndex == true) { if(prevToken != null) { + if(enumerationReferences.get(prevToken) == null) { enumerationReferences.put(prevToken, new ArrayList()); + } + List list = enumerationReferences.get(prevToken); + list.add(identToken); + + // forIndex == true and prevToken == null => this is the enumeration in for-index + } else { + if(enumerationReferences.get(name) == null) { + enumerationReferences.put(name, new ArrayList()); + } + List list = enumerationReferences.get(name); + list.add(identToken); + } + } else { + if(prevToken != null) + name = prevToken + "." + name; if(references.get(name) == null) { + references.put(name, new ArrayList()); + } + List list = references.get(name); + list.add(identToken); + + if(functionCall != null) { + if(!functionCallReferences.containsKey(functionCall)) + functionCallReferences.put(functionCall, new ArrayList()); + List functionReferencelist = getFunctionCallReferences().get(functionCall); + functionReferencelist.add(identToken); } + } + + } + + ( array_subscripts(identToken) )? ( "." component_reference(name) )? +} + +void function_call_args() : { +} { + "(" ( function_arguments() )? ")" { if(functionCall != null) { + if(!functionCallReferences.containsKey(functionCall)) + functionCallReferences.put(functionCall, new ArrayList()); + } + } +} + +void function_arguments() : { +} { + //expression [ "," function_arguments | for for_indices ] + //| named_arguments + LOOKAHEAD(named_argument()) named_argument() ( "," function_arguments() )? + | expression() ( "," function_arguments() | "for" for_indices() )? + +} + +void for_indices() : { +} { + //for_index {"," for_index} + for_index() ("," for_index())* +} + +void for_index() : { + Token identToken = null; +} { + //IDENT [ in expression ] + identToken = ident() + { + forIndices.put(identToken, currentRange); + forIndex = true; } + ( "in" { + ForRange forRange = new ForRange(); + forRange.start = token; } + expression() { + forRange.start = forRange.start.next; + forRange.end = token; + forRanges.add(forRange); } + )? + { forIndex = false; + } +} + +/* Removed by Teemu. Refactored in function_arguments) +void named_arguments() : { +} { + named_argument() ( "," named_arguments() )? +} +*/ + +void named_argument() : { +} { + ident() "=" expression() +} + +void output_expression_list() : { +} { + ( expression() )? ( "," ( expression() )? )* +} + + +void expression_list() : { +} { + expression() ( "," expression() )* +} + +void array_subscripts(Token prevToken) : { if(ranges.get(prevToken.image) == null) { + ranges.put(prevToken.image, new ArrayList>()); + } + List> rangesList = ranges.get(prevToken.image); + currentRange = new ArrayList(); +} { + "[" subscript(currentRange) ( "," subscript(currentRange) )* "]" + { + rangesList.add(currentRange); + } +} + +void subscript(List currentRange) : { + Token rangeToken = new Token(token.kind, ""); + rangeToken.beginColumn = token.beginColumn + 1; + rangeToken.beginLine = token.beginLine; +} { ":" { currentRange.add(token); + } + | LOOKAHEAD( name() "(" ) + { + functionCall = null; + } + name() function_call_args() + { + functionCall = null; + rangeToken.image = ""; + rangeToken.endColumn = token.endColumn; + rangeToken.endLine = token.endLine; + currentRange.add(rangeToken); + } + | rangeIndex(rangeToken, true, ":") ( ":" rangeIndex(rangeToken, false, ":"))? { + rangeToken.endColumn = token.endColumn; + rangeToken.endLine = token.endLine; + currentRange.add(rangeToken); + } + | "{" + { rangeToken.image = rangeToken.image + token.image; + } + rangeIndex(rangeToken, true, ",") ( "," rangeIndex(rangeToken, false, ","))* + { + rangeToken.endColumn = token.endColumn; + rangeToken.endLine = token.endLine; + currentRange.add(rangeToken); + } + "}" + { rangeToken.image = rangeToken.image + token.image; + } +} + +void rangeIndex(Token rangeToken, boolean first, String delim) : { + Token identToken = null; + if(!first) + rangeToken.image = rangeToken.image + delim; +} { { + rangeToken.image = rangeToken.image + token.image; } + | identToken = ident() + { rangeToken.image = rangeToken.image + identToken; + } +} + diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParserConstants.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParserConstants.java new file mode 100644 index 00000000..62dfa364 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParserConstants.java @@ -0,0 +1,130 @@ +/* Generated By:JavaCC: Do not edit this line. ExpressionParserConstants.java */ +package org.simantics.sysdyn.expressionParser; + + +/** + * Token literal values and constants. + * Generated by org.javacc.parser.OtherFilesGen#start() + */ +public interface ExpressionParserConstants { + + /** End of File. */ + int EOF = 0; + /** RegularExpression Id. */ + int WHITESPACE = 1; + /** RegularExpression Id. */ + int COMMENT1 = 2; + /** RegularExpression Id. */ + int COMMENT2 = 3; + /** RegularExpression Id. */ + int IDENT = 88; + /** RegularExpression Id. */ + int QIDENT = 89; + /** RegularExpression Id. */ + int STRING = 90; + /** RegularExpression Id. */ + int UNSIGNED_INTEGER = 91; + /** RegularExpression Id. */ + int UNSIGNED_NUMBER = 92; + + /** Lexical state. */ + int DEFAULT = 0; + + /** Literal token values. */ + String[] tokenImage = { + "", + "", + "", + "", + "\"algorithm\"", + "\"discrete\"", + "\"false\"", + "\"model\"", + "\"redeclare\"", + "\"and\"", + "\"each\"", + "\"final\"", + "\"not\"", + "\"replaceable\"", + "\"annotation\"", + "\"else\"", + "\"flow\"", + "\"operator\"", + "\"return\"", + "\"assert\"", + "\"elseif\"", + "\"for\"", + "\"or\"", + "\"stream\"", + "\"block\"", + "\"elsewhen\"", + "\"function\"", + "\"outer\"", + "\"then\"", + "\"break\"", + "\"encapsulated\"", + "\"if\"", + "\"output\"", + "\"true\"", + "\"class\"", + "\"end\"", + "\"import\"", + "\"package\"", + "\"type\"", + "\"connect\"", + "\"enumeration\"", + "\"in\"", + "\"parameter\"", + "\"when\"", + "\"connector\"", + "\"equation\"", + "\"partial\"", + "\"while\"", + "\"constant\"", + "\"expandable\"", + "\"inner\"", + "\"protected\"", + "\"within\"", + "\"constrainedby\"", + "\"extends\"", + "\"input\"", + "\"public\"", + "\"external\"", + "\"loop\"", + "\"record\"", + "\"(\"", + "\")\"", + "\"{\"", + "\"}\"", + "\"[\"", + "\"]\"", + "\".\"", + "\":\"", + "\";\"", + "\",\"", + "\"<\"", + "\"<=\"", + "\">\"", + "\">=\"", + "\"==\"", + "\"<>\"", + "\"+\"", + "\"-\"", + "\".+\"", + "\".-\"", + "\"*\"", + "\"/\"", + "\".*\"", + "\"./\"", + "\"^\"", + "\".^\"", + "\"=\"", + "\":=\"", + "", + "", + "", + "", + "", + }; + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParserTokenManager.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParserTokenManager.java new file mode 100644 index 00000000..85adbb72 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParserTokenManager.java @@ -0,0 +1,1361 @@ +/* Generated By:JavaCC: Do not edit this line. ExpressionParserTokenManager.java */ +package org.simantics.sysdyn.expressionParser; +import java.util.Set; +import java.util.HashSet; +import java.util.List; +import java.util.ArrayList; +import java.util.HashMap; + +/** Token Manager. */ +public class ExpressionParserTokenManager implements ExpressionParserConstants +{ + + /** Debug output. */ + public java.io.PrintStream debugStream = System.out; + /** Set debug output. */ + public void setDebugStream(java.io.PrintStream ds) { debugStream = ds; } +private final int jjStopStringLiteralDfa_0(int pos, long active0, long active1) +{ + switch (pos) + { + case 0: + if ((active1 & 0x2cc004L) != 0L) + return 12; + if ((active0 & 0xffffffffffffff0L) != 0L) + { + jjmatchedKind = 88; + return 2; + } + if ((active1 & 0x20000L) != 0L) + return 17; + return -1; + case 1: + if ((active0 & 0x84020080400000L) != 0L) + return 2; + if ((active0 & 0xf7bfdff7fbffff0L) != 0L) + { + if (jjmatchedPos != 1) + { + jjmatchedKind = 88; + jjmatchedPos = 1; + } + return 2; + } + return -1; + case 2: + if ((active0 & 0x800201200L) != 0L) + return 2; + if ((active0 & 0xffffdf77f9fedf0L) != 0L) + { + jjmatchedKind = 88; + jjmatchedPos = 2; + return 2; + } + return -1; + case 3: + if ((active0 & 0x400084212118400L) != 0L) + return 2; + if ((active0 & 0xbfff5b56d8e69f0L) != 0L) + { + if (jjmatchedPos != 3) + { + jjmatchedKind = 88; + jjmatchedPos = 3; + } + return 2; + } + return -1; + case 4: + if ((active0 & 0x848004290008c0L) != 0L) + return 2; + if ((active0 & 0xb7b75b1469e6130L) != 0L) + { + jjmatchedKind = 88; + jjmatchedPos = 4; + return 2; + } + return -1; + case 5: + if ((active0 & 0x9100011009c0000L) != 0L) + return 2; + if ((active0 & 0x26b75a046026130L) != 0L) + { + jjmatchedKind = 88; + jjmatchedPos = 5; + return 2; + } + return -1; + case 6: + if ((active0 & 0x4050a000000000L) != 0L) + return 2; + if ((active0 & 0x22b250046026130L) != 0L) + { + if (jjmatchedPos != 6) + { + jjmatchedKind = 88; + jjmatchedPos = 6; + } + return 2; + } + return -1; + case 7: + if ((active0 & 0x201200006020020L) != 0L) + return 2; + if ((active0 & 0x2a150040006110L) != 0L) + { + jjmatchedKind = 88; + jjmatchedPos = 7; + return 2; + } + return -1; + case 8: + if ((active0 & 0x22010040006000L) != 0L) + { + jjmatchedKind = 88; + jjmatchedPos = 8; + return 2; + } + if ((active0 & 0x8140000000110L) != 0L) + return 2; + return -1; + case 9: + if ((active0 & 0x2000000004000L) != 0L) + return 2; + if ((active0 & 0x20010040002000L) != 0L) + { + jjmatchedKind = 88; + jjmatchedPos = 9; + return 2; + } + return -1; + case 10: + if ((active0 & 0x10000002000L) != 0L) + return 2; + if ((active0 & 0x20000040000000L) != 0L) + { + jjmatchedKind = 88; + jjmatchedPos = 10; + return 2; + } + return -1; + case 11: + if ((active0 & 0x40000000L) != 0L) + return 2; + if ((active0 & 0x20000000000000L) != 0L) + { + jjmatchedKind = 88; + jjmatchedPos = 11; + return 2; + } + return -1; + default : + return -1; + } +} +private final int jjStartNfa_0(int pos, long active0, long active1) +{ + return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0, active1), pos + 1); +} +private int jjStopAtPos(int pos, int kind) +{ + jjmatchedKind = kind; + jjmatchedPos = pos; + return pos + 1; +} +private int jjMoveStringLiteralDfa0_0() +{ + switch(curChar) + { + case 40: + return jjStopAtPos(0, 60); + case 41: + return jjStopAtPos(0, 61); + case 42: + return jjStopAtPos(0, 80); + case 43: + return jjStopAtPos(0, 76); + case 44: + return jjStopAtPos(0, 69); + case 45: + return jjStopAtPos(0, 77); + case 46: + jjmatchedKind = 66; + return jjMoveStringLiteralDfa1_0(0x0L, 0x2cc000L); + case 47: + return jjStartNfaWithStates_0(0, 81, 17); + case 58: + jjmatchedKind = 67; + return jjMoveStringLiteralDfa1_0(0x0L, 0x800000L); + case 59: + return jjStopAtPos(0, 68); + case 60: + jjmatchedKind = 70; + return jjMoveStringLiteralDfa1_0(0x0L, 0x880L); + case 61: + jjmatchedKind = 86; + return jjMoveStringLiteralDfa1_0(0x0L, 0x400L); + case 62: + jjmatchedKind = 72; + return jjMoveStringLiteralDfa1_0(0x0L, 0x200L); + case 91: + return jjStopAtPos(0, 64); + case 93: + return jjStopAtPos(0, 65); + case 94: + return jjStopAtPos(0, 84); + case 97: + return jjMoveStringLiteralDfa1_0(0x84210L, 0x0L); + case 98: + return jjMoveStringLiteralDfa1_0(0x21000000L, 0x0L); + case 99: + return jjMoveStringLiteralDfa1_0(0x21108400000000L, 0x0L); + case 100: + return jjMoveStringLiteralDfa1_0(0x20L, 0x0L); + case 101: + return jjMoveStringLiteralDfa1_0(0x242210842108400L, 0x0L); + case 102: + return jjMoveStringLiteralDfa1_0(0x4210840L, 0x0L); + case 105: + return jjMoveStringLiteralDfa1_0(0x84021080000000L, 0x0L); + case 108: + return jjMoveStringLiteralDfa1_0(0x400000000000000L, 0x0L); + case 109: + return jjMoveStringLiteralDfa1_0(0x80L, 0x0L); + case 110: + return jjMoveStringLiteralDfa1_0(0x1000L, 0x0L); + case 111: + return jjMoveStringLiteralDfa1_0(0x108420000L, 0x0L); + case 112: + return jjMoveStringLiteralDfa1_0(0x108442000000000L, 0x0L); + case 114: + return jjMoveStringLiteralDfa1_0(0x800000000042100L, 0x0L); + case 115: + return jjMoveStringLiteralDfa1_0(0x800000L, 0x0L); + case 116: + return jjMoveStringLiteralDfa1_0(0x4210000000L, 0x0L); + case 119: + return jjMoveStringLiteralDfa1_0(0x10880000000000L, 0x0L); + case 123: + return jjStopAtPos(0, 62); + case 125: + return jjStopAtPos(0, 63); + default : + return jjMoveNfa_0(0, 0); + } +} +private int jjMoveStringLiteralDfa1_0(long active0, long active1) +{ + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { + jjStopStringLiteralDfa_0(0, active0, active1); + return 1; + } + switch(curChar) + { + case 42: + if ((active1 & 0x40000L) != 0L) + return jjStopAtPos(1, 82); + break; + case 43: + if ((active1 & 0x4000L) != 0L) + return jjStopAtPos(1, 78); + break; + case 45: + if ((active1 & 0x8000L) != 0L) + return jjStopAtPos(1, 79); + break; + case 47: + if ((active1 & 0x80000L) != 0L) + return jjStopAtPos(1, 83); + break; + case 61: + if ((active1 & 0x80L) != 0L) + return jjStopAtPos(1, 71); + else if ((active1 & 0x200L) != 0L) + return jjStopAtPos(1, 73); + else if ((active1 & 0x400L) != 0L) + return jjStopAtPos(1, 74); + else if ((active1 & 0x800000L) != 0L) + return jjStopAtPos(1, 87); + break; + case 62: + if ((active1 & 0x800L) != 0L) + return jjStopAtPos(1, 75); + break; + case 94: + if ((active1 & 0x200000L) != 0L) + return jjStopAtPos(1, 85); + break; + case 97: + return jjMoveStringLiteralDfa2_0(active0, 0x442000000440L, active1, 0L); + case 101: + return jjMoveStringLiteralDfa2_0(active0, 0x800000000042100L, active1, 0L); + case 102: + if ((active0 & 0x80000000L) != 0L) + return jjStartNfaWithStates_0(1, 31, 2); + break; + case 104: + return jjMoveStringLiteralDfa2_0(active0, 0x880010000000L, active1, 0L); + case 105: + return jjMoveStringLiteralDfa2_0(active0, 0x10000000000820L, active1, 0L); + case 108: + return jjMoveStringLiteralDfa2_0(active0, 0x403118010L, active1, 0L); + case 109: + return jjMoveStringLiteralDfa2_0(active0, 0x1000000000L, active1, 0L); + case 110: + if ((active0 & 0x20000000000L) != 0L) + { + jjmatchedKind = 41; + jjmatchedPos = 1; + } + return jjMoveStringLiteralDfa2_0(active0, 0x84010840004200L, active1, 0L); + case 111: + return jjMoveStringLiteralDfa2_0(active0, 0x421108000201080L, active1, 0L); + case 112: + return jjMoveStringLiteralDfa2_0(active0, 0x20000L, active1, 0L); + case 113: + return jjMoveStringLiteralDfa2_0(active0, 0x200000000000L, active1, 0L); + case 114: + if ((active0 & 0x400000L) != 0L) + return jjStartNfaWithStates_0(1, 22, 2); + return jjMoveStringLiteralDfa2_0(active0, 0x8000220000000L, active1, 0L); + case 115: + return jjMoveStringLiteralDfa2_0(active0, 0x80000L, active1, 0L); + case 116: + return jjMoveStringLiteralDfa2_0(active0, 0x800000L, active1, 0L); + case 117: + return jjMoveStringLiteralDfa2_0(active0, 0x10000010c000000L, active1, 0L); + case 120: + return jjMoveStringLiteralDfa2_0(active0, 0x242000000000000L, active1, 0L); + case 121: + return jjMoveStringLiteralDfa2_0(active0, 0x4000000000L, active1, 0L); + default : + break; + } + return jjStartNfa_0(0, active0, active1); +} +private int jjMoveStringLiteralDfa2_0(long old0, long active0, long old1, long active1) +{ + if (((active0 &= old0) | (active1 &= old1)) == 0L) + return jjStartNfa_0(0, old0, old1); + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { + jjStopStringLiteralDfa_0(1, active0, 0L); + return 2; + } + switch(curChar) + { + case 97: + return jjMoveStringLiteralDfa3_0(active0, 0x400000000L); + case 98: + return jjMoveStringLiteralDfa3_0(active0, 0x100000000000000L); + case 99: + return jjMoveStringLiteralDfa3_0(active0, 0x800002040000400L); + case 100: + if ((active0 & 0x200L) != 0L) + return jjStartNfaWithStates_0(2, 9, 2); + else if ((active0 & 0x800000000L) != 0L) + return jjStartNfaWithStates_0(2, 35, 2); + return jjMoveStringLiteralDfa3_0(active0, 0x180L); + case 101: + return jjMoveStringLiteralDfa3_0(active0, 0x80030020000L); + case 103: + return jjMoveStringLiteralDfa3_0(active0, 0x10L); + case 105: + return jjMoveStringLiteralDfa3_0(active0, 0x800000000000L); + case 108: + return jjMoveStringLiteralDfa3_0(active0, 0x40L); + case 110: + return jjMoveStringLiteralDfa3_0(active0, 0x25108004004800L); + case 111: + return jjMoveStringLiteralDfa3_0(active0, 0x408000001010000L); + case 112: + return jjMoveStringLiteralDfa3_0(active0, 0x82005000002000L); + case 114: + if ((active0 & 0x200000L) != 0L) + return jjStartNfaWithStates_0(2, 21, 2); + return jjMoveStringLiteralDfa3_0(active0, 0x440000800000L); + case 115: + return jjMoveStringLiteralDfa3_0(active0, 0x2188020L); + case 116: + if ((active0 & 0x1000L) != 0L) + return jjStartNfaWithStates_0(2, 12, 2); + return jjMoveStringLiteralDfa3_0(active0, 0x250000108040000L); + case 117: + return jjMoveStringLiteralDfa3_0(active0, 0x210200000000L); + default : + break; + } + return jjStartNfa_0(1, active0, 0L); +} +private int jjMoveStringLiteralDfa3_0(long old0, long active0) +{ + if (((active0 &= old0)) == 0L) + return jjStartNfa_0(1, old0, 0L); + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { + jjStopStringLiteralDfa_0(2, active0, 0L); + return 3; + } + switch(curChar) + { + case 97: + return jjMoveStringLiteralDfa4_0(active0, 0x2240060000800L); + case 99: + return jjMoveStringLiteralDfa4_0(active0, 0x5000020L); + case 101: + if ((active0 & 0x8000L) != 0L) + { + jjmatchedKind = 15; + jjmatchedPos = 3; + } + else if ((active0 & 0x200000000L) != 0L) + return jjStartNfaWithStates_0(3, 33, 2); + else if ((active0 & 0x4000000000L) != 0L) + return jjStartNfaWithStates_0(3, 38, 2); + return jjMoveStringLiteralDfa4_0(active0, 0x24400000a980180L); + case 104: + if ((active0 & 0x400L) != 0L) + return jjStartNfaWithStates_0(3, 10, 2); + return jjMoveStringLiteralDfa4_0(active0, 0x10000000000000L); + case 107: + return jjMoveStringLiteralDfa4_0(active0, 0x2000000000L); + case 108: + return jjMoveStringLiteralDfa4_0(active0, 0x100800000002000L); + case 109: + return jjMoveStringLiteralDfa4_0(active0, 0x10000000000L); + case 110: + if ((active0 & 0x10000000L) != 0L) + return jjStartNfaWithStates_0(3, 28, 2); + else if ((active0 & 0x80000000000L) != 0L) + return jjStartNfaWithStates_0(3, 43, 2); + return jjMoveStringLiteralDfa4_0(active0, 0x108000000000L); + case 111: + return jjMoveStringLiteralDfa4_0(active0, 0x800001000004010L); + case 112: + if ((active0 & 0x400000000000000L) != 0L) + return jjStartNfaWithStates_0(3, 58, 2); + return jjMoveStringLiteralDfa4_0(active0, 0x100000000L); + case 114: + return jjMoveStringLiteralDfa4_0(active0, 0x20000L); + case 115: + return jjMoveStringLiteralDfa4_0(active0, 0x21000400000040L); + case 116: + return jjMoveStringLiteralDfa4_0(active0, 0x8400000000000L); + case 117: + return jjMoveStringLiteralDfa4_0(active0, 0x80000000040000L); + case 119: + if ((active0 & 0x10000L) != 0L) + return jjStartNfaWithStates_0(3, 16, 2); + break; + default : + break; + } + return jjStartNfa_0(2, active0, 0L); +} +private int jjMoveStringLiteralDfa4_0(long old0, long active0) +{ + if (((active0 &= old0)) == 0L) + return jjStartNfa_0(2, old0, 0L); + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { + jjStopStringLiteralDfa_0(3, active0, 0L); + return 4; + } + switch(curChar) + { + case 97: + return jjMoveStringLiteralDfa5_0(active0, 0x2000822000L); + case 99: + return jjMoveStringLiteralDfa5_0(active0, 0x100L); + case 101: + if ((active0 & 0x40L) != 0L) + return jjStartNfaWithStates_0(4, 6, 2); + else if ((active0 & 0x800000000000L) != 0L) + return jjStartNfaWithStates_0(4, 47, 2); + return jjMoveStringLiteralDfa5_0(active0, 0x8118000000000L); + case 105: + return jjMoveStringLiteralDfa5_0(active0, 0x110400000100000L); + case 107: + if ((active0 & 0x1000000L) != 0L) + return jjStartNfaWithStates_0(4, 24, 2); + else if ((active0 & 0x20000000L) != 0L) + return jjStartNfaWithStates_0(4, 29, 2); + break; + case 108: + if ((active0 & 0x80L) != 0L) + return jjStartNfaWithStates_0(4, 7, 2); + else if ((active0 & 0x800L) != 0L) + return jjStartNfaWithStates_0(4, 11, 2); + break; + case 109: + return jjMoveStringLiteralDfa5_0(active0, 0x40000000000L); + case 110: + return jjMoveStringLiteralDfa5_0(active0, 0x42000000000000L); + case 112: + return jjMoveStringLiteralDfa5_0(active0, 0x40000000L); + case 114: + if ((active0 & 0x8000000L) != 0L) + return jjStartNfaWithStates_0(4, 27, 2); + else if ((active0 & 0x4000000000000L) != 0L) + return jjStartNfaWithStates_0(4, 50, 2); + return jjMoveStringLiteralDfa5_0(active0, 0xa000010000c0030L); + case 115: + if ((active0 & 0x400000000L) != 0L) + return jjStartNfaWithStates_0(4, 34, 2); + break; + case 116: + if ((active0 & 0x80000000000000L) != 0L) + return jjStartNfaWithStates_0(4, 55, 2); + return jjMoveStringLiteralDfa5_0(active0, 0x21200004004000L); + case 117: + return jjMoveStringLiteralDfa5_0(active0, 0x100000000L); + case 119: + return jjMoveStringLiteralDfa5_0(active0, 0x2000000L); + default : + break; + } + return jjStartNfa_0(3, active0, 0L); +} +private int jjMoveStringLiteralDfa5_0(long old0, long active0) +{ + if (((active0 &= old0)) == 0L) + return jjStartNfa_0(3, old0, 0L); + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { + jjStopStringLiteralDfa_0(4, active0, 0L); + return 5; + } + switch(curChar) + { + case 97: + return jjMoveStringLiteralDfa6_0(active0, 0x1400000004000L); + case 99: + if ((active0 & 0x100000000000000L) != 0L) + return jjStartNfaWithStates_0(5, 56, 2); + return jjMoveStringLiteralDfa6_0(active0, 0x8108000002000L); + case 100: + if ((active0 & 0x800000000000000L) != 0L) + return jjStartNfaWithStates_0(5, 59, 2); + return jjMoveStringLiteralDfa6_0(active0, 0x42000000000000L); + case 101: + return jjMoveStringLiteralDfa6_0(active0, 0x40000000020L); + case 102: + if ((active0 & 0x100000L) != 0L) + return jjStartNfaWithStates_0(5, 20, 2); + break; + case 103: + return jjMoveStringLiteralDfa6_0(active0, 0x2000000000L); + case 104: + return jjMoveStringLiteralDfa6_0(active0, 0x2000000L); + case 105: + return jjMoveStringLiteralDfa6_0(active0, 0x200004000010L); + case 108: + return jjMoveStringLiteralDfa6_0(active0, 0x100L); + case 109: + if ((active0 & 0x800000L) != 0L) + return jjStartNfaWithStates_0(5, 23, 2); + break; + case 110: + if ((active0 & 0x40000L) != 0L) + return jjStartNfaWithStates_0(5, 18, 2); + else if ((active0 & 0x10000000000000L) != 0L) + return jjStartNfaWithStates_0(5, 52, 2); + return jjMoveStringLiteralDfa6_0(active0, 0x200000000000000L); + case 114: + return jjMoveStringLiteralDfa6_0(active0, 0x20010000000000L); + case 115: + return jjMoveStringLiteralDfa6_0(active0, 0x40000000L); + case 116: + if ((active0 & 0x80000L) != 0L) + return jjStartNfaWithStates_0(5, 19, 2); + else if ((active0 & 0x100000000L) != 0L) + return jjStartNfaWithStates_0(5, 32, 2); + else if ((active0 & 0x1000000000L) != 0L) + return jjStartNfaWithStates_0(5, 36, 2); + return jjMoveStringLiteralDfa6_0(active0, 0x20000L); + default : + break; + } + return jjStartNfa_0(4, active0, 0L); +} +private int jjMoveStringLiteralDfa6_0(long old0, long active0) +{ + if (((active0 &= old0)) == 0L) + return jjStartNfa_0(4, old0, 0L); + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { + jjStopStringLiteralDfa_0(5, active0, 0L); + return 6; + } + switch(curChar) + { + case 97: + return jjMoveStringLiteralDfa7_0(active0, 0x222010000000100L); + case 101: + if ((active0 & 0x2000000000L) != 0L) + return jjStartNfaWithStates_0(6, 37, 2); + return jjMoveStringLiteralDfa7_0(active0, 0x2002000L); + case 108: + if ((active0 & 0x400000000000L) != 0L) + return jjStartNfaWithStates_0(6, 46, 2); + break; + case 110: + return jjMoveStringLiteralDfa7_0(active0, 0x1000000000000L); + case 111: + return jjMoveStringLiteralDfa7_0(active0, 0x200004020000L); + case 115: + if ((active0 & 0x40000000000000L) != 0L) + return jjStartNfaWithStates_0(6, 54, 2); + break; + case 116: + if ((active0 & 0x8000000000L) != 0L) + { + jjmatchedKind = 39; + jjmatchedPos = 6; + } + return jjMoveStringLiteralDfa7_0(active0, 0x8140000004030L); + case 117: + return jjMoveStringLiteralDfa7_0(active0, 0x40000000L); + default : + break; + } + return jjStartNfa_0(5, active0, 0L); +} +private int jjMoveStringLiteralDfa7_0(long old0, long active0) +{ + if (((active0 &= old0)) == 0L) + return jjStartNfa_0(5, old0, 0L); + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { + jjStopStringLiteralDfa_0(6, active0, 0L); + return 7; + } + switch(curChar) + { + case 97: + return jjMoveStringLiteralDfa8_0(active0, 0x2000L); + case 98: + return jjMoveStringLiteralDfa8_0(active0, 0x2000000000000L); + case 101: + if ((active0 & 0x20L) != 0L) + return jjStartNfaWithStates_0(7, 5, 2); + return jjMoveStringLiteralDfa8_0(active0, 0x8040000000000L); + case 104: + return jjMoveStringLiteralDfa8_0(active0, 0x10L); + case 105: + return jjMoveStringLiteralDfa8_0(active0, 0x20000000004000L); + case 108: + if ((active0 & 0x200000000000000L) != 0L) + return jjStartNfaWithStates_0(7, 57, 2); + return jjMoveStringLiteralDfa8_0(active0, 0x40000000L); + case 110: + if ((active0 & 0x2000000L) != 0L) + return jjStartNfaWithStates_0(7, 25, 2); + else if ((active0 & 0x4000000L) != 0L) + return jjStartNfaWithStates_0(7, 26, 2); + else if ((active0 & 0x200000000000L) != 0L) + return jjStartNfaWithStates_0(7, 45, 2); + break; + case 111: + return jjMoveStringLiteralDfa8_0(active0, 0x100000000000L); + case 114: + if ((active0 & 0x20000L) != 0L) + return jjStartNfaWithStates_0(7, 17, 2); + return jjMoveStringLiteralDfa8_0(active0, 0x100L); + case 116: + if ((active0 & 0x1000000000000L) != 0L) + return jjStartNfaWithStates_0(7, 48, 2); + return jjMoveStringLiteralDfa8_0(active0, 0x10000000000L); + default : + break; + } + return jjStartNfa_0(6, active0, 0L); +} +private int jjMoveStringLiteralDfa8_0(long old0, long active0) +{ + if (((active0 &= old0)) == 0L) + return jjStartNfa_0(6, old0, 0L); + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { + jjStopStringLiteralDfa_0(7, active0, 0L); + return 8; + } + switch(curChar) + { + case 97: + return jjMoveStringLiteralDfa9_0(active0, 0x40000000L); + case 98: + return jjMoveStringLiteralDfa9_0(active0, 0x2000L); + case 100: + if ((active0 & 0x8000000000000L) != 0L) + return jjStartNfaWithStates_0(8, 51, 2); + break; + case 101: + if ((active0 & 0x100L) != 0L) + return jjStartNfaWithStates_0(8, 8, 2); + break; + case 105: + return jjMoveStringLiteralDfa9_0(active0, 0x10000000000L); + case 108: + return jjMoveStringLiteralDfa9_0(active0, 0x2000000000000L); + case 109: + if ((active0 & 0x10L) != 0L) + return jjStartNfaWithStates_0(8, 4, 2); + break; + case 110: + return jjMoveStringLiteralDfa9_0(active0, 0x20000000000000L); + case 111: + return jjMoveStringLiteralDfa9_0(active0, 0x4000L); + case 114: + if ((active0 & 0x40000000000L) != 0L) + return jjStartNfaWithStates_0(8, 42, 2); + else if ((active0 & 0x100000000000L) != 0L) + return jjStartNfaWithStates_0(8, 44, 2); + break; + default : + break; + } + return jjStartNfa_0(7, active0, 0L); +} +private int jjMoveStringLiteralDfa9_0(long old0, long active0) +{ + if (((active0 &= old0)) == 0L) + return jjStartNfa_0(7, old0, 0L); + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { + jjStopStringLiteralDfa_0(8, active0, 0L); + return 9; + } + switch(curChar) + { + case 101: + if ((active0 & 0x2000000000000L) != 0L) + return jjStartNfaWithStates_0(9, 49, 2); + return jjMoveStringLiteralDfa10_0(active0, 0x20000000000000L); + case 108: + return jjMoveStringLiteralDfa10_0(active0, 0x2000L); + case 110: + if ((active0 & 0x4000L) != 0L) + return jjStartNfaWithStates_0(9, 14, 2); + break; + case 111: + return jjMoveStringLiteralDfa10_0(active0, 0x10000000000L); + case 116: + return jjMoveStringLiteralDfa10_0(active0, 0x40000000L); + default : + break; + } + return jjStartNfa_0(8, active0, 0L); +} +private int jjMoveStringLiteralDfa10_0(long old0, long active0) +{ + if (((active0 &= old0)) == 0L) + return jjStartNfa_0(8, old0, 0L); + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { + jjStopStringLiteralDfa_0(9, active0, 0L); + return 10; + } + switch(curChar) + { + case 100: + return jjMoveStringLiteralDfa11_0(active0, 0x20000000000000L); + case 101: + if ((active0 & 0x2000L) != 0L) + return jjStartNfaWithStates_0(10, 13, 2); + return jjMoveStringLiteralDfa11_0(active0, 0x40000000L); + case 110: + if ((active0 & 0x10000000000L) != 0L) + return jjStartNfaWithStates_0(10, 40, 2); + break; + default : + break; + } + return jjStartNfa_0(9, active0, 0L); +} +private int jjMoveStringLiteralDfa11_0(long old0, long active0) +{ + if (((active0 &= old0)) == 0L) + return jjStartNfa_0(9, old0, 0L); + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { + jjStopStringLiteralDfa_0(10, active0, 0L); + return 11; + } + switch(curChar) + { + case 98: + return jjMoveStringLiteralDfa12_0(active0, 0x20000000000000L); + case 100: + if ((active0 & 0x40000000L) != 0L) + return jjStartNfaWithStates_0(11, 30, 2); + break; + default : + break; + } + return jjStartNfa_0(10, active0, 0L); +} +private int jjMoveStringLiteralDfa12_0(long old0, long active0) +{ + if (((active0 &= old0)) == 0L) + return jjStartNfa_0(10, old0, 0L); + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { + jjStopStringLiteralDfa_0(11, active0, 0L); + return 12; + } + switch(curChar) + { + case 121: + if ((active0 & 0x20000000000000L) != 0L) + return jjStartNfaWithStates_0(12, 53, 2); + break; + default : + break; + } + return jjStartNfa_0(11, active0, 0L); +} +private int jjStartNfaWithStates_0(int pos, int kind, int state) +{ + jjmatchedKind = kind; + jjmatchedPos = pos; + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { return pos + 1; } + return jjMoveNfa_0(state, pos + 1); +} +static final long[] jjbitVec0 = { + 0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL +}; +private int jjMoveNfa_0(int startState, int curPos) +{ + int startsAt = 0; + jjnewStateCnt = 37; + int i = 1; + jjstateSet[0] = startState; + int kind = 0x7fffffff; + for (;;) + { + if (++jjround == 0x7fffffff) + ReInitRounds(); + if (curChar < 64) + { + long l = 1L << curChar; + do + { + switch(jjstateSet[--i]) + { + case 0: + if ((0x3ff000000000000L & l) != 0L) + { + if (kind > 91) + kind = 91; + jjCheckNAddStates(0, 4); + } + else if ((0x100002600L & l) != 0L) + { + if (kind > 1) + kind = 1; + } + else if (curChar == 47) + jjAddStates(5, 6); + else if (curChar == 46) + jjCheckNAdd(12); + else if (curChar == 34) + jjCheckNAddStates(7, 9); + else if (curChar == 39) + jjCheckNAddTwoStates(4, 5); + break; + case 17: + if (curChar == 47) + { + if (kind > 3) + kind = 3; + jjCheckNAdd(24); + } + else if (curChar == 42) + jjCheckNAddStates(10, 12); + break; + case 2: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 88) + kind = 88; + jjstateSet[jjnewStateCnt++] = 2; + break; + case 3: + if (curChar == 39) + jjCheckNAddTwoStates(4, 5); + break; + case 4: + if ((0xaffffc8300001100L & l) != 0L) + jjCheckNAddTwoStates(4, 5); + break; + case 5: + if (curChar == 39 && kind > 89) + kind = 89; + break; + case 6: + if (curChar == 34) + jjCheckNAddStates(7, 9); + break; + case 7: + if ((0xfffffffbfffffbffL & l) != 0L) + jjCheckNAddStates(7, 9); + break; + case 9: + if ((0xfffffffffffffbffL & l) != 0L) + jjCheckNAddStates(7, 9); + break; + case 10: + if (curChar == 34 && kind > 90) + kind = 90; + break; + case 11: + if (curChar == 46) + jjCheckNAdd(12); + break; + case 12: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 92) + kind = 92; + jjCheckNAddTwoStates(12, 13); + break; + case 14: + if ((0x280000000000L & l) != 0L) + jjCheckNAdd(15); + break; + case 15: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 92) + kind = 92; + jjCheckNAdd(15); + break; + case 16: + if (curChar == 47) + jjAddStates(5, 6); + break; + case 18: + if ((0xfffffbffffffffffL & l) != 0L) + jjCheckNAddStates(10, 12); + break; + case 19: + if (curChar == 42) + jjstateSet[jjnewStateCnt++] = 20; + break; + case 20: + if ((0xffff7fffffffffffL & l) != 0L) + jjCheckNAddStates(10, 12); + break; + case 21: + if (curChar == 47 && kind > 2) + kind = 2; + break; + case 22: + if (curChar == 42) + jjstateSet[jjnewStateCnt++] = 21; + break; + case 23: + if (curChar != 47) + break; + if (kind > 3) + kind = 3; + jjCheckNAdd(24); + break; + case 24: + if ((0xfffffffffffffbffL & l) == 0L) + break; + if (kind > 3) + kind = 3; + jjCheckNAdd(24); + break; + case 25: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 91) + kind = 91; + jjCheckNAddStates(0, 4); + break; + case 26: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 91) + kind = 91; + jjCheckNAdd(26); + break; + case 27: + if ((0x3ff000000000000L & l) != 0L) + jjCheckNAddTwoStates(27, 28); + break; + case 28: + if (curChar != 46) + break; + if (kind > 92) + kind = 92; + jjCheckNAddTwoStates(29, 30); + break; + case 29: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 92) + kind = 92; + jjCheckNAddTwoStates(29, 30); + break; + case 31: + if ((0x280000000000L & l) != 0L) + jjCheckNAdd(32); + break; + case 32: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 92) + kind = 92; + jjCheckNAdd(32); + break; + case 33: + if ((0x3ff000000000000L & l) != 0L) + jjCheckNAddTwoStates(33, 34); + break; + case 35: + if ((0x280000000000L & l) != 0L) + jjCheckNAdd(36); + break; + case 36: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 92) + kind = 92; + jjCheckNAdd(36); + break; + default : break; + } + } while(i != startsAt); + } + else if (curChar < 128) + { + long l = 1L << (curChar & 077); + do + { + switch(jjstateSet[--i]) + { + case 0: + case 2: + if ((0x7fffffe87fffffeL & l) == 0L) + break; + if (kind > 88) + kind = 88; + jjCheckNAdd(2); + break; + case 4: + if ((0x47fffffed7ffffffL & l) != 0L) + jjAddStates(13, 14); + break; + case 7: + if ((0xffffffffefffffffL & l) != 0L) + jjCheckNAddStates(7, 9); + break; + case 8: + if (curChar == 92) + jjstateSet[jjnewStateCnt++] = 9; + break; + case 9: + jjCheckNAddStates(7, 9); + break; + case 13: + if ((0x2000000020L & l) != 0L) + jjAddStates(15, 16); + break; + case 18: + case 20: + jjCheckNAddStates(10, 12); + break; + case 24: + if (kind > 3) + kind = 3; + jjstateSet[jjnewStateCnt++] = 24; + break; + case 30: + if ((0x2000000020L & l) != 0L) + jjAddStates(17, 18); + break; + case 34: + if ((0x2000000020L & l) != 0L) + jjAddStates(19, 20); + break; + default : break; + } + } while(i != startsAt); + } + else + { + int i2 = (curChar & 0xff) >> 6; + long l2 = 1L << (curChar & 077); + do + { + switch(jjstateSet[--i]) + { + case 7: + case 9: + if ((jjbitVec0[i2] & l2) != 0L) + jjCheckNAddStates(7, 9); + break; + case 18: + case 20: + if ((jjbitVec0[i2] & l2) != 0L) + jjCheckNAddStates(10, 12); + break; + case 24: + if ((jjbitVec0[i2] & l2) == 0L) + break; + if (kind > 3) + kind = 3; + jjstateSet[jjnewStateCnt++] = 24; + break; + default : break; + } + } while(i != startsAt); + } + if (kind != 0x7fffffff) + { + jjmatchedKind = kind; + jjmatchedPos = curPos; + kind = 0x7fffffff; + } + ++curPos; + if ((i = jjnewStateCnt) == (startsAt = 37 - (jjnewStateCnt = startsAt))) + return curPos; + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { return curPos; } + } +} +static final int[] jjnextStates = { + 26, 27, 28, 33, 34, 17, 23, 7, 8, 10, 18, 19, 22, 4, 5, 14, + 15, 31, 32, 35, 36, +}; + +/** Token literal values. */ +public static final String[] jjstrLiteralImages = { +"", null, null, null, "\141\154\147\157\162\151\164\150\155", +"\144\151\163\143\162\145\164\145", "\146\141\154\163\145", "\155\157\144\145\154", +"\162\145\144\145\143\154\141\162\145", "\141\156\144", "\145\141\143\150", "\146\151\156\141\154", "\156\157\164", +"\162\145\160\154\141\143\145\141\142\154\145", "\141\156\156\157\164\141\164\151\157\156", "\145\154\163\145", +"\146\154\157\167", "\157\160\145\162\141\164\157\162", "\162\145\164\165\162\156", +"\141\163\163\145\162\164", "\145\154\163\145\151\146", "\146\157\162", "\157\162", +"\163\164\162\145\141\155", "\142\154\157\143\153", "\145\154\163\145\167\150\145\156", +"\146\165\156\143\164\151\157\156", "\157\165\164\145\162", "\164\150\145\156", "\142\162\145\141\153", +"\145\156\143\141\160\163\165\154\141\164\145\144", "\151\146", "\157\165\164\160\165\164", "\164\162\165\145", +"\143\154\141\163\163", "\145\156\144", "\151\155\160\157\162\164", "\160\141\143\153\141\147\145", +"\164\171\160\145", "\143\157\156\156\145\143\164", +"\145\156\165\155\145\162\141\164\151\157\156", "\151\156", "\160\141\162\141\155\145\164\145\162", "\167\150\145\156", +"\143\157\156\156\145\143\164\157\162", "\145\161\165\141\164\151\157\156", "\160\141\162\164\151\141\154", +"\167\150\151\154\145", "\143\157\156\163\164\141\156\164", +"\145\170\160\141\156\144\141\142\154\145", "\151\156\156\145\162", "\160\162\157\164\145\143\164\145\144", +"\167\151\164\150\151\156", "\143\157\156\163\164\162\141\151\156\145\144\142\171", +"\145\170\164\145\156\144\163", "\151\156\160\165\164", "\160\165\142\154\151\143", +"\145\170\164\145\162\156\141\154", "\154\157\157\160", "\162\145\143\157\162\144", "\50", "\51", "\173", "\175", +"\133", "\135", "\56", "\72", "\73", "\54", "\74", "\74\75", "\76", "\76\75", +"\75\75", "\74\76", "\53", "\55", "\56\53", "\56\55", "\52", "\57", "\56\52", "\56\57", +"\136", "\56\136", "\75", "\72\75", null, null, null, null, null, }; + +/** Lexer state names. */ +public static final String[] lexStateNames = { + "DEFAULT", +}; +static final long[] jjtoToken = { + 0xfffffffffffffff1L, 0x1fffffffL, +}; +static final long[] jjtoSkip = { + 0xeL, 0x0L, +}; +protected SimpleCharStream input_stream; +private final int[] jjrounds = new int[37]; +private final int[] jjstateSet = new int[74]; +private final StringBuilder jjimage = new StringBuilder(); +private StringBuilder image = jjimage; +private int jjimageLen; +private int lengthOfMatch; +protected char curChar; +/** Constructor. */ +public ExpressionParserTokenManager(SimpleCharStream stream){ + if (SimpleCharStream.staticFlag) + throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer."); + input_stream = stream; +} + +/** Constructor. */ +public ExpressionParserTokenManager(SimpleCharStream stream, int lexState){ + this(stream); + SwitchTo(lexState); +} + +/** Reinitialise parser. */ +public void ReInit(SimpleCharStream stream) +{ + jjmatchedPos = jjnewStateCnt = 0; + curLexState = defaultLexState; + input_stream = stream; + ReInitRounds(); +} +private void ReInitRounds() +{ + int i; + jjround = 0x80000001; + for (i = 37; i-- > 0;) + jjrounds[i] = 0x80000000; +} + +/** Reinitialise parser. */ +public void ReInit(SimpleCharStream stream, int lexState) +{ + ReInit(stream); + SwitchTo(lexState); +} + +/** Switch to specified lex state. */ +public void SwitchTo(int lexState) +{ + if (lexState >= 1 || lexState < 0) + throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE); + else + curLexState = lexState; +} + +protected Token jjFillToken() +{ + final Token t; + final String curTokenImage; + final int beginLine; + final int endLine; + final int beginColumn; + final int endColumn; + String im = jjstrLiteralImages[jjmatchedKind]; + curTokenImage = (im == null) ? input_stream.GetImage() : im; + beginLine = input_stream.getBeginLine(); + beginColumn = input_stream.getBeginColumn(); + endLine = input_stream.getEndLine(); + endColumn = input_stream.getEndColumn(); + t = Token.newToken(jjmatchedKind); + t.kind = jjmatchedKind; + t.image = curTokenImage; + + t.beginLine = beginLine; + t.endLine = endLine; + t.beginColumn = beginColumn; + t.endColumn = endColumn; + + return t; +} + +int curLexState = 0; +int defaultLexState = 0; +int jjnewStateCnt; +int jjround; +int jjmatchedPos; +int jjmatchedKind; + +/** Get the next Token. */ +public Token getNextToken() +{ + Token matchedToken; + int curPos = 0; + + EOFLoop : + for (;;) + { + try + { + curChar = input_stream.BeginToken(); + } + catch(java.io.IOException e) + { + jjmatchedKind = 0; + matchedToken = jjFillToken(); + return matchedToken; + } + image = jjimage; + image.setLength(0); + jjimageLen = 0; + + jjmatchedKind = 0x7fffffff; + jjmatchedPos = 0; + curPos = jjMoveStringLiteralDfa0_0(); + if (jjmatchedKind != 0x7fffffff) + { + if (jjmatchedPos + 1 < curPos) + input_stream.backup(curPos - jjmatchedPos - 1); + if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) + { + matchedToken = jjFillToken(); + TokenLexicalActions(matchedToken); + return matchedToken; + } + else + { + continue EOFLoop; + } + } + int error_line = input_stream.getEndLine(); + int error_column = input_stream.getEndColumn(); + String error_after = null; + boolean EOFSeen = false; + try { input_stream.readChar(); input_stream.backup(1); } + catch (java.io.IOException e1) { + EOFSeen = true; + error_after = curPos <= 1 ? "" : input_stream.GetImage(); + if (curChar == '\n' || curChar == '\r') { + error_line++; + error_column = 0; + } + else + error_column++; + } + if (!EOFSeen) { + input_stream.backup(1); + error_after = curPos <= 1 ? "" : input_stream.GetImage(); + } + throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR); + } +} + +void TokenLexicalActions(Token matchedToken) +{ + switch(jjmatchedKind) + { + case 90 : + image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); + matchedToken.image = matchedToken.image.substring(1,matchedToken.image.length()-1); + break; + default : + break; + } +} +private void jjCheckNAdd(int state) +{ + if (jjrounds[state] != jjround) + { + jjstateSet[jjnewStateCnt++] = state; + jjrounds[state] = jjround; + } +} +private void jjAddStates(int start, int end) +{ + do { + jjstateSet[jjnewStateCnt++] = jjnextStates[start]; + } while (start++ != end); +} +private void jjCheckNAddTwoStates(int state1, int state2) +{ + jjCheckNAdd(state1); + jjCheckNAdd(state2); +} + +private void jjCheckNAddStates(int start, int end) +{ + do { + jjCheckNAdd(jjnextStates[start]); + } while (start++ != end); +} + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ParseException.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ParseException.java new file mode 100644 index 00000000..c5c3b5f2 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ParseException.java @@ -0,0 +1,196 @@ +/******************************************************************************* + * Copyright (c) 2007, 2010 Association for Decentralized Information Management + * in Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.expressionParser; + +/** + * This exception is thrown when parse errors are encountered. + * You can explicitly create objects of this exception type by + * calling the method generateParseException in the generated + * parser. + * + * You can modify this class to customize your error reporting + * mechanisms so long as you retain the public fields. + */ +public class ParseException extends Exception { + + /** + * The version identifier for this Serializable class. + * Increment only if the serialized form of the + * class changes. + */ + private static final long serialVersionUID = 1L; + + /** + * This constructor is used by the method "generateParseException" + * in the generated parser. Calling this constructor generates + * a new object of this type with the fields "currentToken", + * "expectedTokenSequences", and "tokenImage" set. + */ + public ParseException(Token currentTokenVal, + int[][] expectedTokenSequencesVal, + String[] tokenImageVal + ) + { + super(initialise(currentTokenVal, expectedTokenSequencesVal, tokenImageVal)); + currentToken = currentTokenVal; + expectedTokenSequences = expectedTokenSequencesVal; + tokenImage = tokenImageVal; + } + + /** + * The following constructors are for use by you for whatever + * purpose you can think of. Constructing the exception in this + * manner makes the exception behave in the normal way - i.e., as + * documented in the class "Throwable". The fields "errorToken", + * "expectedTokenSequences", and "tokenImage" do not contain + * relevant information. The JavaCC generated code does not use + * these constructors. + */ + + public ParseException() { + super(); + } + + /** Constructor with message. */ + public ParseException(String message) { + super(message); + } + + + /** + * This is the last token that has been consumed successfully. If + * this object has been created due to a parse error, the token + * followng this token will (therefore) be the first error token. + */ + public Token currentToken; + + /** + * Each entry in this array is an array of integers. Each array + * of integers represents a sequence of tokens (by their ordinal + * values) that is expected at this point of the parse. + */ + public int[][] expectedTokenSequences; + + /** + * This is a reference to the "tokenImage" array of the generated + * parser within which the parse error occurred. This array is + * defined in the generated ...Constants interface. + */ + public String[] tokenImage; + + /** + * It uses "currentToken" and "expectedTokenSequences" to generate a parse + * error message and returns it. If this object has been created + * due to a parse error, and you do not catch it (it gets thrown + * from the parser) the correct error message + * gets displayed. + */ + private static String initialise(Token currentToken, + int[][] expectedTokenSequences, + String[] tokenImage) { + String eol = System.getProperty("line.separator", "\n"); + StringBuffer expected = new StringBuffer(); + int maxSize = 0; + for (int i = 0; i < expectedTokenSequences.length; i++) { + if (maxSize < expectedTokenSequences[i].length) { + maxSize = expectedTokenSequences[i].length; + } + for (int j = 0; j < expectedTokenSequences[i].length; j++) { + expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' '); + } + if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { + expected.append("..."); + } + expected.append(eol).append(" "); + } + String retval = "Encountered \""; + Token tok = currentToken.next; + for (int i = 0; i < maxSize; i++) { + if (i != 0) retval += " "; + if (tok.kind == 0) { + retval += tokenImage[0]; + break; + } + retval += " " + tokenImage[tok.kind]; + retval += " \""; + retval += add_escapes(tok.image); + retval += " \""; + tok = tok.next; + } + retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; + retval += "." + eol; + if (expectedTokenSequences.length == 1) { + retval += "Was expecting:" + eol + " "; + } else { + retval += "Was expecting one of:" + eol + " "; + } + retval += expected.toString(); + return retval; + } + + /** + * The end of line string for this machine. + */ + protected String eol = System.getProperty("line.separator", "\n"); + + /** + * Used to convert raw characters to their escaped version + * when these raw version cannot be used as part of an ASCII + * string literal. + */ + static String add_escapes(String str) { + StringBuffer retval = new StringBuffer(); + char ch; + for (int i = 0; i < str.length(); i++) { + switch (str.charAt(i)) + { + case 0 : + continue; + case '\b': + retval.append("\\b"); + continue; + case '\t': + retval.append("\\t"); + continue; + case '\n': + retval.append("\\n"); + continue; + case '\f': + retval.append("\\f"); + continue; + case '\r': + retval.append("\\r"); + continue; + case '\"': + retval.append("\\\""); + continue; + case '\'': + retval.append("\\\'"); + continue; + case '\\': + retval.append("\\\\"); + continue; + default: + if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { + String s = "0000" + Integer.toString(ch, 16); + retval.append("\\u" + s.substring(s.length() - 4, s.length())); + } else { + retval.append(ch); + } + continue; + } + } + return retval.toString(); + } + +} +/* JavaCC - OriginalChecksum=65dcbd31a9e7a053287ebf70e24f8b8f (do not edit this line) */ diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/SimpleCharStream.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/SimpleCharStream.java new file mode 100644 index 00000000..ae8e144a --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/SimpleCharStream.java @@ -0,0 +1,480 @@ +/******************************************************************************* + * Copyright (c) 2007, 2010 Association for Decentralized Information Management + * in Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.expressionParser; + +/** + * An implementation of interface CharStream, where the stream is assumed to + * contain only ASCII characters (without unicode processing). + */ + +public class SimpleCharStream +{ +/** Whether parser is static. */ + public static final boolean staticFlag = false; + int bufsize; + int available; + int tokenBegin; +/** Position in buffer. */ + public int bufpos = -1; + protected int bufline[]; + protected int bufcolumn[]; + + protected int column = 0; + protected int line = 1; + + protected boolean prevCharIsCR = false; + protected boolean prevCharIsLF = false; + + protected java.io.Reader inputStream; + + protected char[] buffer; + protected int maxNextCharInd = 0; + protected int inBuf = 0; + protected int tabSize = 8; + + protected void setTabSize(int i) { tabSize = i; } + protected int getTabSize(int i) { return tabSize; } + + + protected void ExpandBuff(boolean wrapAround) + { + char[] newbuffer = new char[bufsize + 2048]; + int newbufline[] = new int[bufsize + 2048]; + int newbufcolumn[] = new int[bufsize + 2048]; + + try + { + if (wrapAround) + { + System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); + System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); + buffer = newbuffer; + + System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); + System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); + bufline = newbufline; + + System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); + System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); + bufcolumn = newbufcolumn; + + maxNextCharInd = (bufpos += (bufsize - tokenBegin)); + } + else + { + System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); + buffer = newbuffer; + + System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); + bufline = newbufline; + + System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); + bufcolumn = newbufcolumn; + + maxNextCharInd = (bufpos -= tokenBegin); + } + } + catch (Throwable t) + { + throw new Error(t.getMessage()); + } + + + bufsize += 2048; + available = bufsize; + tokenBegin = 0; + } + + protected void FillBuff() throws java.io.IOException + { + if (maxNextCharInd == available) + { + if (available == bufsize) + { + if (tokenBegin > 2048) + { + bufpos = maxNextCharInd = 0; + available = tokenBegin; + } + else if (tokenBegin < 0) + bufpos = maxNextCharInd = 0; + else + ExpandBuff(false); + } + else if (available > tokenBegin) + available = bufsize; + else if ((tokenBegin - available) < 2048) + ExpandBuff(true); + else + available = tokenBegin; + } + + int i; + try { + if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) + { + inputStream.close(); + throw new java.io.IOException(); + } + else + maxNextCharInd += i; + return; + } + catch(java.io.IOException e) { + --bufpos; + backup(0); + if (tokenBegin == -1) + tokenBegin = bufpos; + throw e; + } + } + +/** Start. */ + public char BeginToken() throws java.io.IOException + { + tokenBegin = -1; + char c = readChar(); + tokenBegin = bufpos; + + return c; + } + + protected void UpdateLineColumn(char c) + { + column++; + + if (prevCharIsLF) + { + prevCharIsLF = false; + line += (column = 1); + } + else if (prevCharIsCR) + { + prevCharIsCR = false; + if (c == '\n') + { + prevCharIsLF = true; + } + else + line += (column = 1); + } + + switch (c) + { + case '\r' : + prevCharIsCR = true; + break; + case '\n' : + prevCharIsLF = true; + break; + case '\t' : + column--; + column += (tabSize - (column % tabSize)); + break; + default : + break; + } + + bufline[bufpos] = line; + bufcolumn[bufpos] = column; + } + +/** Read a character. */ + public char readChar() throws java.io.IOException + { + if (inBuf > 0) + { + --inBuf; + + if (++bufpos == bufsize) + bufpos = 0; + + return buffer[bufpos]; + } + + if (++bufpos >= maxNextCharInd) + FillBuff(); + + char c = buffer[bufpos]; + + UpdateLineColumn(c); + return c; + } + + @Deprecated + /** + * @deprecated + * @see #getEndColumn + */ + + public int getColumn() { + return bufcolumn[bufpos]; + } + + @Deprecated + /** + * @deprecated + * @see #getEndLine + */ + + public int getLine() { + return bufline[bufpos]; + } + + /** Get token end column number. */ + public int getEndColumn() { + return bufcolumn[bufpos]; + } + + /** Get token end line number. */ + public int getEndLine() { + return bufline[bufpos]; + } + + /** Get token beginning column number. */ + public int getBeginColumn() { + return bufcolumn[tokenBegin]; + } + + /** Get token beginning line number. */ + public int getBeginLine() { + return bufline[tokenBegin]; + } + +/** Backup a number of characters. */ + public void backup(int amount) { + + inBuf += amount; + if ((bufpos -= amount) < 0) + bufpos += bufsize; + } + + /** Constructor. */ + public SimpleCharStream(java.io.Reader dstream, int startline, + int startcolumn, int buffersize) + { + inputStream = dstream; + line = startline; + column = startcolumn - 1; + + available = bufsize = buffersize; + buffer = new char[buffersize]; + bufline = new int[buffersize]; + bufcolumn = new int[buffersize]; + } + + /** Constructor. */ + public SimpleCharStream(java.io.Reader dstream, int startline, + int startcolumn) + { + this(dstream, startline, startcolumn, 4096); + } + + /** Constructor. */ + public SimpleCharStream(java.io.Reader dstream) + { + this(dstream, 1, 1, 4096); + } + + /** Reinitialise. */ + public void ReInit(java.io.Reader dstream, int startline, + int startcolumn, int buffersize) + { + inputStream = dstream; + line = startline; + column = startcolumn - 1; + + if (buffer == null || buffersize != buffer.length) + { + available = bufsize = buffersize; + buffer = new char[buffersize]; + bufline = new int[buffersize]; + bufcolumn = new int[buffersize]; + } + prevCharIsLF = prevCharIsCR = false; + tokenBegin = inBuf = maxNextCharInd = 0; + bufpos = -1; + } + + /** Reinitialise. */ + public void ReInit(java.io.Reader dstream, int startline, + int startcolumn) + { + ReInit(dstream, startline, startcolumn, 4096); + } + + /** Reinitialise. */ + public void ReInit(java.io.Reader dstream) + { + ReInit(dstream, 1, 1, 4096); + } + /** Constructor. */ + public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, + int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException + { + this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); + } + + /** Constructor. */ + public SimpleCharStream(java.io.InputStream dstream, int startline, + int startcolumn, int buffersize) + { + this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); + } + + /** Constructor. */ + public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, + int startcolumn) throws java.io.UnsupportedEncodingException + { + this(dstream, encoding, startline, startcolumn, 4096); + } + + /** Constructor. */ + public SimpleCharStream(java.io.InputStream dstream, int startline, + int startcolumn) + { + this(dstream, startline, startcolumn, 4096); + } + + /** Constructor. */ + public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException + { + this(dstream, encoding, 1, 1, 4096); + } + + /** Constructor. */ + public SimpleCharStream(java.io.InputStream dstream) + { + this(dstream, 1, 1, 4096); + } + + /** Reinitialise. */ + public void ReInit(java.io.InputStream dstream, String encoding, int startline, + int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException + { + ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); + } + + /** Reinitialise. */ + public void ReInit(java.io.InputStream dstream, int startline, + int startcolumn, int buffersize) + { + ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); + } + + /** Reinitialise. */ + public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException + { + ReInit(dstream, encoding, 1, 1, 4096); + } + + /** Reinitialise. */ + public void ReInit(java.io.InputStream dstream) + { + ReInit(dstream, 1, 1, 4096); + } + /** Reinitialise. */ + public void ReInit(java.io.InputStream dstream, String encoding, int startline, + int startcolumn) throws java.io.UnsupportedEncodingException + { + ReInit(dstream, encoding, startline, startcolumn, 4096); + } + /** Reinitialise. */ + public void ReInit(java.io.InputStream dstream, int startline, + int startcolumn) + { + ReInit(dstream, startline, startcolumn, 4096); + } + /** Get token literal value. */ + public String GetImage() + { + if (bufpos >= tokenBegin) + return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); + else + return new String(buffer, tokenBegin, bufsize - tokenBegin) + + new String(buffer, 0, bufpos + 1); + } + + /** Get the suffix. */ + public char[] GetSuffix(int len) + { + char[] ret = new char[len]; + + if ((bufpos + 1) >= len) + System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); + else + { + System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, + len - bufpos - 1); + System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); + } + + return ret; + } + + /** Reset buffer when finished. */ + public void Done() + { + buffer = null; + bufline = null; + bufcolumn = null; + } + + /** + * Method to adjust line and column numbers for the start of a token. + */ + public void adjustBeginLineColumn(int newLine, int newCol) + { + int start = tokenBegin; + int len; + + if (bufpos >= tokenBegin) + { + len = bufpos - tokenBegin + inBuf + 1; + } + else + { + len = bufsize - tokenBegin + bufpos + 1 + inBuf; + } + + int i = 0, j = 0, k = 0; + int nextColDiff = 0, columnDiff = 0; + + while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) + { + bufline[j] = newLine; + nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; + bufcolumn[j] = newCol + columnDiff; + columnDiff = nextColDiff; + i++; + } + + if (i < len) + { + bufline[j] = newLine++; + bufcolumn[j] = newCol + columnDiff; + + while (i++ < len) + { + if (bufline[j = start % bufsize] != bufline[++start % bufsize]) + bufline[j] = newLine++; + else + bufline[j] = newLine; + } + } + + line = bufline[j]; + column = bufcolumn[j]; + } + +} +/* JavaCC - OriginalChecksum=c766a5138ab7879b8b98d46681a242b8 (do not edit this line) */ diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/TestExpressionParser.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/TestExpressionParser.java new file mode 100644 index 00000000..35225c26 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/TestExpressionParser.java @@ -0,0 +1,47 @@ +/******************************************************************************* + * Copyright (c) 2007, 2010 Association for Decentralized Information Management + * in Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.expressionParser; + +import java.io.StringReader; +import java.util.HashMap; +import java.util.List; + +public class TestExpressionParser { + + static private ExpressionParser parser; + + public static void parse(String string) { + parser.ReInit(new StringReader(string)); + try { + parser.expr(); + HashMap> references = parser.getReferences(); + for(String ref : references.keySet()) { + System.out.println(ref); + } + } catch (ParseException e) { + System.out.println("While parsing " + string + ":"); + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public static void main(String[] args) { + parser = new ExpressionParser( + new StringReader("") + ); + parse("1 + m2ma"); + System.out.println("##"); + parse("ter2e + moro"); + System.out.println("##"); + parse("moro * sqr(4.0) + min(m2ma, moi)"); + } +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/Token.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/Token.java new file mode 100644 index 00000000..9cce5690 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/Token.java @@ -0,0 +1,155 @@ +/******************************************************************************* + * Copyright (c) 2007, 2010 Association for Decentralized Information Management + * in Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.expressionParser; + +/** + * Describes the input token stream. + */ + +public class Token implements java.io.Serializable, Comparable { + + /** + * The version identifier for this Serializable class. + * Increment only if the serialized form of the + * class changes. + */ + private static final long serialVersionUID = 1L; + + /** + * An integer that describes the kind of this token. This numbering + * system is determined by JavaCCParser, and a table of these numbers is + * stored in the file ...Constants.java. + */ + public int kind; + + /** The line number of the first character of this Token. */ + public int beginLine; + /** The column number of the first character of this Token. */ + public int beginColumn; + /** The line number of the last character of this Token. */ + public int endLine; + /** The column number of the last character of this Token. */ + public int endColumn; + + /** + * The string image of the token. + */ + public String image; + + /** + * A reference to the next regular (non-special) token from the input + * stream. If this is the last token from the input stream, or if the + * token manager has not read tokens beyond this one, this field is + * set to null. This is true only if this token is also a regular + * token. Otherwise, see below for a description of the contents of + * this field. + */ + public Token next; + + /** + * This field is used to access special tokens that occur prior to this + * token, but after the immediately preceding regular (non-special) token. + * If there are no such special tokens, this field is set to null. + * When there are more than one such special token, this field refers + * to the last of these special tokens, which in turn refers to the next + * previous special token through its specialToken field, and so on + * until the first special token (whose specialToken field is null). + * The next fields of special tokens refer to other special tokens that + * immediately follow it (without an intervening regular token). If there + * is no such token, this field is null. + */ + public Token specialToken; + + /** + * An optional attribute value of the Token. + * Tokens which are not used as syntactic sugar will often contain + * meaningful values that will be used later on by the compiler or + * interpreter. This attribute value is often different from the image. + * Any subclass of Token that actually wants to return a non-null value can + * override this method as appropriate. + */ + public Object getValue() { + return null; + } + + /** + * No-argument constructor + */ + public Token() {} + + /** + * Constructs a new token for the specified Image. + */ + public Token(int kind) + { + this(kind, null); + } + + /** + * Constructs a new token for the specified Image and Kind. + */ + public Token(int kind, String image) + { + this.kind = kind; + this.image = image; + } + + /** + * Returns the image. + */ + public String toString() + { + return image; + } + + /** + * Returns a new Token object, by default. However, if you want, you + * can create and return subclass objects based on the value of ofKind. + * Simply add the cases to the switch for all those special cases. + * For example, if you have a subclass of Token called IDToken that + * you want to create if ofKind is ID, simply add something like : + * + * case MyParserConstants.ID : return new IDToken(ofKind, image); + * + * to the following switch statement. Then you can cast matchedToken + * variable to the appropriate type and use sit in your lexical actions. + */ + public static Token newToken(int ofKind, String image) + { + switch(ofKind) + { + default : return new Token(ofKind, image); + } + } + + public static Token newToken(int ofKind) + { + return newToken(ofKind, null); + } + + @Override + public int compareTo(Token o) { + if (this.beginLine < o.beginLine) + return -1; + if (this.beginLine > o.beginLine) + return 1; + else { + if (this.beginColumn < o.beginColumn) + return -1; + if (this.beginColumn > o.beginColumn) + return 1; + return 0; + } + } + +} +/* JavaCC - OriginalChecksum=ed7a6d865f7fbc2c64e008e34bd824b0 (do not edit this line) */ diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/TokenMgrError.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/TokenMgrError.java new file mode 100644 index 00000000..db380412 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/TokenMgrError.java @@ -0,0 +1,156 @@ +/******************************************************************************* + * Copyright (c) 2007, 2010 Association for Decentralized Information Management + * in Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.expressionParser; + +/** Token Manager Error. */ +public class TokenMgrError extends Error +{ + + /** + * The version identifier for this Serializable class. + * Increment only if the serialized form of the + * class changes. + */ + private static final long serialVersionUID = 1L; + + /* + * Ordinals for various reasons why an Error of this type can be thrown. + */ + + /** + * Lexical error occurred. + */ + static final int LEXICAL_ERROR = 0; + + /** + * An attempt was made to create a second instance of a static token manager. + */ + static final int STATIC_LEXER_ERROR = 1; + + /** + * Tried to change to an invalid lexical state. + */ + static final int INVALID_LEXICAL_STATE = 2; + + /** + * Detected (and bailed out of) an infinite loop in the token manager. + */ + static final int LOOP_DETECTED = 3; + + /** + * Indicates the reason why the exception is thrown. It will have + * one of the above 4 values. + */ + int errorCode; + + /** + * Replaces unprintable characters by their escaped (or unicode escaped) + * equivalents in the given string + */ + protected static final String addEscapes(String str) { + StringBuffer retval = new StringBuffer(); + char ch; + for (int i = 0; i < str.length(); i++) { + switch (str.charAt(i)) + { + case 0 : + continue; + case '\b': + retval.append("\\b"); + continue; + case '\t': + retval.append("\\t"); + continue; + case '\n': + retval.append("\\n"); + continue; + case '\f': + retval.append("\\f"); + continue; + case '\r': + retval.append("\\r"); + continue; + case '\"': + retval.append("\\\""); + continue; + case '\'': + retval.append("\\\'"); + continue; + case '\\': + retval.append("\\\\"); + continue; + default: + if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { + String s = "0000" + Integer.toString(ch, 16); + retval.append("\\u" + s.substring(s.length() - 4, s.length())); + } else { + retval.append(ch); + } + continue; + } + } + return retval.toString(); + } + + /** + * Returns a detailed message for the Error when it is thrown by the + * token manager to indicate a lexical error. + * Parameters : + * EOFSeen : indicates if EOF caused the lexical error + * curLexState : lexical state in which this error occurred + * errorLine : line number when the error occurred + * errorColumn : column number when the error occurred + * errorAfter : prefix that was seen before this error occurred + * curchar : the offending character + * Note: You can customize the lexical error message by modifying this method. + */ + protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) { + return("Lexical error at line " + + errorLine + ", column " + + errorColumn + ". Encountered: " + + (EOFSeen ? " " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") + + "after : \"" + addEscapes(errorAfter) + "\""); + } + + /** + * You can also modify the body of this method to customize your error messages. + * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not + * of end-users concern, so you can return something like : + * + * "Internal Error : Please file a bug report .... " + * + * from this method for such cases in the release version of your parser. + */ + public String getMessage() { + return super.getMessage(); + } + + /* + * Constructors of various flavors follow. + */ + + /** No arg constructor. */ + public TokenMgrError() { + } + + /** Constructor with message and reason. */ + public TokenMgrError(String message, int reason) { + super(message); + errorCode = reason; + } + + /** Full Constructor. */ + public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) { + this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason); + } +} +/* JavaCC - OriginalChecksum=24b6b4792f62099f85bde9ed73a49451 (do not edit this line) */ diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/ActiveResults.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/ActiveResults.java new file mode 100644 index 00000000..6ae1b035 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/ActiveResults.java @@ -0,0 +1,71 @@ +/******************************************************************************* + * Copyright (c) 2013 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Semantum Oy - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.manager; + +import java.util.ArrayList; +import java.util.Collection; + +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.common.request.ObjectsWithType; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.request.Read; +import org.simantics.layer0.Layer0; +import org.simantics.modeling.ModelingResources; +import org.simantics.sysdyn.SysdynResource; + +public class ActiveResults implements Read>{ + + private Resource resource; + + public ActiveResults(Resource resource) { + this.resource = resource; + } + + @Override + public Collection perform(ReadGraph graph) throws DatabaseException { + Layer0 L0 = Layer0.getInstance(graph); + SysdynResource SR = SysdynResource.getInstance(graph); + ModelingResources MR = ModelingResources.getInstance(graph); + + Collection result = new ArrayList(); + + Collection experiments; + if(graph.isInstanceOf(resource, MR.StructuralModel)) + experiments = graph.syncRequest(new ObjectsWithType(resource, L0.ConsistsOf, SR.Experiment)); + else { + experiments = new ArrayList(); + experiments.add(resource); + } + + for(Resource experiment : experiments) { + Collection experimentResults = graph.getObjects(experiment, SR.Experiment_result); + for(Resource r : experimentResults) { + if(graph.hasStatement(r, SR.Result_showResult)) { + result.add(r); + } + } + Collection experimentResultSets = graph.getObjects(experiment, SR.Experiment_resultSet); + for(Resource resultSet : experimentResultSets) { + experimentResults = graph.getObjects(resultSet, SR.Experiment_result); + for(Resource r : experimentResults) { + if(graph.hasStatement(r, SR.Result_showResult)) { + result.add(r); + } + } + } + } + + return result; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/FileResult.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/FileResult.java new file mode 100644 index 00000000..e685e8d4 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/FileResult.java @@ -0,0 +1,116 @@ +/******************************************************************************* + * Copyright (c) 2013 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Semantum Oy - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.manager; + +import java.io.File; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.simantics.databoard.Accessors; +import org.simantics.databoard.Bindings; +import org.simantics.databoard.accessor.Accessor; +import org.simantics.databoard.accessor.MapAccessor; +import org.simantics.databoard.accessor.RecordAccessor; +import org.simantics.databoard.accessor.binary.BinaryRecord; +import org.simantics.databoard.accessor.binary.BinaryVariant; +import org.simantics.databoard.accessor.error.AccessorConstructionException; +import org.simantics.databoard.accessor.error.AccessorException; +import org.simantics.databoard.accessor.reference.ChildReference; +import org.simantics.databoard.accessor.reference.ComponentReference; +import org.simantics.databoard.accessor.reference.IndexReference; +import org.simantics.databoard.accessor.reference.KeyReference; +import org.simantics.databoard.accessor.reference.NameReference; +import org.simantics.databoard.binding.mutable.Variant; + +public class FileResult extends SysdynResult { + + private RecordAccessor accessor; + + /** + * Open result from a file + * + * @param result Name of the result (seen in visualization) + * @param path file path + */ + public FileResult(String resultName, String path) { + super(resultName); + File file = new File(path); + try { + BinaryVariant bv = (BinaryVariant)Accessors.openAccessor(file); + BinaryRecord br = bv.getContentAccessor(); + accessor = br; + } catch (AccessorConstructionException e) { + e.printStackTrace(); + } + } + + /** + * Get the {@link RecordAccessor} of this result + * @return {@link RecordAccessor} for this result + */ + public Accessor getAccessor() { + return accessor; + } + + + /** + * Get dataset for a named variable from accessor + * @param variable The name of the variable + * @return {@link SysdynDataSet} + */ + @Override + public SysdynDataSet getDataSet(String variable) { + if(accessor != null) { + synchronized(accessor) { + ChildReference ref = ChildReference.compile( + new NameReference("recordings"), + new KeyReference( Bindings.VARIANT, Variant.ofInstance(variable) ), + new ComponentReference(), + new NameReference("segments"), + new IndexReference(0) + ); + MapAccessor ma; + try { + ma = accessor.getComponent( ref ); + } catch (AccessorConstructionException e) { + return null; + } + + try { + int size = ma.size(); + Double[] times = new Double[size]; + Double[] values = new Double[size]; + + ma.getAll(Bindings.DOUBLE, Bindings.DOUBLE, times, values); + + double[] times_ = new double[size]; + double[] values_ = new double[size]; + for (int i=0; i getLibraryPathsForModelica(final SysdynExperiment experiment) { + try { + return Simantics.getSession().syncRequest(new Read>() { + @Override + public List perform(ReadGraph graph) throws DatabaseException { + SysdynResource sr = SysdynResource.getInstance(graph); + + List paths = new ArrayList(); + for(Resource parent : getParents(graph, experiment.getModel(), true)) { + if(graph.isInstanceOf(parent, sr.SysdynModel)) { + String modelName = NameUtils.getSafeName(graph, parent); + paths.add(modelName + "_functions.mo"); + } else { + String libraryName = NameUtils.getSafeName(graph, parent); + paths.add("..\\\\\\\\..\\\\\\\\libraries\\\\\\\\functions\\\\\\\\" + libraryName + ".mo"); + } + } + return paths; + } + }); + } + catch (DatabaseException e) { + e.printStackTrace(); + return null; + } + } + + public static void updateFunctionFilesForExperiment(final SysdynExperiment experiment) { + try { + Simantics.getSession().syncRequest(new ReadRequest() { + @Override + public void run(ReadGraph graph) throws DatabaseException { + SysdynResource sr = SysdynResource.getInstance(graph); + + for (Resource parent : getParents(graph, experiment.getModel(), false)) { + if(graph.isInstanceOf(parent, sr.SysdynModel)) { + String parentName = NameUtils.getSafeName(graph, parent); + File scriptFile = new File(experiment.getExperimentDir(), parentName + "_functions.mo"); + updateFunctionFile(graph, parent, scriptFile, false); + } else { + updateFunctionFileForLibrary(graph, parent); + } + } + + } + }); + } + catch (DatabaseException e) { + e.printStackTrace(); + } + } + + private static Set getParents(ReadGraph graph, Resource model, boolean ignoreEmpty) + throws DatabaseException{ + Layer0 l0 = Layer0.getInstance(graph); + SysdynResource sr = SysdynResource.getInstance(graph); + + Set parents = new HashSet(); + + if(model == null) { + return parents; + } + + parents.add(model); + + for(Resource r : graph.getObjects(model, l0.IsLinkedTo)) { + if(graph.isInstanceOf(r, sr.SharedFunctionOntology)) { + parents.add(r); + } else { + if(!graph.syncRequest(new ObjectsWithType(r, l0.ConsistsOf, sr.SysdynModelicaFunctionLibrary)).isEmpty()) { + parents.add(r); + } + } + } + + if(ignoreEmpty) { + Set nonEmptyParents = new HashSet(); + for(Resource parent : parents) { + if(isNonEmpty(graph, parent)) { + nonEmptyParents.add(parent); + } + } + parents = nonEmptyParents; + } + + return parents; + } + + private static boolean isNonEmpty(ReadGraph graph, Resource library) + throws DatabaseException { + Layer0 l0 = Layer0.getInstance(graph); + SysdynResource sr = SysdynResource.getInstance(graph); + + if(!graph.syncRequest(new ObjectsWithType(library, l0.ConsistsOf, sr.SysdynModelicaFunction)).isEmpty()) { + return true; + } else { + for(Resource l : graph.syncRequest(new ObjectsWithType(library, l0.ConsistsOf, sr.SysdynModelicaFunctionLibrary))) { + if(isNonEmpty(graph, l)) { + return true; + } + } + } + + return false; + } + + private static void updateFunctionFile(ReadGraph graph, Resource library, File scriptFile, boolean builtIn) + throws DatabaseException { + PrintStream s; + try { + s = new PrintStream(scriptFile); + } catch (FileNotFoundException e) { + e.printStackTrace(); + return; + } + + SysdynResource sr = SysdynResource.getInstance(graph); + + String name = NameUtils.getSafeName(graph, library); + + if(!builtIn && !graph.isInstanceOf(library, sr.SysdynModel)) { + s.println("package " + name); + } + writeLibrary(graph, library, scriptFile, s, builtIn); + if(!builtIn && !graph.isInstanceOf(library, sr.SysdynModel)) { + s.println("end " + name + ";\n"); + } + + s.close(); + } + + private static void updateFunctionFileForLibrary(ReadGraph graph, Resource library) + throws DatabaseException { + Layer0 l0 = Layer0.getInstance(graph); + + while(!graph.isInstanceOf(library, l0.Ontology)) { + library = graph.getSingleObject(library, l0.PartOf); + } + + File librariesDir = Activator.getBundleContext().getDataFile("libraries"); + if (!librariesDir.exists()) { + librariesDir.mkdir(); + } + File dir = new File(librariesDir, "functions"); + if (!dir.exists()) { + dir.mkdir(); + } + + String parentName = NameUtils.getSafeName(graph, library); + File scriptFile = new File(dir, parentName + ".mo"); + + Resource sysdyn = graph.getResource("http://www.simantics.org/Sysdyn-1.1"); + + if(library.equals(sysdyn)) { + updateFunctionFile(graph, library, scriptFile, true); + } else { + updateFunctionFile(graph, library, scriptFile, false); + } + + } + + private static void writeLibrary(ReadGraph graph, Resource library, File scriptFile, PrintStream stream, boolean builtIn) throws DatabaseException { + Layer0 l0 = Layer0.getInstance(graph); + SysdynResource sr = SysdynResource.getInstance(graph); + writeLibraryFunctions(graph, library, scriptFile, stream); + for(Resource sublibrary : graph.syncRequest(new ObjectsWithType(library, l0.ConsistsOf, sr.SysdynModelicaFunctionLibrary))) { + String name = NameUtils.getSafeName(graph, sublibrary); + if(!builtIn) + stream.println("encapsulated package " + name); + writeLibrary(graph, sublibrary, scriptFile, stream, builtIn); + if(!builtIn) + stream.println("end " + name + ";\n"); + } + } + + private static void writeLibraryFunctions(ReadGraph graph, Resource library, File scriptFile, PrintStream stream) + throws DatabaseException { + Layer0 l0 = Layer0.getInstance(graph); + SysdynResource sr = SysdynResource.getInstance(graph); + for(Resource function : graph.syncRequest(new ObjectsWithType(library, l0.ConsistsOf, sr.SysdynModelicaFunction))) { + String name = NameUtils.getSafeName(graph, function); + // Built-in Modelica (array) functions have no function code and they don't need to be added explicitly. + String functionCode = graph.getPossibleRelatedValue(function, sr.SysdynModelicaFunction_modelicaFunctionCode); + if (functionCode == null) { + continue; + } + stream.println("function " + name); + stream.println(functionCode); + stream.println("end " + name + ";\n"); + for(Resource externalFunction : graph.syncRequest(new ObjectsWithType(function, l0.ConsistsOf, sr.ExternalFunctionFile))) { + createExternalFunctionFile(graph, externalFunction, scriptFile); + } + } + } + + private static void createExternalFunctionFile(ReadGraph graph, Resource externalFunction, File scriptFile) + throws DatabaseException { + SysdynResource sr = SysdynResource.getInstance(graph); + + File dir = scriptFile.getParentFile(); + + if(!dir.exists()) + dir.mkdir(); + + if(!dir.isDirectory()) + return; + + try { + String name = NameUtils.getSafeName(graph, externalFunction); + if(name.endsWith(".o") || name.endsWith(".a")) { + FileOutputStream fos = new FileOutputStream(dir + File.separator + name); + byte[] fileBArray = graph.getPossibleRelatedValue(externalFunction, sr.ExternalFunctionFile_externalFile, Bindings.BYTE_ARRAY); + fos.write(fileBArray); + fos.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/GameResult.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/GameResult.java new file mode 100644 index 00000000..8997ca07 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/GameResult.java @@ -0,0 +1,33 @@ +package org.simantics.sysdyn.manager; + +import gnu.trove.list.array.TDoubleArrayList; +import gnu.trove.map.hash.THashMap; + +import org.simantics.modelica.data.DataSet; +import org.simantics.modelica.data.SimulationResult; + +/** + * Game results + * @author Teemu Lempinen + * + */ +public class GameResult extends SimulationResult { + + public GameResult(SysdynGameExperimentBase sysdynGameExperiment, THashMap results, String[] subscription) { + + // Get times + TDoubleArrayList timeList = results.get("time"); + double[] times = timeList.toArray(); + + String name; + for(int k = 0; k < subscription.length; k++) { + name = subscription[k]; + TDoubleArrayList valueList = results.get(name); + if(valueList.size() == timeList.size()) { + this.variables.add(new DataSet(name, times, valueList.toArray())); + } else { + System.err.println("wrong amount of values " + name); + } + } + } +} \ No newline at end of file diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/HistoryDatasetResult.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/HistoryDatasetResult.java new file mode 100644 index 00000000..9805a7cb --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/HistoryDatasetResult.java @@ -0,0 +1,324 @@ +/******************************************************************************* + * Copyright (c) 2013 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + * Semantum Oy - Bug #4180 + *******************************************************************************/ +package org.simantics.sysdyn.manager; + +import java.io.File; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.simantics.Simantics; +import org.simantics.databoard.Bindings; +import org.simantics.databoard.binding.mutable.Variant; +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.common.utils.NameUtils; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.variable.Variable; +import org.simantics.db.procedure.Listener; +import org.simantics.db.request.Read; +import org.simantics.layer0.Layer0; +import org.simantics.modelica.data.DataSet; +import org.simantics.modelica.data.SimulationResult; +import org.simantics.simulation.ontology.SimulationResource; +import org.simantics.spreadsheet.SheetVariables; +import org.simantics.spreadsheet.common.matrix.VariantMatrix; +import org.simantics.sysdyn.SysdynResource; +import org.simantics.sysdyn.representation.Configuration; +import org.simantics.sysdyn.representation.IElement; +import org.simantics.sysdyn.representation.Module; +import org.simantics.sysdyn.representation.utils.IndexUtils; +import org.simantics.utils.datastructures.Pair; + +/** + * A result built from a spreadsheet table. Imitates a normal simulation result for + * easy display on charts and tables. + * + * @author Teemu Lempinen + * + */ +public class HistoryDatasetResult extends SimulationResult { + @Override + public void read(File file, int interval) {} // Do nothing + @Override + public void read(InputStream stream, int interval) {} // Do nothing + + private boolean disposed; + + /** + * Dispose listeners of this result. It is important to dispose all listeners + * when they are not needed anymore. + */ + public void disposeListeners() { + this.disposed = true; + } + + /** + * Reads history data to this result. Location of the data is described in historyData resource. + * + * @param sysdynResult MemoryResult to which this simulation result is read + * @param historyData Resource describing the history data to be read from a spreadsheet + */ + public void read(final MemoryResult sysdynResult, final Resource historyData) { + + Simantics.getSession().asyncRequest(new Read>>() { + + @Override + public Pair> perform(ReadGraph graph) throws DatabaseException { + ArrayList variables = new ArrayList(); + + SysdynResource sr = SysdynResource.getInstance(graph); + Layer0 l0 = Layer0.getInstance(graph); + SimulationResource simu = SimulationResource.getInstance(graph); + + String datasetName = "History Dataset"; + VariantMatrix vm = null; + SysdynModel sdmodel = null; + String timeVariable = "time"; + boolean columns = true; + try { + Pair> emptyResult = new Pair>(sdmodel, variables); + + + // Find the SysdynModel of this historyData + Resource model = graph.getPossibleObject(historyData, l0.PartOf); + Resource config = graph.getPossibleObject(model, simu.HasConfiguration); + sdmodel = SysdynModelManager.getInstance(graph.getSession()).getModel(graph, config); + sdmodel.update(graph); + + // Find properties of the result: name, sheet, range, time variable, orientation + datasetName = NameUtils.getSafeLabel(graph, historyData); + + + Resource sheet = graph.getPossibleObject(historyData, sr.HistoryDataset_sheet); + if(sheet == null) + return emptyResult; + + String start = graph.getPossibleRelatedValue(historyData, sr.HistoryDataset_start); + String end = graph.getPossibleRelatedValue(historyData, sr.HistoryDataset_end); + if(start == null || start.isEmpty() || end == null || end.isEmpty()) + return emptyResult; + String r = start + ":" + end; + + String time = graph.getPossibleRelatedValue(historyData, sr.HistoryDataset_timeName); + if(time != null && !time.isEmpty()) + timeVariable = time; + + if(graph.hasStatement(historyData, sr.HistoryDataset_columns)) + columns = graph.getRelatedValue(historyData, sr.HistoryDataset_columns, Bindings.BOOLEAN); + + // Find the sheet variable + Variable v = graph.adapt(sheet, Variable.class); + Variable range = v.getChild(graph, r); + if(range == null) + return emptyResult; + + // Find the content of the range + Variant content = range.getPropertyValue(graph, SheetVariables.CONTENT, Bindings.VARIANT); + Object matrixValue = content.getValue(); + if(matrixValue instanceof VariantMatrix) { + vm = (VariantMatrix)matrixValue; + } + + } catch(DatabaseException e) { + return new Pair>(sdmodel, variables); + } catch(NegativeArraySizeException e) { + // Negative array size may be result of mofifying start and end variables + return new Pair>(sdmodel, variables); + } + + + // Orientation + int x = columns ? vm.getColumnCount() : vm.getRowCount(); + int y = columns ? vm.getRowCount() : vm.getColumnCount(); + + /* + * The table needs at least: + * + * headers for variables + one value + * two variables (of which one is time-variable) + * + * => minimum of 2x2 matrix + */ + if(vm == null || x < 2 || y < 2) + return new Pair>(sdmodel, variables); + + String[] names = new String[x]; + HashMap>> values = new HashMap>>(); + Integer timeIndex = null; + + // Find variable names + for(int i = 0; i < x ; i++) { + Variant cell = columns ? vm.get(0, i) : vm.get(i, 0); + if(cell != null && cell.getValue() != null) { + String name = cell.getValue().toString(); + if(!values.containsKey(name)) { + names[i] = name; + values.put(names[i], new ArrayList>()); + + // Time column index + if(names[i].equals(timeVariable)) + timeIndex = i; + } + } else { + names[i] = null; + } + } + + // If times were not found, return empty + if(timeIndex == null || names[timeIndex] == null) + return new Pair>(sdmodel, variables); + + // Get time column ready first + for(int i = 1; i < y; i++) { + Variant cell = columns ? vm.get(i, timeIndex) : vm.get(timeIndex, i); + Double value = null; + if(cell != null) + value = getDoubleValue(cell); + values.get(names[timeIndex]).add(new Pair(value, value)); // add also null-values + } + + // Get variable values column by column (or row by row + for(int i = 0; i < x; i++) { + if(i == timeIndex || names[i] == null) + continue; + + for(int j = 1; j < y; j++) { + Variant cell = columns ? vm.get(j, i) : vm.get(i, j); + if(cell != null && cell.getValue() != null) { + Double value = getDoubleValue(cell); + if(value != null) { + Pair time = values.get(names[timeIndex]).get(j - 1); + if(time != null && time.first != null) { + values.get(names[i]).add( + new Pair( + time.first, + value) + ); + } + } + } + } + + ArrayList> doubles = values.get(names[i]); + + String name = names[i]; + // If the variable has array indexes, they need to be converted to numbers + if(name.contains("[")) { + org.simantics.sysdyn.representation.Variable variable = getVariable(name, sdmodel.getConfiguration()); + if(variable != null) + name = IndexUtils.equationRangesToIndexes(variable, name); + } + + // Replace spaces with '_'. That is how they are stored elsewhere + name = name.replace(" ", "_"); + + // Read values to SysdynDataSet + SysdynDataSet ds = new SysdynDataSet(name, datasetName, new double[doubles.size()], new double[doubles.size()]); + variables.add(ds); + for(int d = 0; d < doubles.size(); d++) { + Pair pair = doubles.get(d); + ds.times[d] = pair.first; + ds.values[d] = pair.second; + } + } + return new Pair>(sdmodel, variables); + } + + }, new Listener>>() { + + @Override + public void execute(Pair> result) { + // Update result set and send message to model that results have been changed + HistoryDatasetResult.this.variables = result.second; + sysdynResult.setResult(HistoryDatasetResult.this); + if(result.first != null) + result.first.resultChanged(); + } + + @Override + public void exception(Throwable t) { + t.printStackTrace(); + } + + @Override + public boolean isDisposed() { + return disposed; + } + }); + + + } + + /** + * Finds a variable defined by path starting from configuration + * @param path Path of the variable + * @param configuration Configuration where to look for the variable + * @return Variable + */ + private org.simantics.sysdyn.representation.Variable getVariable(String path, Configuration configuration) { + String next = path; + int index = next.indexOf("."); + + // If path has commas, we are looking for a module + if(index > 0) { + path = path.substring(index + 1); + next = next.substring(0, index); + } else { + // No commas, we are looking for a variable + if(next.contains("[")) + // Variable has array indexes, remove the array indexes + next = next.substring(0, next.indexOf("[")); + } + + for(IElement e : configuration.getElements()) { + if(e instanceof org.simantics.sysdyn.representation.Variable) { + org.simantics.sysdyn.representation.Variable v = (org.simantics.sysdyn.representation.Variable) e; + if(v.getName().equals(next)) { + return v; // found the variable + } + } else if(e instanceof Module && ((Module)e).getName().equals(next)) { + return getVariable(path, ((Module)e).getType().getConfiguration()); // Recursive call with a shorter path + } + } + return null; + } + + /** + * Finds the double value from a spreadsheet cell. + * @param cell Cell where to look for + * @return Double value of the cell or null if not double or if empty + */ + private Double getDoubleValue(Variant cell) { + if(cell.getValue() == null) + return null; + + Double value = null; + try { + value = Double.parseDouble(cell.getValue().toString()); + } catch (NumberFormatException e) { + } + return value; + } + + @Override + public DataSet getDataSet(String name) { + DataSet ds = super.getDataSet(name); + if(ds == null && name.contains(".")) { + ds = super.getDataSet(name.substring(name.lastIndexOf(".") + 1)); + } + return ds; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/HistoryDatasetUtils.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/HistoryDatasetUtils.java new file mode 100644 index 00000000..e164c81b --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/HistoryDatasetUtils.java @@ -0,0 +1,92 @@ +/******************************************************************************* + * Copyright (c) 2007, 2012 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.manager; + +import java.util.ArrayList; +import java.util.List; + +import org.simantics.databoard.Bindings; +import org.simantics.databoard.binding.mutable.Variant; +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.variable.Variable; +import org.simantics.spreadsheet.SheetVariables; +import org.simantics.spreadsheet.common.matrix.VariantMatrix; +import org.simantics.sysdyn.SysdynResource; + +public class HistoryDatasetUtils { + + public static List getVariableNamesInRange(ReadGraph graph, Resource historyData) throws DatabaseException { + SysdynResource sr = SysdynResource.getInstance(graph); + + ArrayList values = new ArrayList(); + + + Resource sheet = graph.getPossibleObject(historyData, sr.HistoryDataset_sheet); + if(sheet == null) + return values; + + String start = graph.getPossibleRelatedValue(historyData, sr.HistoryDataset_start); + String end = graph.getPossibleRelatedValue(historyData, sr.HistoryDataset_end); + if(start == null || start.isEmpty() || end == null || end.isEmpty()) + return values; + String r = start + ":" + end; + + if(!graph.hasStatement(historyData, sr.HistoryDataset_columns)) + return values; + + boolean columns = graph.getRelatedValue(historyData, sr.HistoryDataset_columns, Bindings.BOOLEAN); + + Variable v = graph.adapt(sheet, Variable.class); + Variable range = v.getChild(graph, r); + if(range == null) + return values; + + Variant content = range.getPropertyValue(graph, SheetVariables.CONTENT, Bindings.VARIANT); + Object matrixValue = content.getValue(); + if(!(matrixValue instanceof VariantMatrix)) + return values; + + VariantMatrix vm = (VariantMatrix)matrixValue; + + /* + * The table needs at least: + * + * headers for variables + one value + * two variables (of which one is time-variable) + * + * => minimum of 2x2 matrix + */ + + int x = columns ? vm.getColumnCount() : vm.getRowCount(); + int y = columns ? vm.getRowCount() : vm.getColumnCount(); + + if(vm == null || x < 2 || y < 2) + return values; + + + // Names + for(int i = 0; i < x ; i++) { + Variant cell = columns ? vm.get(0, i) : vm.get(i, 0); + if(cell != null && cell.getValue() != null) { + String name = cell.getValue().toString(); + if(!values.contains(name)) { + values.add(name); + } + } + } + + return values; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/MemoryResult.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/MemoryResult.java new file mode 100644 index 00000000..f6ef5bb5 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/MemoryResult.java @@ -0,0 +1,249 @@ +/******************************************************************************* + * Copyright (c) 2013 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Semantum Oy - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.manager; + +import gnu.trove.map.hash.THashMap; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.List; +import java.util.TreeMap; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.simantics.databoard.Accessors; +import org.simantics.databoard.Bindings; +import org.simantics.databoard.Datatypes; +import org.simantics.databoard.Files; +import org.simantics.databoard.accessor.MapAccessor; +import org.simantics.databoard.accessor.RecordAccessor; +import org.simantics.databoard.accessor.error.AccessorConstructionException; +import org.simantics.databoard.accessor.java.JavaRecord; +import org.simantics.databoard.annotations.Arguments; +import org.simantics.databoard.binding.Binding; +import org.simantics.databoard.binding.RecordBinding; +import org.simantics.databoard.binding.error.BindingException; +import org.simantics.databoard.binding.mutable.Variant; +import org.simantics.databoard.type.Datatype; +import org.simantics.modelica.data.DataSet; +import org.simantics.modelica.data.SimulationResult; + +// TODO: rename to OpenModelicaResult or something as this is very specific? +public class MemoryResult extends SysdynResult { + + private THashMap results; + private File resultFile; + private Integer resultIndex = null; + private SimulationResult simulationResult; + + + /** + * Create a sysdynresult accessor using a {@link SimulationResult} + * @param result + */ + public MemoryResult(SimulationResult result, String resultName) { + super(resultName); + + results = new THashMap(); + + if(result != null) + setResult(result); + + } + + @Override + public SysdynDataSet getDataSet(String variable) { + // Try to get cached result + SysdynDataSet result = results.get(variable); + if(result != null) + return result; + + // if not found, try to read it + SimulationResult simulationResult = getSimulationResult(); + try { + if (simulationResult != null) { + DataSet ds = simulationResult.getDataSet(variable); + if(ds == null) + ds = simulationResult.readVariable(variable, resultFile); + + if(ds != null) { + SysdynDataSet sds = new SysdynDataSet(ds.name, getResultName(), ds.times, ds.values, resultIndex); + results.put(variable, sds); + return sds; + } + } + } catch (FileNotFoundException e1) { + // Unable to read data from OpenModelica result file + System.err.println("Variable " + variable + " not found in OpenModelica result file"); + return null; + } catch (IOException e1) { + // IoFail + e1.printStackTrace(); + } + + return null; + } + + public void setResultFile(File resFile) { + this.resultFile = resFile; + } + + public int numberOfVariables() { + return simulationResult.getVariableDataSets().size(); + } + + public void setResult(SimulationResult result) { + this.simulationResult = result; + this.results.clear(); + if(result != null) + addAllInitialValues(result); // For legacy reasons + } + + public SimulationResult getSimulationResult() { + return this.simulationResult; + } + + + + /** + * Read all results from their DataSets. --- Legacy init file support. Not needed with mat files. + */ + private void addAllInitialValues(SimulationResult result) { + // Add initial values + for(DataSet ds : result.getInitialValueDataSets()){ + SysdynDataSet sds = new SysdynDataSet(ds.name, getResultName(), ds.times, ds.values); + results.put(ds.name, sds); + } + } + + + /** + * Save current {@link RecordAccessor} to a {@link File} + * + * @param file {@link File} where the {@link RecordAccessor} is saved + */ + @Override + public void saveToFile(File file, IProgressMonitor progressMonitor) { + try { + // Create Memory Historian + Datatype recordingSessionType = Datatypes.getDatatype("RecordingSession"); + RecordBinding sessionBinding = (RecordBinding) Bindings.getBinding( recordingSessionType ); + Object session = sessionBinding.createDefault(); + JavaRecord accessor = (JavaRecord) Accessors.getAccessor( sessionBinding, session ); + + // Get binding and value from memory + JavaRecord jr = (JavaRecord) accessor; + Binding binding = jr.getBinding(); + Object value = jr.getObject(); + + // Read the missing variables one by one. + getSimulationResult().readMissingVariables(this.resultFile); + + addAllDataSetsToAccessor(accessor, progressMonitor); + // Write to file + if (progressMonitor != null) { + progressMonitor.subTask("Save results"); + } + Files.createFile(file, binding, value); + + // The division is made so that 1 unit per variable and their sum for saving them. + progressMonitor.worked(numberOfVariables()); + } catch (IOException e) { + e.printStackTrace(); + } catch (BindingException e) { + e.printStackTrace(); + } catch (AccessorConstructionException e) { + e.printStackTrace(); + } + + } + + + /** + * Read all results from their DataSets. + * @param progressMonitor + */ + private void addAllDataSetsToAccessor(JavaRecord accessor, IProgressMonitor progressMonitor) { + try { + MapAccessor recordings = accessor.getFieldAccessor("recordings"); + + // There is a recording for each variable + List datasets = getSimulationResult().getVariableDataSets(); + RecordBinding recordingBinding = (RecordBinding) Bindings.getBinding( Recording.class ); + if (progressMonitor != null) { + progressMonitor.subTask("Prepare saving"); + } + // Add variables + for(DataSet ds : datasets){ + if (progressMonitor != null) { + progressMonitor.worked(1); + } + // Add recording to session, if not already added + Variant dsNodeId = Variant.ofInstance( ds.name ); + if (recordings.containsKey(Bindings.VARIANT, dsNodeId)) + continue; + + Recording recording = createRecording(ds); + recordings.put(Bindings.VARIANT, recording.nodeId, Bindings.VARIANT, new Variant(recordingBinding, recording)); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Create a recording for a variable to this result's {@link RecordAccessor} + * @param ds {@link DataSet} for the variable + * @return {@link Recording} + * @throws BindingException + */ + @SuppressWarnings("unchecked") + Recording createRecording(DataSet ds) throws BindingException { + RecordBinding recordingBinding = (RecordBinding) Bindings.getBindingUnchecked( Recording.class ); + Recording recording = (Recording) recordingBinding.createDefault(); + recording.nodeId = Variant.ofInstance( ds.name ); + recording.labels.put("en", ds.name); + + // Create one segment + TreeMap segment = new TreeMap(); + recording.segments = new TreeMap[] { segment }; + + int length = ds.values.length; + for (int i=0; i labels; + public @Arguments({TreeMap.class, Double.class, Double.class}) TreeMap[] segments; + } + + /** + * Set the index of the run; used when the individual time series of a variable are shown in + * the same JFreeChart. + * @param currentRun The index of the run + */ + public void setResultIndex(int resultIndex) { + this.resultIndex = resultIndex; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/OldSysdynExperiment.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/OldSysdynExperiment.java new file mode 100644 index 00000000..d9218f28 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/OldSysdynExperiment.java @@ -0,0 +1,893 @@ +/******************************************************************************* + * Copyright (c) 2010, 2013 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + * Semantum Oy - Bug #4180 + *******************************************************************************/ +package org.simantics.sysdyn.manager; + +import gnu.trove.set.hash.THashSet; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.concurrent.locks.Lock; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.preferences.DefaultScope; +import org.eclipse.core.runtime.preferences.IScopeContext; +import org.osgi.service.prefs.Preferences; +import org.simantics.db.ReadGraph; +import org.simantics.db.RequestProcessor; +import org.simantics.db.Resource; +import org.simantics.db.Session; +import org.simantics.db.VirtualGraph; +import org.simantics.db.WriteGraph; +import org.simantics.db.common.request.ReadRequest; +import org.simantics.db.common.request.WriteRequest; +import org.simantics.db.common.utils.Logger; +import org.simantics.db.common.utils.NameUtils; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.service.VirtualGraphSupport; +import org.simantics.layer0.Layer0; +import org.simantics.modelica.IModelicaMonitor; +import org.simantics.modelica.ModelicaException; +import org.simantics.modelica.ModelicaKeys; +import org.simantics.modelica.ModelicaManager; +import org.simantics.modelica.SimulationLocation; +import org.simantics.modelica.data.CSVSimulationResult; +import org.simantics.modelica.data.MatSimulationResult; +import org.simantics.modelica.data.SimulationResult; +import org.simantics.modelica.preferences.OpenModelicaPreferences; +import org.simantics.simulation.data.Datasource; +import org.simantics.simulation.experiment.ExperimentState; +import org.simantics.simulation.experiment.IExperimentListener; +import org.simantics.simulation.ontology.SimulationResource; +import org.simantics.sysdyn.Activator; +import org.simantics.sysdyn.adapter.VariableValueSubscription; +import org.simantics.sysdyn.modelica.ModelicaWriter; +import org.simantics.sysdyn.representation.Configuration; +import org.simantics.sysdyn.representation.Model; +import org.simantics.sysdyn.simulation.SimulationScheduler; + +public class OldSysdynExperiment extends SysdynExperiment { + + protected Session session; + protected Runnable modificationListener; + protected SysdynModel sysdynModel; + protected boolean toggled = false; + @SuppressWarnings("rawtypes") + protected THashSet variableValueSubscriptions = new THashSet(); + @SuppressWarnings("rawtypes") + protected volatile VariableValueSubscription[] variableValueSubscriptionsSnapshot = null; + + protected String previousModelStructure; + protected HashMap previousParameters; + protected Process process; + protected boolean canceled = false; + protected ExperimentState sysdynExperimentState; + + private SysdynResult result; + private File simulationDir; + + protected String experimentName; + protected static String omcVersion = null; + protected static String omcHome = null; + + public static OldSysdynExperiment INSTANCE; + + boolean publishResults = true; + + public OldSysdynExperiment(Resource experiment, Resource model) { + super(experiment, model); + INSTANCE = this; + } + + public static OldSysdynExperiment getInstance() { + return INSTANCE; + } + + public SysdynResult getCurrentResult() { + if(this.result == null) + this.result = new MemoryResult(null, null); + return this.result; + } + + public Collection getActiveResults() { + ArrayList result = new ArrayList(); + if(getCurrentResult() != null) + result.add(getCurrentResult()); + result.addAll(sysdynModel.getDisplayedResults()); + return result; + } + + /** + * Initialize this experiment + * @param g ReadGraph + */ + public void init(ReadGraph g) { + try { + this.experimentName = NameUtils.getSafeName(g, experiment); + } catch (DatabaseException e) { + this.experimentName = "Experiment"; + } + + this.session = g.getSession(); + state = ExperimentState.STOPPED; + for(IExperimentListener listener : listeners.getListeners()) + listener.stateChanged(state); + + try { + g.syncRequest(new ReadRequest() { + + @Override + public void run(ReadGraph graph) throws DatabaseException { + final Resource configuration = graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration); + sysdynModel = SysdynModelManager.getInstance(session).getModel(graph, configuration); + toggleActivation(graph, true); + } + }); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } + + setSysdynExperimentState(ExperimentState.INITIALIZING); + } + + @Override + public void saveState() { + if(result == null || !(result instanceof MemoryResult)) + return; + // TODO: temporary fix + SaveResultJob saveResultJob = new SaveResultJob(OldSysdynExperiment.this, session, (MemoryResult)result); + saveResultJob.schedule(); + } + + protected Thread getSaveThread(final SysdynResult result, final File file, final IProgressMonitor progressMonitor) { + return new Thread() { + @Override + public void run() { + if(!canceled) { + // Get and store results result.saveToFile(file, progressMonitor); + } } + }; + } + + /** + * Starts a simulation job. Use this method to start a simulation. + */ + @Override + public void simulate(boolean enabled) { + if(enabled && sysdynModel != null) { + if(!ExperimentState.RUNNING.equals(getState())) { + changeState(ExperimentState.RUNNING); + startSimulationJob(); + } + } else if (!toggled){ + changeState(ExperimentState.STOPPED); + } + } + + /** + * Starts a simulation job + */ + protected void startSimulationJob() { + session.asyncRequest(new ReadRequest() { + + @Override + public void run(ReadGraph graph) throws DatabaseException { + SimulationScheduler.start(sysdynModel, OldSysdynExperiment.this); + } + }); + } + + + /** + * Write model configuration to a single Modelica code + * @param monitor + * @param isGame is the experiment a "game experiment". This is needed for modifying the code to work with FMU simulation + * @return Modelica code + */ + protected String getModelicaCode(IModelicaMonitor monitor, boolean isGame, String modelicaVersion) { + String modelText = null; + try { + // Write all configurations once + modelText = ModelicaWriter.write(sysdynModel.getModules(), sysdynModel.getConfiguration().getModel().getStartTime(), isGame, modelicaVersion); + } catch (Exception e) { + // Stop experiment and show console + /*setExperimentStopped(experiment); =>*/ simulate(false); + monitor.showConsole(); + monitor.message("Error when writing Modelica code."); + } + return modelText; + } + + /** + * Get all inits and parameter values required for the inits -file + * @param monitor + * @return All inits in a map + */ + protected HashMap getExperimentParameters(IModelicaMonitor monitor) { + Configuration configuration = sysdynModel.getConfiguration(); +// HashMap inits = sysdynModel.getInits(configuration, ""); Not needed anymore, whole xml content is replaced + HashMap parameters = new HashMap(); + Model model = configuration.getModel(); + Double startTime = model.getStartTime(); + Double stopTime = model.getStopTime(); + parameters.put(ModelicaKeys.START_VALUE, startTime.toString()); + parameters.put(ModelicaKeys.STOP_VALUE, stopTime.toString()); + String outputFormat = "mat"; + parameters.put(ModelicaKeys.OUTPUT_FORMAT, outputFormat); + + Double simulationStepLength = model.getSimulationStepLength(); + if(simulationStepLength != null) { + parameters.put(ModelicaKeys.STEP_VALUE, simulationStepLength.toString()); + parameters.put(ModelicaKeys.NUMBER_OF_INTERVALS, "" + ((int)((stopTime - startTime) / simulationStepLength))); + } else { + parameters.put(ModelicaKeys.STEP_VALUE, "" + (stopTime - startTime) / 500); + } + + Double outputInterval = model.getOutputInterval(); + parameters.put(ModelicaKeys.OUTPUT_INTERVAL, outputInterval != null ? outputInterval.toString() : parameters.get(ModelicaKeys.STEP_VALUE)); + + String method = "\"" + model.getSolver() + "\""; + parameters.put(ModelicaKeys.METHOD, method); + if(model.getTolerance() != null) + parameters.put(ModelicaKeys.TOLERANCE, model.getTolerance().toString()); + String variableFilter = model.getVariableFilter(); + if(variableFilter != null && !variableFilter.isEmpty()) + parameters.put(ModelicaKeys.VARIABLE_FILTER, variableFilter); + return parameters; + } + + /** + * Builds a model + * @param simulationLocation + * @param inits + * @param modelText + * @param monitor + */ + protected void buildModel(SimulationLocation simulationLocation, IModelicaMonitor monitor) { + + try { + simulationLocation.executableFile.delete(); + ModelicaManager.buildModel(simulationLocation, monitor); + } catch (ModelicaException e) { + if(e.getMessage() != null) + monitor.message(e.getMessage()); + monitor.showConsole(); + canceled = true; + previousModelStructure = ""; + previousParameters = null; + } + } + + /** + * Run a built model + * @param structureChanged + * @throws IOException + */ + protected void runModelica(SimulationLocation simulationLocation, IModelicaMonitor monitor, IProgressMonitor progressMonitor, HashMap experimentParameters, HashMap changes) throws IOException { + progressMonitor.subTask("Simulate model"); + process = ModelicaManager.runModelica( + simulationLocation, + monitor, + experimentParameters, + changes + ); + ModelicaManager.printProcessOutput(process, monitor); + + Thread resultThread = getResultThread(simulationLocation, experimentParameters, monitor, progressMonitor); + resultThread.run(); + + process = null; + } + + /** + * Get a thread for reading and saving reuslts from a normal simulation + * @param simulationLocation + * @param inits + * @param monitor + * @param progressMonitor + * @return + */ + protected Thread getResultThread(final SimulationLocation simulationLocation, final HashMap experimentParameters, final IModelicaMonitor monitor, final IProgressMonitor progressMonitor) { + return new Thread() { + @Override + public void run() { + try { + process.waitFor(); + + if(!canceled) { + // Get and store results + progressMonitor.worked(1); + progressMonitor.subTask("Read results"); + SimulationResult result; + if(simulationLocation.resultFile.getName().endsWith(".csv")) + result = new CSVSimulationResult(); + else if(simulationLocation.resultFile.getName().endsWith(".plt")) + result = new SimulationResult(); + else + result = new MatSimulationResult(); // The latest format + + // The interval of results saved. Every result? Every other result? etc... + int outIntervalInt = 1; + String outputInterval = experimentParameters.get(ModelicaKeys.OUTPUT_INTERVAL); + if(outputInterval != null) { + String stepTime = experimentParameters.get(ModelicaKeys.STEP_VALUE); + String stopTime = experimentParameters.get(ModelicaKeys.STOP_VALUE); + + Double step = Double.parseDouble(stepTime); + Double stop = Double.parseDouble(stopTime); + Double outInterval = Double.parseDouble(outputInterval); + + outIntervalInt = (int)getInterval(outInterval, step); + // Actually you might be able to use an outInterval one or two longer. + int maxIntervalInt = (int)Math.round(stop / step); + if (outIntervalInt > maxIntervalInt) + outIntervalInt = maxIntervalInt; + } + + result.initRead(simulationLocation.resultFile); + result.readTime(simulationLocation.resultFile, outIntervalInt); + //result.readInits(simulationLocation.initFile); // Parameter values are read from .mat + result.filter(); + ((MemoryResult)getCurrentResult()).setResult(result); + ((MemoryResult)getCurrentResult()).setResultFile(simulationLocation.resultFile); + progressMonitor.worked(1); + resultsChanged(); + + simulate(false); + + String errorString = result.getResultReadErrors(); + if(errorString != null && !errorString.isEmpty()) + monitor.message(errorString); + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }; + } + + protected static long getInterval(double outputLength, double stepLength) { + double interval = outputLength / stepLength; + if (interval <= 1) + return 1; + return Math.round(interval); + } + + + /** + * + * @param sysdynModel + * @param modelText + * @param inits + * @param additionalScript + * @return + * @throws IOException + */ + protected SimulationLocation createSimulationFiles(SysdynModel sysdynModel, String modelText, HashMap inits, String additionalScript, boolean fmu) throws IOException { + File simulationDir = getExperimentDir(); + + // update all function files. both the model's and built-in + FunctionUtils.updateFunctionFilesForExperiment(this); + + + SimulationLocation location = ModelicaManager.createSimulationLocation(simulationDir, sysdynModel.getConfiguration().getLabel(), modelText, ModelicaManager.getOMHome(), ModelicaManager.isOldOMVersion()); + if (fmu) { + ModelicaManager.createFMUSimulationScripts(location, inits, additionalScript); + } + else { + ModelicaManager.createSimulationScripts(location, inits, additionalScript); + } + return location; + } + + /** + * Get a simulation directory for this model + * @return File directory + */ + public File getExperimentDir() { + if(simulationDir == null) { + File modelsDir = Activator.getBundleContext().getDataFile("models"); + String experimentName = this.experimentName; + List files = Arrays.asList(modelsDir.list()); + if (files.contains(experimentName)) { + int i = 2; + while (files.contains(experimentName + "_" + i)){ + i++; + } + experimentName += "_" + i; + } + + simulationDir = Activator.getBundleContext().getDataFile("models/" + experimentName); + if (!simulationDir.exists()) { + simulationDir.mkdir(); + } + } + return simulationDir; + } + + /** + * + * @return + */ + protected String getAdditionalScripts() { + StringBuilder functionscript = new StringBuilder(); + for(String path : FunctionUtils.getLibraryPathsForModelica(this)) { + functionscript.append("loadFile(\"" + path + "\");\n"); + } + return functionscript.toString(); + } + + /** + * Starts simulating a model. Call only from inside simulation job! Start simulation using simulate(true). + * @param monitor + * @param progressMonitor + * @throws IOException + */ + public synchronized void simulate(final IModelicaMonitor monitor, final IProgressMonitor progressMonitor, String modelName) throws IOException { + canceled = false; + progressMonitor.subTask("Write modelica classes"); + + omcVersion = ModelicaManager.getDefaultOMVersion(); + + monitor.message("Simulate " + modelName + " using OpenModelica " + omcVersion); + + // Get Modelica code + String modelText = getModelicaCode(monitor, false, omcVersion); + if(modelText == null) + return; + progressMonitor.worked(1); + + // Write initial files and add init-parameters + progressMonitor.subTask("Write simulation files"); + HashMap experimentParameters = getExperimentParameters(monitor); + + // add loadFile script to load all related functions and function libraries + String additionalScript = getAdditionalScripts(); + + // Create simulation files + SimulationLocation simulationLocation = createSimulationFiles(sysdynModel, modelText, experimentParameters, additionalScript, false); + progressMonitor.worked(1); + + // Build the model and store previous model structure and inits that affect the building + // If there is no exe file OR the model structure has not changed, no need to build + String flatModelText = ModelicaManager.getFlatModelText(simulationLocation, monitor, FunctionUtils.getLibraryPathsForModelica(this)); + boolean structureChanged = sysdynModel.isStructureModified(); + + if (!simulationLocation.executableFile.isFile() || structureChanged) { + progressMonitor.subTask("Build model"); + previousModelStructure = flatModelText; + previousParameters = ModelicaManager.getModelParameters(previousModelStructure); + + buildModel(simulationLocation, monitor); + } + + // Add changed parameters in case that structure has not changed + HashMap changes = structureChanged ? null : new HashMap(); + if(!structureChanged && previousParameters != null && omcVersion.startsWith("1.9")) { + HashMap newParameters = ModelicaManager.getModelParameters(flatModelText); + for(String key : previousParameters.keySet()) { + if(!previousParameters.get(key).equals(newParameters.get(key))) { + changes.put(key, newParameters.get(key)); + } + } + previousParameters = newParameters; + } + progressMonitor.worked(1); + + if(simulationLocation != null && !canceled) { + // Simulate the model + runModelica(simulationLocation, monitor, progressMonitor, experimentParameters, changes); + } + + if(canceled) + simulate(false); + process = null; + } + + /** + * Get the version of the OpenModelica compiler that is defined to be used + * in Preferences + * @return OpenModelica version + */ + protected String getOpenModelicaVersion() { + String omVersion = null; + + IScopeContext context = DefaultScope.INSTANCE; + Preferences node = context.getNode(org.simantics.modelica.Activator.PLUGIN_ID); + String omHome = node.get(OpenModelicaPreferences.OM_HOME, null); + if(omHome != null) { + File omHomeDir = new File(omHome); + if(omHomeDir != null && omHomeDir.isDirectory()) + omVersion = ModelicaManager.getOMVersion(omHomeDir); + } + + if(omVersion == null) { + omVersion = ModelicaManager.getDefaultOMVersion(); + } + + return omVersion; + } + + + /** + * Method that compares given modelText and inits to previous model and inits + * @param modelText Textual representation of a model (Modelica code) + * @param inits map of init parameters + * @return true if the model has changed, false otherwise + */ +// protected boolean hasStructureChanged(String modelText) { +// +// if(previousModelStructure == null) +// return true; +// +// // Then compare the actual model structure +// BufferedReader current = new BufferedReader( +// new StringReader(modelText)); +// BufferedReader previous = new BufferedReader( +// new StringReader(previousModelStructure)); +// +// String c, p; +// try { +// // Read both current and previous model texts at the same time +// c = current.readLine(); +// p = previous.readLine(); +// +// while (c != null && p != null) { +// // if the lines are the same, no need for further examination +// if(!c.equals(p)) { +// if(c.contains("parameter") && p.contains("parameter")) { +// /* +// * The line is a parameter definition. +// * In this case only what is before '=' matters +// * +// * parameter Real Var = 1; +// * is structurally same as +// * parameter Real Var = 2; +// */ +// int i = c.indexOf("="); +// if(!c.substring(0, i).equals(p.substring(0, i))) { +// // different parameter definition +// return true; +// } +// } else { +// // other than a line containing parameters differs +// return true; +// } +// } +// c = current.readLine(); +// p = previous.readLine(); +// } +// +// if((c == null && p != null) || (c != null && p == null)) { +// // different lengths +// return true; +// } +// +// } catch(IOException e) { +// // Something went wrong in the comparison, it is safer to say that the structure has changed +// return true; +// } +// return false; +// } + + /** + * Destroy an ongoing simulation process + */ + public void cancelSimulation() { + canceled = true; + if(process != null) { + process.destroy(); + } + } + + /** + * Toggle simulation state + * @param enabled true == RUNNING, false == STOPPED + */ + public void toggleSimulation(boolean enabled) { + if(enabled) { + this.toggled = true; + changeState(ExperimentState.RUNNING); + if(modificationListener == null) { + + modificationListener = new Runnable() { + + @Override + public void run() { + session.asyncRequest(new ReadRequest() { + + @Override + public void run(ReadGraph graph) throws DatabaseException { + if(getState() == ExperimentState.RUNNING) { + SimulationScheduler.start(sysdynModel, OldSysdynExperiment.this); + } + + } + }); + + }; + }; + sysdynModel.addModificationListener(modificationListener); + } + } + else { + changeState(ExperimentState.STOPPED); + this.toggled = false; + } + + } + + @Override + public void refresh(RequestProcessor session) { + session.asyncRequest(new ReadRequest() { + + @Override + public void run(ReadGraph graph) throws DatabaseException { + init(graph); + } + + }); + } + + @Override + public void refresh(Session session) { + refresh((RequestProcessor)session); + } + + @Override + protected void localStateChange() { + setSysdynExperimentState(getState()); + switch(state) { + case DISPOSED: + onExperimentDisposed(); + break; + default: + break; + } + + } + + /** + * Returns sysdyn experiment state. It is usually the same as ordinary experiment state. + * Initializing phase takes longer than normally in game experiments. + * @return + */ + public ExperimentState getSysdynExperimentState() { + return sysdynExperimentState; + } + + protected void setSysdynExperimentState(final ExperimentState state) { + sysdynExperimentState = state; + session.asyncRequest(new ReadRequest() { + + @Override + public void run(ReadGraph graph) throws DatabaseException { + VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class); + final Session session = graph.getSession(); + session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("experiments")) { + @Override + public void perform(WriteGraph graph) throws DatabaseException { + Layer0 L0 = Layer0.getInstance(graph); + SimulationResource SR = SimulationResource.getInstance(graph); + graph.deny(model, SR.HasExperimentState); + graph.deny(experiment, SR.HasExperimentState); + + Resource st = graph.newResource(); + switch(state) { + case INITIALIZING: + graph.claim(st, L0.InstanceOf, SR.ExperimentState_Initializing); + break; + case RUNNING: + graph.claim(st, L0.InstanceOf, SR.ExperimentState_Running); + break; + case STOPPED: + graph.claim(st, L0.InstanceOf, SR.ExperimentState_Stopped); + break; + case DISPOSED: + graph.claim(st, L0.InstanceOf, SR.ExperimentState_Disposed); + break; + } + + graph.claim(model, SR.HasExperimentState, st); + graph.claim(experiment, SR.HasExperimentState, st); + }}); + } + }); + } + + /** + * Actions performed when experiment is disposed + * @param graph + */ + protected void onExperimentDisposed() { + cancelSimulation(); + sysdynModel.removeModificationListener(modificationListener); + modificationListener = null; + + session.asyncRequest(new ReadRequest() { + @Override + public void run(ReadGraph graph) throws DatabaseException { + toggleActivation(graph, false); + } + }); + } + + + /** + * Toggles the active-state of this experiment on or off + * @param graph ReadGraph + * @param activate The active-state of this experiment + */ + protected void toggleActivation(ReadGraph graph, final boolean activate) { + VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class); + final Session session = graph.getSession(); + session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("experiments")) { + @Override + public void perform(WriteGraph graph) throws DatabaseException { + VirtualGraph runtime = graph.getService(VirtualGraph.class); + + session.asyncRequest(new WriteRequest(runtime) { + + @Override + public void perform(WriteGraph graph) throws DatabaseException { + SimulationResource SIMU = SimulationResource.getInstance(graph); + if(activate) + graph.claim(experiment, SIMU.IsActive, experiment); + else + graph.denyStatement(experiment, SIMU.IsActive, experiment); + } + + }); + } + }); + } + + + /* Result subscriptions */ + + @SuppressWarnings("rawtypes") + /** + * Copy from AprosExperiment + * @param subscription + */ + @Override + public void addVariableValueSubscription(VariableValueSubscription subscription) { + assert subscription != null; + synchronized (variableValueSubscriptions) { + //System.out.println("ADD listener " + subscription); + variableValueSubscriptions.add(subscription); + variableValueSubscriptionsSnapshot = null; + } + } + + @SuppressWarnings("rawtypes") + /** + * Copy from AprosExperiment + * @param subscription + */ + @Override + public void removeVariableValueSubscription(VariableValueSubscription subscription) { + assert subscription != null; + synchronized (variableValueSubscriptions) { + //System.out.println("REMOVE listener " + subscription); + variableValueSubscriptions.remove(subscription); + variableValueSubscriptionsSnapshot = null; + } + } + + @SuppressWarnings("rawtypes") + /** + * Copy from AprosExperiment + * @return + */ + @Override + public VariableValueSubscription[] getListenerSnapshot() { + VariableValueSubscription[] snapshot = variableValueSubscriptionsSnapshot; + if (snapshot == null) { + synchronized (variableValueSubscriptions) { + snapshot = variableValueSubscriptionsSnapshot; + if (snapshot == null) { + snapshot = variableValueSubscriptionsSnapshot = variableValueSubscriptions.toArray(new VariableValueSubscription[variableValueSubscriptions.size()]); + } + } + //System.out.println("listener count: " + snapshot.length); + } + return snapshot; + } + + volatile long previousVariableUpdateTime = 0; + volatile boolean skippedVariableUpdate = true; + + + /** + * Modified copy from AprosExperiment + */ + public void resultsChanged() { + resultsChanged(false); + } + + public void setPublishResults(boolean value) { + publishResults = value; + if(publishResults) resultsChanged(true); + } + + public void resultsChanged(boolean force) { + long time = System.nanoTime(); + long sinceLast = time - previousVariableUpdateTime; +// System.err.println("sinceLast " + 1e-9*sinceLast); + if(sinceLast > 100000000 || force) { + updateSubscriptions(); + previousVariableUpdateTime = time; + } + else + skippedVariableUpdate = true; + } + + @SuppressWarnings("rawtypes") + /** + * Modified copy from AporsExperiment + */ + @Override + public void updateSubscriptions() { + if(!publishResults) return; + for(VariableValueSubscription subscription : getListenerSnapshot()) + subscription.update(); + skippedVariableUpdate = false; + } + + public int numberOfSimulationRunSteps() { + /* + * 1. Write modelica files + * 2. Write other simulation files + * 3. Build model OR update parameters + * 4. Run modelica + * 5. Read results + */ + return 5; + } + + + /* Experiment methods that are not used in this experiment */ + + @Override + public Lock getDatasourceLock() { + return null; + } + + @Override + public Datasource getDatasource() { + return null; + } + + @Override + public void simulateDuration(double duration) { + System.out.println("simulateDuartion"); + } + + + @Override + public void rewindTo(double time) { + System.out.println("rewindTo"); + } + +} + diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SaveResultJob.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SaveResultJob.java new file mode 100644 index 00000000..38a87e6c --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SaveResultJob.java @@ -0,0 +1,126 @@ +/******************************************************************************* + * Copyright (c) 2010, 2013 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + * Semantum Oy - Bug #4180 + *******************************************************************************/ +package org.simantics.sysdyn.manager; + +import java.io.File; +import java.util.UUID; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.Session; +import org.simantics.db.WriteGraph; +import org.simantics.db.common.request.WriteRequest; +import org.simantics.db.common.utils.NameUtils; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.request.Read; +import org.simantics.layer0.Layer0; +import org.simantics.layer0.utils.direct.GraphUtils; +import org.simantics.sysdyn.SysdynResource; + +/** + * Class for saving simulation results. + * @author Tuomas Miettinen + * + */ +public class SaveResultJob extends Job { + + private final MemoryResult sysdynResult; + private final OldSysdynExperiment experiment; + private final Session session; + private IProgressMonitor monitor; + private File file; + + public SaveResultJob(final OldSysdynExperiment experiment, Session session, final MemoryResult result) { + super("Save Result"); + this.experiment = experiment; + this.sysdynResult = result; + this.session = session; + } + + @Override + protected IStatus run(IProgressMonitor monitor) { + this.monitor = monitor; + int resultItemsNumber = sysdynResult.numberOfVariables(); + monitor.beginTask("Save result", resultItemsNumber * 2 + 1); + try { + // Create result file + file = session.syncRequest(new Read() { + + @Override + public File perform(ReadGraph graph) throws DatabaseException { + Layer0 l0 = Layer0.getInstance(graph); + Resource model = graph.getSingleObject(experiment.getResource(), l0.PartOf); + Resource project = graph.getSingleObject(model, l0.PartOf); + String projectName = graph.getPossibleRelatedValue(project, l0.HasName); + File root = new File(Platform.getLocation().toOSString(), "www.simantics.org"); + if(!root.isDirectory()) root.mkdir(); + File projectRoot = new File(root, projectName); + if(!projectRoot.isDirectory()) projectRoot.mkdir(); + File file = new File(projectRoot, UUID.randomUUID().toString() + ".dbb"); + return file; + } + }); + + // Start the saving operation + Thread saveThread = experiment.getSaveThread(sysdynResult, file, SaveResultJob.this.monitor); + saveThread.run(); + + // Add the result under the experiment within the model browser. + session.syncRequest(new WriteRequest() { + + @Override + public void perform(WriteGraph graph) throws DatabaseException { + Layer0 l0 = Layer0.getInstance(graph); + Resource model = graph.getSingleObject(experiment.getResource(), l0.PartOf); + String name = NameUtils.findFreshName(graph, "Result", model, l0.ConsistsOf, "%s%d"); + + SysdynResource sr = SysdynResource.getInstance(graph); + Resource res = GraphUtils.create2(graph, sr.Result, + l0.HasLabel, name, + l0.HasName, name, + l0.PartOf, model, + sr.Result_resultFile, file.getAbsolutePath(), + sr.Result_time, System.currentTimeMillis()); + graph.claim(experiment.getResource(), sr.Experiment_result, res); + } + }); + + } catch (DatabaseException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + return new Status( + Status.ERROR, + "org.simantics.sysdyn.ui", + "Save results failed: \n" + e.getMessage()); + } + monitor.done(); + return Status.OK_STATUS; + } + + @Override + public boolean belongsTo(Object family) { + return "SaveResultJob".equals(family); + } + + @Override + protected void canceling() { + + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SaveResultSetJob.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SaveResultSetJob.java new file mode 100644 index 00000000..ea2f9e62 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SaveResultSetJob.java @@ -0,0 +1,153 @@ +/******************************************************************************* + * Copyright (c) 2010, 2013 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.manager; + +import java.io.File; +import java.util.ArrayList; +import java.util.UUID; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.Session; +import org.simantics.db.WriteGraph; +import org.simantics.db.common.request.WriteRequest; +import org.simantics.db.common.request.WriteResultRequest; +import org.simantics.db.common.utils.NameUtils; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.request.Read; +import org.simantics.layer0.Layer0; +import org.simantics.layer0.utils.direct.GraphUtils; +import org.simantics.sysdyn.SysdynResource; + +/** + * Class for saving simulation result sets. + * @author Tuomas Miettinen + * + */ +public class SaveResultSetJob extends Job { + + private final ArrayList sysdynResults; + private final OldSysdynExperiment experiment; + private final Session session; + private IProgressMonitor monitor; + private File file; + + public SaveResultSetJob(final OldSysdynExperiment experiment, Session session, final ArrayList results) { + super("Save Results"); + this.experiment = experiment; + this.sysdynResults = results; + this.session = session; + } + + @Override + protected IStatus run(IProgressMonitor monitor) { + this.monitor = monitor; + if (sysdynResults == null || sysdynResults.size() == 0) + return Status.CANCEL_STATUS; + int resultItemsNumber = sysdynResults.get(0).numberOfVariables() * sysdynResults.size(); + monitor.beginTask("Save results", resultItemsNumber * 2 + 2); + + try { + // Create a ResultSet, under which the individual results are stored, and + // add it under the experiment within the model browser. + + final Resource resultSetResource = session.syncRequest(new WriteResultRequest() { + + @Override + public Resource perform(WriteGraph graph) throws DatabaseException { + Layer0 l0 = Layer0.getInstance(graph); + Resource model = graph.getSingleObject(experiment.getResource(), l0.PartOf); + String name = NameUtils.findFreshName(graph, "ResultSet", model, l0.ConsistsOf, "%s%d"); + + SysdynResource sr = SysdynResource.getInstance(graph); + Resource res = GraphUtils.create2(graph, sr.ResultSet, + l0.HasLabel, name, + l0.HasName, name, + l0.PartOf, model, + sr.Result_time, System.currentTimeMillis()); + graph.claim(experiment.getResource(), sr.Experiment_resultSet, res); + return res; + } + }); + monitor.worked(1); + + // Save the individual results + for (int i = 0; i < sysdynResults.size(); ++i) { + MemoryResult result = sysdynResults.get(i); + final String name = new Integer(i+1).toString(); + // Create result file + file = session.syncRequest(new Read() { + + @Override + public File perform(ReadGraph graph) throws DatabaseException { + Layer0 l0 = Layer0.getInstance(graph); + Resource model = graph.getSingleObject(experiment.getResource(), l0.PartOf); + Resource project = graph.getSingleObject(model, l0.PartOf); + String projectName = graph.getPossibleRelatedValue(project, l0.HasName); + File root = new File(Platform.getLocation().toOSString(), "www.simantics.org"); + if(!root.isDirectory()) root.mkdir(); + File projectRoot = new File(root, projectName); + if(!projectRoot.isDirectory()) projectRoot.mkdir(); + File file = new File( projectRoot, UUID.randomUUID().toString() + ".dbb"); + return file; + } + }); + + // Start the saving operation + Thread saveThread = experiment.getSaveThread(result, file, SaveResultSetJob.this.monitor); + saveThread.run(); + + // Add the result under the ResultSet within the model browser. + session.syncRequest(new WriteRequest() { + + @Override + public void perform(WriteGraph graph) throws DatabaseException { + Layer0 l0 = Layer0.getInstance(graph); + String resultSetName = graph.getRelatedValue(resultSetResource, l0.HasName); + + SysdynResource sr = SysdynResource.getInstance(graph); + Resource res = GraphUtils.create2(graph, sr.Result, + l0.HasLabel, name, + l0.HasName, resultSetName + "#" + name, + sr.Result_resultFile, file.getAbsolutePath(), + sr.Result_time, System.currentTimeMillis()); + graph.claim(resultSetResource, sr.Experiment_result, res); + } + }); + + } + + } catch (DatabaseException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + monitor.done(); + return Status.OK_STATUS; + } + + @Override + public boolean belongsTo(Object family) { + return "SaveResultSetJob".equals(family); + } + + @Override + protected void canceling() { + + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SimulateDurationJob.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SimulateDurationJob.java new file mode 100644 index 00000000..defe0698 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SimulateDurationJob.java @@ -0,0 +1,102 @@ +package org.simantics.sysdyn.manager; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; +import org.simantics.simulation.experiment.ExperimentState; +import org.simantics.sysdyn.solver.ISolver; + +class SimulateDurationJob extends Job { + + private boolean canceled = false; + private double duration; + private final SysdynGameExperimentBase base; + private final ISolver solver; + + public SimulateDurationJob(SysdynGameExperimentBase base, String name, double duration) { + super(name); + this.base = base; + this.solver = base.getSolver(); + this.duration = duration; + } + + @Override + protected void canceling() { + canceled = true; + } + + @Override + protected IStatus run(IProgressMonitor monitor) { + if(base == null || base.getState() != ExperimentState.STOPPED) + return Status.OK_STATUS; + + long start = System.nanoTime(); + + base.changeState(ExperimentState.RUNNING); + int nSteps = (int)(duration / base.stepLength); + int work = 1 + nSteps * 3 + 2; // initialization + number of steps * number of phases per step + set result + call result listeners + + monitor.beginTask("Simulating " + duration + " time steps", work); + monitor.subTask("Initialize step simulation"); + + if(base.subscription == null || base.results == null) + return Status.OK_STATUS; + + if(duration <= 0.0) + duration = base.stepDuration; + + + try { + + solver.prepareToStep(); + + double time = solver.getTime(); + double eTime = time + duration; + + monitor.worked(1); + + base.setSubscribedResults(monitor, time); + + int stepNumber = 1; + while((eTime - time > base.stepLength * 1e-6) && !canceled) { + + if(eTime - time < base.stepLength) + solver.setStepLength(eTime - time); + + monitor.subTask("Simulate step (time = " + time + ")"); + solver.simulateStep(); + monitor.worked(1); + + time = solver.getTime(); + + if(stepNumber % base.savePer == 0) { + base.setSubscribedResults(monitor, time); + } else { + monitor.worked(1); + } + stepNumber++; + monitor.worked(1); + + } + + monitor.subTask("Display results"); + ((MemoryResult)base.getCurrentResult()).setResult(new GameResult(base, base.results, base.subscription)); + monitor.worked(1); + + base.resultsChanged(true); + monitor.worked(1); + base.changeState(ExperimentState.STOPPED); + + } catch (Exception e) { + e.printStackTrace(); + System.err.println("SysdynGameExperiment simulateDuration failed: \n\t" + e.getMessage()); + } + + long end = System.nanoTime(); +// System.err.println("simulate duration took " + 1e-6*(end-start) + "ms."); + + return Status.OK_STATUS; + + } +} \ No newline at end of file diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynConsole.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynConsole.java new file mode 100644 index 00000000..3d20128c --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynConsole.java @@ -0,0 +1,205 @@ +package org.simantics.sysdyn.manager; + +import java.text.SimpleDateFormat; +import java.util.Calendar; + +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.console.ConsolePlugin; +import org.eclipse.ui.console.IConsole; +import org.eclipse.ui.console.IConsoleManager; +import org.eclipse.ui.console.IHyperlink; +import org.eclipse.ui.console.IPatternMatchListener; +import org.eclipse.ui.console.MessageConsole; +import org.eclipse.ui.console.MessageConsoleStream; +import org.eclipse.ui.console.PatternMatchEvent; +import org.eclipse.ui.console.TextConsole; +import org.simantics.sysdyn.solver.ISolverMonitor; + +public class SysdynConsole implements ISolverMonitor { + + private static String SYSDYN_CONSOLE = "Sysdyn modelica console"; + private MessageConsole console; + + public static SysdynConsole INSTANCE = new SysdynConsole(); + + public SysdynConsole() { + ConsolePlugin plugin = ConsolePlugin.getDefault(); + IConsoleManager conMan = plugin.getConsoleManager(); + IConsole[] existing = conMan.getConsoles(); + for (int i = 0; i < existing.length; i++) + if (existing[i].getName().equals(SYSDYN_CONSOLE)) + console = (MessageConsole) existing[i]; + if(console == null) { + MessageConsole myConsole = new MessageConsole(SYSDYN_CONSOLE, null); + conMan.addConsoles(new IConsole[]{myConsole}); + console = myConsole; + console.addPatternMatchListener(new IPatternMatchListener() { + + @Override + public void matchFound(PatternMatchEvent event) { + try { + console.addHyperlink(new IssueLink(), event.getOffset(), event.getLength()); + } catch (BadLocationException e) { + e.printStackTrace(); + } + } + + @Override + public void disconnect() { + } + + @Override + public void connect(TextConsole console) { + } + + @Override + public String getPattern() { + + return "Issues view"; + } + + @Override + public String getLineQualifier() { + return null; + } + + @Override + public int getCompilerFlags() { + return 0; + } + }); + + /* Link to the modelica document: to be opened to a modelica code viewer. + console.addPatternMatchListener(new IPatternMatchListener() { + + @Override + public void matchFound(PatternMatchEvent event) { + try { + if(event.getSource() instanceof MessageConsole) { + MessageConsole console = (MessageConsole) event.getSource(); + IDocument document = console.getDocument(); + String s = document.get(event.getOffset(), event.getLength()); + s = s.substring(s.indexOf(":") + 1, s.lastIndexOf(":")); + String[] split = s.split(":|-"); + + //TODO: Find the modelica document and its locations + int startOffset = modelicaDocument.getLineOffset(Integer.parseInt(split[0])) + Integer.parseInt(split[1]); + int endOffset = modelicaDocument.getLineOffset(Integer.parseInt(split[2])) + Integer.parseInt(split[3]); + System.out.println("Open modelica editor for model at: " + startOffset + ", " + (endOffset - startOffset)); + + } + + console.addHyperlink(new ModelicaLink(), event.getOffset(), event.getLength()); + } catch (BadLocationException e) { + e.printStackTrace(); + } + } + + @Override + public void disconnect() { + } + + @Override + public void connect(TextConsole console) { + } + + @Override + public String getPattern() { + return "\\[[^\\[]*:[\\d]*:[\\d]*\\-[\\d]*:[\\d]*:writable\\]"; + + } + + @Override + public String getLineQualifier() { + return null; + } + + @Override + public int getCompilerFlags() { + return 0; + } + }); + */ + + + } + } + + @Override + public void message(String message) { + message(message, "hh:mm:ss"); + } + + /** + * Print message to a console with a specified time stamp format + * + * @param message the message to be printed + * @param timeStampFormat simpledateformat timestamp format. null if no timestamp wanted + */ + public void message(String message, String timeStampFormat) { + Calendar cal = Calendar.getInstance(); + SimpleDateFormat sdf = new SimpleDateFormat(timeStampFormat); + String time = sdf.format(cal.getTime()); + + MessageConsoleStream out = this.console.newMessageStream(); + if(message.length() > 1) + out.println("[" + time +"] " + message); + + + + if(message.contains("Error")) { + showConsole(); + out.println("See Issues view"); + } + } + + public void clearConsole() { + this.console.clearConsole(); + } + + public void showConsole() { + ConsolePlugin plugin = ConsolePlugin.getDefault(); + IConsoleManager conMan = plugin.getConsoleManager(); + conMan.showConsoleView(console); + } + + class IssueLink implements IHyperlink { + + @Override + public void linkEntered() { + } + + @Override + public void linkExited() { + } + + @Override + public void linkActivated() { + try { + PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("org.simantics.issues.ui.issueview2"); + } catch (PartInitException e) { + e.printStackTrace(); + } + } + } + + class ModelicaLink implements IHyperlink { + + @Override + public void linkEntered() { + } + + @Override + public void linkExited() { + } + + @Override + public void linkActivated() { + System.err.println("MODELICA LINK"); + } + + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynDataSet.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynDataSet.java new file mode 100644 index 00000000..a98ad679 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynDataSet.java @@ -0,0 +1,38 @@ +/******************************************************************************* + * Copyright (c) 2010 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.manager; + +import org.simantics.modelica.data.DataSet; + +/** + * Extension for the basic Modelica result {@link DataSet} containing also an optional result name. + * + * @author Teemu Lempinen + * + */ +public class SysdynDataSet extends DataSet { + + public String result; // Name of the result file if this is not the result of the current simulation + public Integer resultIndex = null; + + public SysdynDataSet(String name, String result, double[] times, double[] values, Integer resultIndex) { + super(name, times, values); + this.result = result; + this.resultIndex = resultIndex; + } + + public SysdynDataSet(String name, String result, double[] times, double[] values) { + super(name, times, values); + this.result = result; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiment.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiment.java new file mode 100644 index 00000000..54f8aa28 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiment.java @@ -0,0 +1,451 @@ +/******************************************************************************* + * Copyright (c) 2010, 2013 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + * Semantum Oy - Bug #4180 + *******************************************************************************/ +package org.simantics.sysdyn.manager; + +import gnu.trove.set.hash.THashSet; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.locks.Lock; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.simantics.db.ReadGraph; +import org.simantics.db.RequestProcessor; +import org.simantics.db.Resource; +import org.simantics.db.Session; +import org.simantics.db.VirtualGraph; +import org.simantics.db.WriteGraph; +import org.simantics.db.common.request.ReadRequest; +import org.simantics.db.common.request.WriteRequest; +import org.simantics.db.common.utils.NameUtils; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.service.VirtualGraphSupport; +import org.simantics.layer0.Layer0; +import org.simantics.simulation.data.Datasource; +import org.simantics.simulation.experiment.Experiment; +import org.simantics.simulation.experiment.ExperimentState; +import org.simantics.simulation.experiment.IDynamicExperiment; +import org.simantics.simulation.experiment.IExperimentListener; +import org.simantics.simulation.ontology.SimulationResource; +import org.simantics.sysdyn.Activator; +import org.simantics.sysdyn.adapter.VariableValueSubscription; +import org.simantics.sysdyn.solver.SysdynSimulationJob; +import org.simantics.sysdyn.solver.SolverSettings; +import org.simantics.sysdyn.solver.SolverSettings.SolverType; + +public class SysdynExperiment extends Experiment implements IDynamicExperiment, VariableSubscriptionManager { + + // TODO: change to protected as necessary when oldSysdynExperiment is removed + + private Session session; + private Runnable modificationListener; + public SysdynModel sysdynModel; + private boolean toggled = false; + + @SuppressWarnings("rawtypes") + private THashSet variableValueSubscriptions = new THashSet(); + @SuppressWarnings("rawtypes") + private VariableValueSubscription[] variableValueSubscriptionsSnapshot = null; + + private Process process; + private boolean canceled = false; + private ExperimentState sysdynExperimentState; + + private SysdynResult result; + + private String experimentName; + private File experimentDir; + + public SysdynExperiment(Resource experiment, Resource model) { + super(experiment, model); + this.experimentName = "Experiment"; + this.experimentDir = null; + } + + public SysdynResult getCurrentResult() { + if(this.result == null) + this.result = new MemoryResult(null, null); + return this.result; + } + + public void setCurrentResult(SysdynResult result) { + this.result = result; + } + + public Collection getActiveResults() { + ArrayList result = new ArrayList(); + if(getCurrentResult() != null) + result.add(getCurrentResult()); + result.addAll(sysdynModel.getDisplayedResults()); + return result; + } + + /** + * Initialize this experiment + * @param g ReadGraph + */ + public void init(ReadGraph g) { + try { + this.experimentName = NameUtils.getSafeName(g, experiment); + } catch (DatabaseException e) { + this.experimentName = "Experiment"; + } + + this.session = g.getSession(); + state = ExperimentState.STOPPED; + for(IExperimentListener listener : listeners.getListeners()) + listener.stateChanged(state); + + session.asyncRequest(new ReadRequest() { + + @Override + public void run(ReadGraph graph) throws DatabaseException { + final Resource configuration = graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration); + sysdynModel = SysdynModelManager.getInstance(session).getModel(graph, configuration); + toggleActivation(graph, true); + } + }); + + setSysdynExperimentState(ExperimentState.INITIALIZING); + } + + @Override + public void saveState() { + if(result == null || !(result instanceof MemoryResult)) + return; + // TODO: fix this + //SaveResultJob saveResultJob = new SaveResultJob(AltSysdynExperiment.this, session, result); + //saveResultJob.schedule(); + } + + protected Thread getSaveThread(final SysdynResult result, final File file, final IProgressMonitor progressMonitor) { + return new Thread() { + @Override + public void run() { + if(!canceled) { + // Get and store results result.saveToFile(file, progressMonitor); + } } + }; + } + + @Override + public void simulate(boolean enabled) { + // TODO: add state checks + if (enabled) { + SysdynSimulationJob job = new SysdynSimulationJob(sysdynModel.getConfiguration().getLabel(), this); + job.schedule(); + } + } + + /** + * Destroy an ongoing simulation process + */ + public void cancelSimulation() { + canceled = true; + if(process != null) { + process.destroy(); + } + } + + /** + * Toggle simulation state + * @param enabled true == RUNNING, false == STOPPED + */ + public void toggleSimulation(boolean enabled) { + if(enabled) { + this.toggled = true; + changeState(ExperimentState.RUNNING); + if(modificationListener == null) { + + modificationListener = new Runnable() { + + @Override + public void run() { + session.asyncRequest(new ReadRequest() { + + @Override + public void run(ReadGraph graph) throws DatabaseException { + if(getState() == ExperimentState.RUNNING) { + // TODO: fix this + //SimulationScheduler.start(sysdynModel, this); + } + + } + }); + + }; + }; + sysdynModel.addModificationListener(modificationListener); + } + } + else { + changeState(ExperimentState.STOPPED); + this.toggled = false; + } + + } + + @Override + public void refresh(RequestProcessor session) { + session.asyncRequest(new ReadRequest() { + + @Override + public void run(ReadGraph graph) throws DatabaseException { + init(graph); + } + + }); + } + + @Override + public void refresh(Session session) { + refresh((RequestProcessor)session); + } + + @Override + protected void localStateChange() { + setSysdynExperimentState(getState()); + switch(state) { + case DISPOSED: + onExperimentDisposed(); + break; + default: + break; + } + + } + + /** + * Returns sysdyn experiment state. It is usually the same as ordinary experiment state. + * Initializing phase takes longer than normally in game experiments. + * @return + */ + public ExperimentState getSysdynExperimentState() { + return sysdynExperimentState; + } + + protected void setSysdynExperimentState(final ExperimentState state) { + sysdynExperimentState = state; + session.asyncRequest(new ReadRequest() { + + @Override + public void run(ReadGraph graph) throws DatabaseException { + VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class); + final Session session = graph.getSession(); + session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("experiments")) { + @Override + public void perform(WriteGraph graph) throws DatabaseException { + Layer0 L0 = Layer0.getInstance(graph); + SimulationResource SR = SimulationResource.getInstance(graph); + graph.deny(model, SR.HasExperimentState); + graph.deny(experiment, SR.HasExperimentState); + + Resource st = graph.newResource(); + switch(state) { + case INITIALIZING: + graph.claim(st, L0.InstanceOf, SR.ExperimentState_Initializing); + break; + case RUNNING: + graph.claim(st, L0.InstanceOf, SR.ExperimentState_Running); + break; + case STOPPED: + graph.claim(st, L0.InstanceOf, SR.ExperimentState_Stopped); + break; + case DISPOSED: + graph.claim(st, L0.InstanceOf, SR.ExperimentState_Disposed); + break; + } + + graph.claim(model, SR.HasExperimentState, st); + graph.claim(experiment, SR.HasExperimentState, st); + }}); + } + }); + } + + /** + * Actions performed when experiment is disposed + * @param graph + */ + protected void onExperimentDisposed() { + cancelSimulation(); + sysdynModel.removeModificationListener(modificationListener); + modificationListener = null; + + session.asyncRequest(new ReadRequest() { + @Override + public void run(ReadGraph graph) throws DatabaseException { + toggleActivation(graph, false); + } + }); + } + + + /** + * Toggles the active-state of this experiment on or off + * @param graph ReadGraph + * @param activate The active-state of this experiment + */ + protected void toggleActivation(ReadGraph graph, final boolean activate) { + // TODO: does not work correctly, the experiment can appear inactive even when it is actually active + VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class); + final Session session = graph.getSession(); + session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("experiments")) { + @Override + public void perform(WriteGraph graph) throws DatabaseException { + VirtualGraph runtime = graph.getService(VirtualGraph.class); + + session.asyncRequest(new WriteRequest(runtime) { + + @Override + public void perform(WriteGraph graph) throws DatabaseException { + SimulationResource SIMU = SimulationResource.getInstance(graph); + if(activate) + graph.claim(experiment, SIMU.IsActive, experiment); + else + graph.denyStatement(experiment, SIMU.IsActive, experiment); + } + + }); + } + }); + } + + + /* Result subscriptions */ + + @SuppressWarnings("rawtypes") + /** + * Copy from AprosExperiment + * @param subscription + */ + @Override + public void addVariableValueSubscription(VariableValueSubscription subscription) { + assert subscription != null; + synchronized (variableValueSubscriptions) { + variableValueSubscriptions.add(subscription); + variableValueSubscriptionsSnapshot = null; + } + } + + @SuppressWarnings("rawtypes") + /** + * Copy from AprosExperiment + * @param subscription + */ + @Override + public void removeVariableValueSubscription(VariableValueSubscription subscription) { + assert subscription != null; + synchronized (variableValueSubscriptions) { + variableValueSubscriptions.remove(subscription); + variableValueSubscriptionsSnapshot = null; + } + } + + @SuppressWarnings("rawtypes") + /** + * Copy from AprosExperiment + * @return + */ + @Override + public VariableValueSubscription[] getListenerSnapshot() { + VariableValueSubscription[] snapshot = variableValueSubscriptionsSnapshot; + if (snapshot == null) { + synchronized (variableValueSubscriptions) { + snapshot = variableValueSubscriptionsSnapshot; + if (snapshot == null) { + snapshot = variableValueSubscriptionsSnapshot = + variableValueSubscriptions.toArray(new VariableValueSubscription[variableValueSubscriptions.size()]); + } + } + } + return snapshot; + } + + volatile long previousVariableUpdateTime = 0; + + /** + * Modified copy from AprosExperiment + */ + public void resultsChanged() { + long time = System.nanoTime(); + if (time - previousVariableUpdateTime > 10000000) { + updateSubscriptions(); + previousVariableUpdateTime = time; + } + } + + @SuppressWarnings("rawtypes") + /** + * Modified copy from AporsExperiment + */ + @Override + public void updateSubscriptions() { + for(VariableValueSubscription subscription : getListenerSnapshot()) + subscription.update(); + } + + /* Experiment methods that are not used in this experiment */ + + @Override + public Lock getDatasourceLock() { + throw new UnsupportedOperationException(); + } + + @Override + public Datasource getDatasource() { + throw new UnsupportedOperationException(); + } + + @Override + public void simulateDuration(double duration) { + throw new UnsupportedOperationException(); + } + + @Override + public void rewindTo(double time) { + throw new UnsupportedOperationException(); + } + + + + // TODO: clean this up a bit maybe? + public File getExperimentDir() { + if (experimentDir == null) { + File modelsDir = Activator.getBundleContext().getDataFile("models"); + String name = experimentName; + List files = Arrays.asList(modelsDir.list()); + if (files.contains(name)) { + int i = 2; + while (files.contains(name + "_" + i)){ + i++; + } + name += "_" + i; + } + experimentDir = new File(modelsDir, name); + experimentDir.mkdir(); + } + + return experimentDir; + } + + public SolverType getSolverType() { + // should be defined in experiment properties (similarly to other experiment types) + return SolverSettings.getSelectedSolverType(); + } + +} + diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiments.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiments.java new file mode 100644 index 00000000..20f90f3c --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiments.java @@ -0,0 +1,300 @@ +package org.simantics.sysdyn.manager; + +import java.util.Collection; +import java.util.concurrent.Semaphore; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.SubMonitor; +import org.simantics.Simantics; +import org.simantics.databoard.Bindings; +import org.simantics.databoard.binding.mutable.Variant; +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.WriteGraph; +import org.simantics.db.common.request.ObjectsWithType; +import org.simantics.db.common.utils.NameUtils; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.util.Layer0Utils; +import org.simantics.db.layer0.util.RemoverUtil; +import org.simantics.db.layer0.variable.RVI; +import org.simantics.db.layer0.variable.Variable; +import org.simantics.db.layer0.variable.Variables; +import org.simantics.layer0.Layer0; +import org.simantics.modeling.ModelingResources; +import org.simantics.modeling.PartialIC; +import org.simantics.project.IProject; +import org.simantics.simulation.experiment.ExperimentState; +import org.simantics.simulation.experiment.IDynamicExperiment; +import org.simantics.simulation.experiment.IExperiment; +import org.simantics.simulation.model.ExperimentLoadingFailed; +import org.simantics.simulation.project.IExperimentActivationListener; +import org.simantics.simulation.project.IExperimentManager; +import org.simantics.sysdyn.SysdynResource; +import org.simantics.utils.DataContainer; + +public class SysdynExperiments { + + public static void setPublishResults(ReadGraph graph, Variable variable, boolean value) throws DatabaseException { + + final IProject project = Simantics.getProject(); + if (project == null) return; + + final IExperimentManager experimentManager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER); + if(experimentManager == null) return; + + IExperiment exp = experimentManager.getExperiment(variable.getName(graph)); + if(exp instanceof OldSysdynExperiment) { + OldSysdynExperiment experiment = (OldSysdynExperiment)exp; + experiment.setPublishResults(value); + } + + } + + public static String activateExperiment(IProgressMonitor monitor, final IProject project, final IExperimentManager manager, final Resource experimentResource) { + + if(monitor == null) monitor = new NullProgressMonitor(); + + final SubMonitor mon = SubMonitor.convert(monitor, "Activating experiment", 100000); + +// SysdynExperimentManagerListener.listenManager(manager); + IExperiment[] experiments = manager.getExperiments(); + SubMonitor shutdownMon = mon.newChild(10000); + int workPerExperiment; + if (experiments.length > 0) + workPerExperiment = 10000 / experiments.length; + else + workPerExperiment = 10000; + for(IExperiment e : experiments) + if(e.getState() != ExperimentState.DISPOSED) + e.shutdown(shutdownMon.newChild(workPerExperiment)); + mon.setWorkRemaining(90000); + + final Semaphore activated = new Semaphore(0); + final DataContainer problem = new DataContainer(); + final DataContainer run = new DataContainer(); + manager.startExperiment(experimentResource, new IExperimentActivationListener() { + + @Override + public void onExperimentActivated(final IExperiment experiment) { +// MessageService.defaultLog(new org.eclipse.core.runtime.Status(IStatus.INFO, "org.simantics.simulation.ui", 0, "Activated experiment " + experiment.getIdentifier() , null)); + activated.release(); + run.set(experiment); + } + @Override + public void onFailure(Throwable e) { + problem.set(e); + activated.release(); + } + @Override + public void onMessage(IStatus message) { +// MessageService.getDefault().log(message); + } + @Override + public IProgressMonitor getProgressMonitor() { + return mon; + } + }, true); + try { + activated.acquire(); + Throwable t = problem.get(); + if (t != null) { + if (t instanceof ExperimentLoadingFailed) { +// ErrorLogger.defaultLogError(t); +// ShowMessage.showError("Experiment Activation Failed", t.getMessage()); + } else { +// ExceptionUtils.logAndShowError(t); + } + } + + return run.get().getIdentifier(); + //return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Experiment activation failed, see exception for details.", problem.get()); + } catch (InterruptedException e) { + return null; + } + } + + + public static String activateExperiment(Resource experiment) throws DatabaseException { + +// Resource experiment = Layer0Utils.getPossibleChild(graph, model, name); +// if( experiment == null) return false; + +// SimulationResource SIMU = SimulationResource.getInstance(graph); +// if (!graph.isInstanceOf(experiment, SIMU.Experiment)) return false; + + final IProject project = Simantics.getProject(); + if (project == null) return null; + + final IExperimentManager experimentManager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER); + if(experimentManager == null) return null; + + return SysdynExperiments.activateExperiment(null, project, experimentManager, experiment); + + } + + public static void run(String experimentId) throws DatabaseException { + + final IProject project = Simantics.getProject(); + if (project == null) return; + + final IExperimentManager experimentManager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER); + if(experimentManager == null) return; + + IExperiment experiment = experimentManager.getExperiment(experimentId); + if(experiment instanceof IDynamicExperiment) + ((IDynamicExperiment)experiment).simulate(true); + + } + + private static void processChild(ReadGraph graph, Variable child, PartialIC IC) throws DatabaseException { + + System.err.println("processChild " + child.getURI(graph)); + + for(Variable c : child.getChildren(graph)) { + processChild(graph, c, IC); + } + Variable values = child.getPossibleProperty(graph, "values"); + if(values == null) return; + + Resource represents = child.getPossibleRepresents(graph); + if(represents == null) return; + + Layer0 L0 = Layer0.getInstance(graph); + SysdynResource SYSDYN = SysdynResource.getInstance(graph); + + Collection exprs = graph.syncRequest(new ObjectsWithType(represents, L0.ConsistsOf, SYSDYN.ParameterExpression)); + if(exprs.size() == 0) return; + + Variable v = values.getPossibleProperty(graph, ""); + if(v == null) return; + double[][] vs = v.getValue(graph); + Variable value = child.getPossibleProperty(graph, "value"); + if(value == null) return; + for(int i=0;i 0) { + RVI rvi = target.getRVI(graph); + double initial = ds[0]; + System.err.println("rvi=" + rvi + " value=" + initial); + IC.add(rvi, Variant.ofInstance(initial)); + } + } + } + + public static Resource saveIC(WriteGraph graph, Variable input) throws DatabaseException { + Layer0 L0 = Layer0.getInstance(graph); + Resource model = Variables.getModel(graph, input); + String name = NameUtils.findFreshName(graph, "IC", model, L0.ConsistsOf); + return saveIC(graph, input, name); + } + + public static Resource saveIC(WriteGraph graph, Variable input, String name) throws DatabaseException { + graph.markUndoPoint(); + Resource model = Variables.getModel(graph, input); + Resource child = Layer0Utils.getPossibleChild(graph, model, name); + SysdynResource SYSDYN = SysdynResource.getInstance(graph); + + if(child != null) { + if(graph.isInstanceOf(child, SYSDYN.InitialCondition)) { + RemoverUtil.remove(graph, child); + } else { + return null; + } + } + + PartialIC IC = new PartialIC(); + processChild(graph, input, IC); + + Layer0 L0 = Layer0.getInstance(graph); + ModelingResources MOD = ModelingResources.getInstance(graph); + Resource ic = graph.newResource(); + graph.claim(ic, L0.InstanceOf, SYSDYN.InitialCondition); + graph.addLiteral(ic, L0.HasName, L0.NameOf, L0.String, name, Bindings.STRING); + graph.addLiteral(ic, SYSDYN.InitialCondition_HasInitialValues, SYSDYN.InitialCondition_HasInitialValues_Inverse, MOD.PartialIC, IC, PartialIC.BINDING); + graph.claim(model, L0.ConsistsOf, ic); + + Layer0Utils.addCommentMetadata(graph, "Saved new Initial Condition " + name + " " + ic); + return ic; + + } + + public static void assignIC(WriteGraph graph, Variable experiment, String name) throws DatabaseException { + graph.markUndoPoint(); + System.err.println("assignIC " + experiment.getURI(graph)); + + Layer0 L0 = Layer0.getInstance(graph); + SysdynResource SYSDYN = SysdynResource.getInstance(graph); + + Resource run = experiment.getPossibleRepresents(graph); + if(run == null) return; + Resource exp = graph.getPossibleObject(run, L0.PartOf); + if(exp == null) return; + + Resource model = Variables.getModel(graph, experiment); + Resource ic = Layer0Utils.getPossibleChild(graph, model, name); + if(ic == null) return; + + if(!graph.isInstanceOf(ic, SYSDYN.InitialCondition)) return; + + graph.deny(exp, SYSDYN.Experiment_ic); + graph.claim(exp, SYSDYN.Experiment_ic, ic); + Layer0Utils.addCommentMetadata(graph, "Assigned Initial Condition " + graph.getRelatedValue2(ic, L0.HasName, Bindings.STRING) + " to experiment " + graph.getRelatedValue2(exp, L0.HasName, Bindings.STRING)); + } + + public static void deassignIC(WriteGraph graph, Variable experiment) throws DatabaseException { + + System.err.println("deassignIC " + experiment.getURI(graph)); + + Layer0 L0 = Layer0.getInstance(graph); + SysdynResource SYSDYN = SysdynResource.getInstance(graph); + + Resource run = experiment.getPossibleRepresents(graph); + if(run == null) return; + Resource exp = graph.getPossibleObject(run, L0.PartOf); + if(exp == null) return; + + graph.deny(exp, SYSDYN.Experiment_ic); + + } + + public static void applyIC(WriteGraph graph, Variable experiment, String name) throws DatabaseException { + + System.err.println("applyIC " + experiment.getURI(graph)); + + Layer0 L0 = Layer0.getInstance(graph); + SysdynResource SYSDYN = SysdynResource.getInstance(graph); + + Resource run = experiment.getPossibleRepresents(graph); + if(run == null) return; + Resource exp = graph.getPossibleObject(run, L0.PartOf); + if(exp == null) return; + + Resource model = Variables.getModel(graph, experiment); + Resource ic = Layer0Utils.getPossibleChild(graph, model, name); + if(ic == null) return; + + if(!graph.isInstanceOf(ic, SYSDYN.InitialCondition)) return; + + Variable base = Variables.getVariable(graph, run); + + PartialIC data = graph.getPossibleRelatedValue(ic, SYSDYN.InitialCondition_HasInitialValues, PartialIC.BINDING); + data.apply(graph, base); + + } + + public static void deleteIC(WriteGraph graph, Variable input, String name) throws DatabaseException { + graph.markUndoPoint(); + Resource model = Variables.getModel(graph, input); + Resource child = Layer0Utils.getPossibleChild(graph, model, name); + SysdynResource SYSDYN = SysdynResource.getInstance(graph); + + if((child != null) && graph.isInstanceOf(child, SYSDYN.InitialCondition)) + RemoverUtil.remove(graph, child); + Layer0Utils.addCommentMetadata(graph, "Deleted Initial Condition " + graph.getRelatedValue2(child, Layer0.getInstance(graph).HasName, Bindings.STRING)); + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperiment.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperiment.java new file mode 100644 index 00000000..6d8d4a92 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperiment.java @@ -0,0 +1,415 @@ +/******************************************************************************* + * Copyright (c) 2007, 2012 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.manager; + +import gnu.trove.list.array.TDoubleArrayList; +import gnu.trove.map.hash.THashMap; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.HashMap; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.simantics.Simantics; +import org.simantics.databoard.Bindings; +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.Session; +import org.simantics.db.WriteGraph; +import org.simantics.db.common.request.WriteRequest; +import org.simantics.db.common.utils.Logger; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.util.Layer0Utils; +import org.simantics.db.layer0.variable.Variable; +import org.simantics.db.layer0.variable.Variables; +import org.simantics.db.request.Read; +import org.simantics.fmu.FMUControlJNI; +import org.simantics.fmu.FMUJNIException; +import org.simantics.modelica.IModelicaMonitor; +import org.simantics.modelica.ModelicaManager; +import org.simantics.modelica.SimulationLocation; +import org.simantics.modeling.PartialIC; +import org.simantics.sysdyn.SysdynResource; +import org.simantics.sysdyn.simulation.SimulationJob.HeadlessModelicaMonitor; +import org.simantics.sysdyn.solver.ISolver; +import org.simantics.sysdyn.solver.ModelicaSolver; + +/** + * Game experiment + * @author Teemu Lempinen + * + */ +public class SysdynGameExperiment extends SysdynGameExperimentBase { + + private ModelicaSolver solver; + public FMUControlJNI control; + private boolean loaded = false; + + private static boolean fortranLibrariesLoaded = false; + + public SysdynGameExperiment(Resource experiment, Resource model) { + super(experiment, model); + this.solver = new ModelicaSolver(this); + } + + public FMUControlJNI getFMUControl() { + return control; + } + + @Override + public void init(ReadGraph g) { + super.init(g); + + if(control == null) + control = new FMUControlJNI(); + + results = new THashMap(); + + } + + @Override + protected void onExperimentDisposed() { + super.onExperimentDisposed(); + if(control!=null) { + try { + control.unloadFMU(); + loaded = false; + } catch (FMUJNIException e) { + e.printStackTrace(); + } + } + } + + private boolean isValidFMU(File file) { + if(!file.exists()) return false; + if(!file.isFile()) return false; + if(file.length() == 0) return false; + return true; + } + + + @Override + public synchronized void simulate(final IModelicaMonitor monitor, final IProgressMonitor progressMonitor, String modelName) throws IOException { + canceled = false; + + progressMonitor.subTask("Write modelica classes"); + + // Write Modelica files + String modelText = getModelicaCode(monitor, true, getOpenModelicaVersion()); + if(modelText == null) + return; + + omcVersion = ModelicaManager.getDefaultOMVersion(); + + monitor.message("Simulate " + modelName + " using OpenModelica " + omcVersion); + + progressMonitor.worked(1); + + // Write initial files and add init-parameters + progressMonitor.subTask("Write simulation files"); + HashMap inits = getExperimentParameters(monitor); + + + // add loadFile script to load all related functions and function libraries + String additionalScript = getAdditionalScripts(); + + // Create simulation files + SimulationLocation simulationLocation = createSimulationFiles(sysdynModel, modelText, inits, additionalScript, true); + progressMonitor.worked(1); + + // Load precompiled fmu if structure has not changed and it has not yet been loaded + File fmu = null; + if(!sysdynModel.isStructureModified()) { + if(!simulationLocation.executableFile.isFile()) { + fmu = loadModelFmu(simulationLocation); + } else { + fmu = simulationLocation.executableFile; + } + } + // Build the model and store previous model structure and inits that affect the building + // If there is no exe file OR the model structure has not changed, no need to build + if (fmu == null && (!isValidFMU(simulationLocation.executableFile) || sysdynModel.isStructureModified())) { + progressMonitor.subTask("Build model"); + buildModel(simulationLocation, monitor); + previousModelStructure = modelText; + + saveModelFmu(simulationLocation); + } + + progressMonitor.worked(1); + + if(simulationLocation != null && !canceled) { + // Load fmu and initialize it for simulation + try { + if (false && !fortranLibrariesLoaded) { // Enable this when we update from OpenModelica 1.9.0beta4! + File omDir = ModelicaManager.getOMHome(); + File mingw = new File(omDir, "MinGW"); + File mbin = new File(mingw, "bin"); + + // Add MinGW path to java.library.path. This is a bit of a hack because + // java.library.path isn't intended to be set programmatically. + String newLibPath = System.getProperty("java.library.path") + File.pathSeparator + mbin.getAbsolutePath(); + System.setProperty("java.library.path", newLibPath); + Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths"); + fieldSysPath.setAccessible(true); + if (fieldSysPath != null) { + fieldSysPath.set(System.class.getClassLoader(), null); + } + + System.loadLibrary("libgfortran-3"); + System.out.println("Loaded libgfortran-3.dll"); + System.loadLibrary("pthreadGC2"); + System.out.println("Loaded pthreadGC2.dll"); + fortranLibrariesLoaded = true; + } + + control.loadFMUFile(simulationLocation.executableFile.getAbsolutePath()); // unzip and load fmu + loaded = true; + instantiate(); + + } catch (FMUJNIException e) { + System.err.println("SysdynGameExperiment initialization failed:\n\t" + e.getMessage()); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchFieldException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + process = null; + simulate(false); + } + + /** + * Load fmu file from database, if it exists for the model of this experiment + * + * @param simulationLocation SimulationLocation indicating where the fmu should be loaded + * @return Loaded fmu or null if it was not loaded from database + */ + private File loadModelFmu(SimulationLocation simulationLocation) { + File fmu = null; + try { + final String fmuLocation = simulationLocation.executableFile.getAbsolutePath(); + fmu = session.syncRequest(new Read() { + @Override + public File perform(ReadGraph graph) throws DatabaseException { + File result = null; + FileOutputStream fos; + try { + fos = new FileOutputStream(fmuLocation); + byte[] fileBArray = graph.getPossibleRelatedValue( + getModel(), SysdynResource.getInstance(graph).SysdynModel_fmuFile, Bindings.BYTE_ARRAY); + + if(fileBArray != null) { + fos.write(fileBArray); + fos.close(); + result = new File(fmuLocation); + } else { + fos.close(); + return null; + } + + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return result; + } + }); + } catch (DatabaseException e) { + e.printStackTrace(); + } + + return fmu; + } + + /** + * Save fmu file from simulationLocation to database + * @param simulationLocation Location for finding fmu + */ + private void saveModelFmu(SimulationLocation simulationLocation) { + final String fmuLocation = simulationLocation.executableFile.getAbsolutePath(); + session.asyncRequest(new WriteRequest() { + + @Override + public void perform(WriteGraph graph) throws DatabaseException { + File file = new File(fmuLocation); + byte[] fileBArray = new byte[(int)file.length()]; + FileInputStream fis; + try { + fis = new FileInputStream(file); + + fis.read(fileBArray); + graph.claimLiteral( + getModel(), + SysdynResource.getInstance(graph).SysdynModel_fmuFile, + fileBArray, Bindings.BYTE_ARRAY); + fis.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + }); + } + + + @Override + public void rewindTo(double time) { + + if(control == null) + return; + + if(time >-0.001 && time < 0.001) { + try { + simulate(new HeadlessModelicaMonitor(), new NullProgressMonitor(), sysdynModel.getConfiguration().getLabel()); + //instantiate(); + } catch (IOException e) { + Logger.defaultLogError(e); + } + } else { + System.out.println("rewindTo"); + } + } + + @Override + public void refresh(Session session) { + try { + control.initializeSimulation(); + clearResults(); + //getInitialResultValues(); + + } catch (FMUJNIException e) { + System.err.println("SysdynGameExperiment instantiate failed: " + e.getMessage()); + } + } + + private synchronized void instantiate() { + try { + HashMap inits = getExperimentParameters(null); + + control.setStepLength(stepLength); // FIXME: fixed step lenghth + control.setTime(startTime); + control.instantiateSimulation(); // instantiate simulation + + if(!control.isInitialized()) { + control.initializeSimulation(); + } + + if(inits.get("variableFilter") == null || inits.get("variableFilter").equals(".*")) + subscription = control.getAllVariables(); + else + subscription = control.filterVariables(inits.get("variableFilter")); + + // Initialize subscription indexes map for fast result reading in getValue() + if(subscriptionIndexes == null) + subscriptionIndexes = new HashMap(); + + subscriptionIndexes.clear(); + for(int i = 0; i < subscription.length; i++) { + subscriptionIndexes.put(subscription[i], i); + } + + // Initialize container for current simulation results + currentValues = new double[subscription.length]; + + // subscribe all variables + control.subscribe(subscription); + + clearResults(); + //getInitialResultValues(); + + Simantics.getSession().syncRequest(new WriteRequest() { + + @Override + public void perform(WriteGraph graph) throws DatabaseException { + + Resource run = Layer0Utils.getPossibleChild(graph, SysdynGameExperiment.this.experiment, getIdentifier()); + if(run == null) { + System.err.println("No run"); + return; + } + + Variable base = Variables.getVariable(graph, run); + + SysdynResource SYSDYN = SysdynResource.getInstance(graph); + + Resource ic = graph.getPossibleObject(SysdynGameExperiment.this.experiment, SYSDYN.Experiment_ic); + if(ic == null) return; + + PartialIC data = graph.getPossibleRelatedValue(ic, SYSDYN.InitialCondition_HasInitialValues, PartialIC.BINDING); + data.apply(graph, base); + + } + + }); + + } catch (FMUJNIException e) { + System.err.println("SysdynGameExperiment instantiate failed: " + e.getMessage()); + } catch (DatabaseException e) { + System.err.println("SysdynGameExperiment instantiate failed: " + e.getMessage()); + } + } + +// private synchronized void getInitialResultValues() { +// try { +// // Initialize results +// results.clear(); +// +// currentValues = control.getSubscribedResults(currentValues); +// for(int k = 0; k < subscription.length; k++) { +// results.put(subscription[k], new ArrayList()); +// results.get(subscription[k]).add(currentValues[k]); +// } +// +// ((MemoryResult)getCurrentResult()).setResult(new GameResult(this.results, this.subscription)); +// resultsChanged(); +// } catch (FMUJNIException e) { +// System.err.println("SysdynGameExperiment getInitialResultValues failed: " + e.getMessage()); +// } +// } + + @Override + public void updateSubscriptions() { + + if(!loaded) return; + + try { + if(control.isInitialized()) + currentValues = control.getSubscribedResults(currentValues); + } catch (FMUJNIException e) { + e.printStackTrace(); + } + super.updateSubscriptions(); + } + + @Override + public ISolver getSolver() { + return solver; + } + + } diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperimentBase.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperimentBase.java new file mode 100644 index 00000000..c4de04a1 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperimentBase.java @@ -0,0 +1,218 @@ +/******************************************************************************* + * Copyright (c) 2007, 2012 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.manager; + +import gnu.trove.list.array.TDoubleArrayList; +import gnu.trove.map.hash.THashMap; + +import java.util.Collection; +import java.util.HashMap; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.jobs.Job; +import org.simantics.db.AsyncReadGraph; +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.procedure.AsyncListener; +import org.simantics.db.request.Read; +import org.simantics.fmu.FMUJNIException; +import org.simantics.simulation.experiment.ExperimentState; +import org.simantics.sysdyn.SysdynResource; +import org.simantics.sysdyn.solver.ISolver; +import org.simantics.utils.datastructures.Quad; + +/** + * Game experiment + * @author Teemu Lempinen + * + */ +abstract public class SysdynGameExperimentBase extends OldSysdynExperiment { + + public double stepLength = DEFAULT_STEP_LENGTH; + public double startTime = DEFAULT_START_TIME; + protected double stepDuration = DEFAULT_STEP_DURATION; + protected int savePer = 1; + + protected HashMap subscriptionIndexes; + protected double[] currentValues; // Current values from FMU. Updated with updateSubscriptions + + THashMap results; + + public String[] subscription; + + public static double DEFAULT_STEP_DURATION = 1.0; + public static double DEFAULT_STEP_LENGTH = 0.1; + public static double DEFAULT_START_TIME = 0.0; + public static int DEFAULT_OUTPUT_INTERVAL = 1; + + public SysdynGameExperimentBase(Resource experiment, Resource model) { + super(experiment, model); + } + + public double getStepDuration() { + return stepDuration; + } + + public void setStepDuration(double duration) { + this.stepDuration = duration; + } + + public double getStepLength() { + return stepLength; + } + + public void setStepLength(double stepLength) { + this.stepLength = stepLength; + } + + public void setStartTime(double startTime) { + this.startTime = startTime; + } + + public void setOutputInterval(int interval) { + this.savePer = interval; + } + + public static class Subscription { + public SysdynGameExperimentBase exp; + public int[] indexes; + public void getValues(double[] data) { + for(int i=0;i names) { + Subscription result = new Subscription(); + int[] indexes = new int[names.size()]; + int index = 0; + for(String name : names) + indexes[index++] = subscriptionIndexes.get(name); + result.exp = this; + result.indexes = indexes; + return result; + } + + public Double getCurrentValue(String name) { + if(subscriptionIndexes != null && name != null) { + Integer index = subscriptionIndexes.get(name); + if(index != null) { + return currentValues[index]; + } + } + return null; + } + + public void setSubscribedResults(IProgressMonitor monitor, double time) throws FMUJNIException { + + monitor.subTask("Get results (time = " + time + ")"); + currentValues = getSolver().getSubscribedResults(currentValues); + monitor.worked(1); + + monitor.subTask("Save results (time = " + time + ")"); + for(int k = 0; k < subscription.length; k++) { + setResults(time, subscription[k], currentValues[k]); + } + + lastResultTime = time; + + } + + private double lastResultTime = Double.NaN; + + public void setResults(double time, String key, Double value) { + TDoubleArrayList list = results.get(key); + if(list == null) { + list = new TDoubleArrayList(); + results.put(key, list); + } + if(time == lastResultTime) { + list.set(list.size()-1, value); + } else { + list.add(value); + } +// System.err.println("setResults " + time + " " + key + " = " + list); + } + + public void clearResults() { + lastResultTime = Double.NaN; + results.clear(); + } + + @Override + public void simulateDuration(double duration) { + Job job = new SimulateDurationJob(this, "Simulate steps", duration); + // Start the Job + job.schedule(); + } + + public void refresh() { + } + + public abstract ISolver getSolver(); + + @Override + public void init(ReadGraph g) { + + super.init(g); + + try { + g.syncRequest(new Read>() { + + @Override + public Quad perform(ReadGraph graph) + throws DatabaseException { + SysdynResource sr = SysdynResource.getInstance(graph); + Double stepDuration = graph.getPossibleRelatedValue(experiment, sr.GameExperiment_stepDuration); + Double stepLength = graph.getPossibleRelatedValue(experiment, sr.GameExperiment_stepLength); + Double outputInterval = graph.getPossibleRelatedValue(model, sr.SysdynModel_outputInterval); + Double startTime = graph.getPossibleRelatedValue(model, sr.SysdynModel_startTime); + return new Quad(stepDuration, stepLength, outputInterval, startTime); + } + }, new AsyncListener>() { + + @Override + public void execute(AsyncReadGraph graph, + Quad result) { + setStepDuration(result.first != null ? result.first : DEFAULT_STEP_DURATION); + setStepLength(result.second != null ? result.second : DEFAULT_STEP_LENGTH); + setStartTime(result.fourth != null ? result.fourth : DEFAULT_START_TIME); + + if(result.third == null) { + setOutputInterval(DEFAULT_OUTPUT_INTERVAL); + } else { + int interval = (int)getInterval(result.third, getStepLength()); + setOutputInterval(interval); + } + } + + @Override + public void exception(AsyncReadGraph graph, Throwable throwable) { + throwable.printStackTrace(); + setStepDuration(DEFAULT_STEP_DURATION); + setStepLength(DEFAULT_STEP_LENGTH); + setStartTime(DEFAULT_START_TIME); + setOutputInterval(DEFAULT_OUTPUT_INTERVAL); + } + + @Override + public boolean isDisposed() { + return getState().equals(ExperimentState.DISPOSED); + } + }); + } catch (DatabaseException e) { + e.printStackTrace(); + } + + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperimentInternal.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperimentInternal.java new file mode 100644 index 00000000..1dfc9a8d --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperimentInternal.java @@ -0,0 +1,181 @@ +/******************************************************************************* + * Copyright (c) 2007, 2012 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.manager; + +import gnu.trove.list.array.TDoubleArrayList; +import gnu.trove.map.hash.THashMap; + +import java.io.IOException; +import java.util.HashMap; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.simantics.Simantics; +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.WriteGraph; +import org.simantics.db.common.request.WriteRequest; +import org.simantics.db.common.utils.Logger; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.util.Layer0Utils; +import org.simantics.db.layer0.variable.Variable; +import org.simantics.db.layer0.variable.Variables; +import org.simantics.modelica.IModelicaMonitor; +import org.simantics.modeling.PartialIC; +import org.simantics.simulation.experiment.ExperimentState; +import org.simantics.sysdyn.SysdynResource; +import org.simantics.sysdyn.simulation.SimulationJob.HeadlessModelicaMonitor; +import org.simantics.sysdyn.solver.ISolver; +import org.simantics.sysdyn.solver.ISolverMonitor; +import org.simantics.sysdyn.solver.InternalSolver; + + +public class SysdynGameExperimentInternal extends SysdynGameExperimentBase { + + public InternalSolver solver; + + public SysdynGameExperimentInternal(Resource experiment, Resource model) { + super(experiment, model); + } + + @Override + public ISolver getSolver() { + return solver; + } + + @Override + public void init(ReadGraph g) { + + super.init(g); + + results = new THashMap(); + + solver = new InternalSolver(this, sysdynModel, true, new ISolverMonitor() { + + @Override + public void showConsole() { + // TODO Auto-generated method stub + + } + + @Override + public void message(String message) { + System.err.println("Internal solver:" + message); + } + + @Override + public void clearConsole() { + // TODO Auto-generated method stub + + } + }); + + } + + @Override + public synchronized void simulate(final IModelicaMonitor monitor, final IProgressMonitor progressMonitor, String modelName) throws IOException { + + try { + + solver.initialize(); + solver.buildModel(); + + //solver.setTime(startTime); + + subscription = solver.solver.keys(); + + // Initialize subscription indexes map for fast result reading in getValue() + if(subscriptionIndexes == null) + subscriptionIndexes = new HashMap(); + + subscriptionIndexes.clear(); + for(int i = 0; i < subscription.length; i++) { + subscriptionIndexes.put(subscription[i], i); + } + + // Initialize container for current simulation results + currentValues = new double[subscription.length]; + + // subscribe all variables + //solver.subscribe(subscription); + + clearResults(); + //getInitialResultValues(); + + Simantics.getSession().syncRequest(new WriteRequest() { + + @Override + public void perform(WriteGraph graph) throws DatabaseException { + + Resource run = Layer0Utils.getPossibleChild(graph, SysdynGameExperimentInternal.this.experiment, getIdentifier()); + if(run == null) { + System.err.println("No run"); + return; + } + + Variable base = Variables.getVariable(graph, run); + + SysdynResource SYSDYN = SysdynResource.getInstance(graph); + + Resource ic = graph.getPossibleObject(SysdynGameExperimentInternal.this.experiment, SYSDYN.Experiment_ic); + if(ic == null) return; + + PartialIC data = graph.getPossibleRelatedValue(ic, SYSDYN.InitialCondition_HasInitialValues, PartialIC.BINDING); + data.apply(graph, base); + + } + + }); + + + setSubscribedResults(new NullProgressMonitor(), solver.getTime()); + + ((MemoryResult)getCurrentResult()).setResult(new GameResult(this, this.results, this.subscription)); + + resultsChanged(true); + + changeState(ExperimentState.STOPPED); + + } catch (Exception e) { + Logger.defaultLogError(e); + } + } + + @Override + public void refresh() { + try { + setSubscribedResults(new NullProgressMonitor(), solver.getTime()); + + ((MemoryResult)getCurrentResult()).setResult(new GameResult(this, this.results, this.subscription)); + + resultsChanged(true); + } catch (Exception e) { + Logger.defaultLogError(e); + } + } + + @Override + public void rewindTo(double time) { + + if(time >-0.001 && time < 0.001) { + try { + simulate(new HeadlessModelicaMonitor(), new NullProgressMonitor(), sysdynModel.getConfiguration().getLabel()); + //instantiate(); + } catch (IOException e) { + Logger.defaultLogError(e); + } + } else { + System.out.println("rewindTo"); + } + } + + } diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModel.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModel.java new file mode 100644 index 00000000..0d4a811a --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModel.java @@ -0,0 +1,589 @@ +/******************************************************************************* + * Copyright (c) 2010, 2013, 2014 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + * Semantum Oy - Bug #4180 + *******************************************************************************/ +package org.simantics.sysdyn.manager; + +import gnu.trove.set.hash.THashSet; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.simantics.Simantics; +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.Session; +import org.simantics.db.common.utils.NameUtils; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.exception.ManyObjectsForFunctionalRelationException; +import org.simantics.db.exception.ServiceException; +import org.simantics.db.procedure.Listener; +import org.simantics.db.request.Read; +import org.simantics.db.service.VirtualGraphSupport; +import org.simantics.layer0.Layer0; +import org.simantics.objmap.IMapping; +import org.simantics.objmap.IMappingListener; +import org.simantics.objmap.MappingException; +import org.simantics.objmap.Mappings; +import org.simantics.project.IProject; +import org.simantics.simulation.experiment.IExperiment; +import org.simantics.simulation.model.IModel; +import org.simantics.simulation.ontology.SimulationResource; +import org.simantics.simulation.project.ExperimentRuns; +import org.simantics.simulation.project.IExperimentActivationListener; +import org.simantics.simulation.project.IExperimentManager; +import org.simantics.structural.stubs.StructuralResource2; +import org.simantics.sysdyn.SysdynResource; +import org.simantics.sysdyn.adapter.VariableValueSubscription; +import org.simantics.sysdyn.representation.Configuration; +import org.simantics.sysdyn.representation.IElement; +import org.simantics.sysdyn.representation.IndependentVariable; +import org.simantics.sysdyn.representation.Model; +import org.simantics.sysdyn.representation.Module; +import org.simantics.sysdyn.representation.ParameterOverride; +import org.simantics.sysdyn.representation.Sheet; +import org.simantics.sysdyn.representation.SysdynSchema; +import org.simantics.sysdyn.representation.Variability; +import org.simantics.sysdyn.representation.expressions.Expression; +import org.simantics.sysdyn.representation.expressions.IExpression; +import org.simantics.sysdyn.representation.expressions.ParameterExpression; +import org.simantics.sysdyn.representation.expressions.StockExpression; +import org.simantics.sysdyn.solver.SolverSettings; +import org.simantics.sysdyn.solver.SolverSettings.SolverType; + +/** + * Maintains a Java representation of system dynamic model. + * @author Hannu Niemistö, Teemu Lempinen, Tuomas Miettinen + */ +public class SysdynModel implements IModel, IMappingListener, VariableSubscriptionManager { + + private Session session; + + private IMapping mapping; + + private Resource configurationResource; + private Resource modelResource; + + private Configuration configuration; + + private final Set modules = new HashSet(); + + private ArrayList displayedResults; + private final ArrayList listeningHistories = new ArrayList(); + + private final CopyOnWriteArrayList modificationListeners = + new CopyOnWriteArrayList(); + + @SuppressWarnings("rawtypes") + protected THashSet variableValueSubscriptions = new THashSet(); + @SuppressWarnings("rawtypes") + protected volatile VariableValueSubscription[] variableValueSubscriptionsSnapshot = null; + + @SuppressWarnings("rawtypes") + private final Map services = new HashMap(); + + private boolean structureModified = false; + + /** + * Recursively read all module configurations that are used in + * configResource and its components children + * + * @param graph ReadGraph + * @param configResource Configuration + * @param result set containing all encountered configurations + * @throws DatabaseException + */ + void readModules(ReadGraph graph, Resource configResource, Set result) throws DatabaseException { + + // if result does not contain this resource, add it to the result + if(!result.add(configResource)) return; + + Layer0 l0 = Layer0.getInstance(graph); + SysdynResource sr = SysdynResource.getInstance(graph); + StructuralResource2 str = StructuralResource2.getInstance(graph); + + for(Resource part : graph.getObjects(configResource, l0.ConsistsOf)) { + if(graph.isInstanceOf(part, sr.Module)) { + Resource type = graph.getPossibleType(part, sr.Module); + Resource config = graph.getPossibleObject(type, str.IsDefinedBy); + // Recursively readModules + readModules(graph, config, result); + } + } + + } + + /** + * Get all modules that have been used in configResource and its children + * @param graph ReadGraph + * @param configResource Configuration + * @return All modules (configuration resources) that have been used in configResource + * @throws DatabaseException + */ + Set readModules(ReadGraph graph, Resource configResource) throws DatabaseException { + HashSet result = new HashSet(); + readModules(graph, configResource, result); + return result; + } + + /** + * Create an ObjMapping + * @param g ReadGraph + * @throws DatabaseException + */ + private void createMapping(ReadGraph g) throws DatabaseException { + SysdynSchema schema = new SysdynSchema(g); + mapping = Mappings.createWithListening(schema); + mapping.addMappingListener(SysdynModel.this); + try { + configuration = (Configuration)mapping.map(g, configurationResource); + } catch (MappingException e) { + SysdynConsole.INSTANCE.message( + "Error: Mapping is broken! Find the problem, " + + "fix it and restart the program." + + "\nJava error message:\n" + + e.getMessage()); + throw e; + } + for(Resource config : readModules(g, configurationResource)) { + modules.add((Configuration)mapping.map(g, config)); + } + } + + /** + * New Sysdyn model + * @param g ReadGraph + * @param configurationResource Configration resource of the model + */ + public SysdynModel(ReadGraph g, Resource configurationResource) { + this.session = g.getSession(); + this.configurationResource = configurationResource; + + try { + createMapping(g); + } catch(DatabaseException e) { + e.printStackTrace(); + } + + g.asyncRequest(new Read> () { + @Override + public ArrayList perform(ReadGraph graph) throws DatabaseException { + ArrayList displayedResults = new ArrayList(); + // TODO: this can be done automatically with a listener + + for(HistoryDatasetResult hs : listeningHistories) + hs.disposeListeners(); // dispose old histories listening to spreadsheets + + try { + // Find all active saved results + Layer0 l0 = Layer0.getInstance(graph); + SysdynResource sr = SysdynResource.getInstance(graph); + SimulationResource SIMU = SimulationResource.getInstance(graph); + Resource model = graph.getPossibleObject(getConfigurationResource(), SIMU.IsConfigurationOf); + if(model == null) + return null; + + Collection results = graph.syncRequest(new ActiveResults(model)); + for(Resource result : results) { + if(graph.hasStatement(result, sr.Result_showResult)) { + SysdynResult sysdynResult = null; + if(graph.isInstanceOf(result, sr.HistoryDataset)) { + HistoryDatasetResult r = new HistoryDatasetResult(); + listeningHistories.add(r); + sysdynResult = new MemoryResult(r, NameUtils.getSafeLabel(graph, result)); + r.read((MemoryResult)sysdynResult, result); + } else { + sysdynResult = new FileResult( + (String) graph.getPossibleRelatedValue(result, l0.HasLabel), + (String) graph.getPossibleRelatedValue(result, sr.Result_resultFile)); + } + + if(sysdynResult != null) + displayedResults.add(sysdynResult); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + + return displayedResults; + } + + }, new Listener> () { + + @Override + public void execute(ArrayList result) { + // Add the current result if there is one + displayedResults = result; + resultChanged(); + } + + @Override + public void exception(Throwable t) { + t.printStackTrace(); + } + + @Override + public boolean isDisposed() { + return false; + } + + }); + } + + // A dummy call for experiments + public SysdynModel(Resource modelResource) { + this.modelResource = modelResource; + } + + /** + * Get modules + * @return modules + */ + public Set getModules() { + return modules; + } + + /** + * Update mapping. + * + * Use this if inside a transaction. + * + * @param graph ReadGraph + * @return has the range been modified + * @throws DatabaseException + */ + public synchronized boolean update(ReadGraph graph) throws DatabaseException { + if(mapping.isDomainModified()) { + try { + Collection updated = mapping.updateRange(graph); + + for(Object o : updated) { + if(o instanceof Model) { + continue; + } else if(o instanceof Expression && !(o instanceof StockExpression)) { + IndependentVariable variable = ((Expression)o).getParent(); + Variability variability = Variability.getVariability(variable, false, configuration); + if(variability == Variability.PARAMETER) + continue; + } + + // if continue has not been called, the structure has changed + setStructureModified(true); + break; + + } + + } catch (MappingException e) { + SysdynConsole.INSTANCE.message( + "Error: Mapping is broken! Find the problem, " + + "fix it and restart the program." + + "\nJava error message:\n" + + e.getMessage()); + throw e; + } + + // Remove all unnecessary module configurations from modules + Set configs = readModules(graph, configurationResource); + for(Resource config : configs) { + if(!modules.contains(config)) + modules.add((Configuration)mapping.map(graph, config)); + } + + HashSet toBeRemoved = null; + for(Configuration module : modules) { + if(!configs.contains(mapping.inverseGet(module))) { + if(toBeRemoved == null) + toBeRemoved = new HashSet(); + toBeRemoved.add(module); + } + } + if(toBeRemoved != null) + modules.removeAll(toBeRemoved); + return true; + } + else + return false; + } + + /** + * Update mapping. + * + * Use only if not inside a transaction + * @return has range been updated + * @throws DatabaseException + */ + public boolean update() throws DatabaseException { + return session.syncRequest(new Read() { + @Override + public Boolean perform(ReadGraph graph) throws DatabaseException { + return update(graph); + } + }); + } + + /** + * Fires an update to all result listeners and subscriptions + * after results have changed + */ + public void resultChanged() { + IProject project = Simantics.peekProject(); + IExperimentManager manager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER); + IExperiment active = manager.getActiveExperiment(); + if(active != null && active instanceof SysdynExperiment) { + ((SysdynExperiment)active).resultsChanged(); + } + + updateSubscriptions(); + } + + public void addModificationListener(Runnable listener) { + synchronized(modificationListeners) { + modificationListeners.add(listener); + } + } + + public void removeModificationListener(Runnable listener) { + synchronized(modificationListeners) { + modificationListeners.remove(listener); + } + } + + /** + * Fires all modification listeners after a change in the domain + */ + @Override + public void domainModified() { + synchronized(modificationListeners) { + for(Runnable listener : modificationListeners) + listener.run(); + } + } + + @Override + public void rangeModified() { + } + + public Configuration getConfiguration() { + return configuration; + } + + public Resource getConfigurationResource() { + return configurationResource; + } + + public IMapping getMapping() { + return mapping; + } + + public synchronized IElement getElement(Resource resource) { + return (IElement)mapping.get(resource); + } + + public T getService(Class clazz) { + synchronized(services) { + return clazz.cast(services.get(clazz)); + } + } + + public void addService(Class clazz, T service) { + synchronized(services) { + services.put(clazz, service); + } + } + + @Override + public IExperiment loadExperiment(ReadGraph g, Resource experiment, IExperimentActivationListener listener) { + // Make sure that configurationResource exists + if(configurationResource == null && modelResource != null) { + SimulationResource simu = SimulationResource.getInstance(g); + try { + configurationResource = g.getPossibleObject(modelResource, simu.HasConfiguration); + } catch (ManyObjectsForFunctionalRelationException e) { + e.printStackTrace(); + } catch (ServiceException e) { + e.printStackTrace(); + } + } + + try { + // Create a new experiment based on the experiment resource type + SysdynResource sr = SysdynResource.getInstance(g); + SysdynExperiment exp; + + if(g.isInstanceOf(experiment, sr.PlaybackExperiment)) { + exp = new SysdynPlaybackExperiment(experiment, modelResource); + } else if(g.isInstanceOf(experiment, sr.GameExperiment)) { + if (SolverType.INTERNAL.equals(SolverSettings.getSelectedSolverType())) { + exp = new SysdynGameExperimentInternal(experiment, modelResource); + } + else { + exp = new SysdynGameExperiment(experiment, modelResource); + } + } else if(g.isInstanceOf(experiment, sr.SensitivityAnalysisExperiment)) { + exp = new SysdynSensitivityAnalysisExperiment(experiment, modelResource); + } else if(g.isInstanceOf(experiment, sr.BasicExperiment)) { + // TODO: this is a temporary hack to make sure at least one + // working implementation is available even if the new solver + // architecture is completely broken + if (SolverType.INTERNAL.equals(SolverSettings.getSelectedSolverType())) { + exp = new SysdynExperiment(experiment, modelResource); + } + else { + exp = new OldSysdynExperiment(experiment, modelResource); + } + } else { + return null; + } + + // TODO: should maybe get the model from model manager? + + exp.init(g); + + VirtualGraphSupport support = g.getSession().getService(VirtualGraphSupport.class); + ExperimentRuns.createRun(g.getSession(), support.getWorkspacePersistent("experiments"), experiment, exp, SysdynResource.URIs.Experiment_Run, listener, null); + if(listener != null) + listener.onExperimentActivated(exp); + return exp; + } catch(Exception e) { + if(listener != null) + listener.onFailure(e); + return null; + } + } + + + /** + * Get active results. To update the active results, use getAndUpdateActiveResults() + * + * @param graph ReadGraph + * @return all active SysdynResults (last update with getAndUpdateActiveResults()) + */ + public Collection getDisplayedResults() { + // TODO: displayedResults are always empty? + if(displayedResults == null) + return new ArrayList(); + else + return displayedResults; + } + + /** + * Get all parameters for Configuration + * + * @param configuration Configuration + * @param prefix String prefix of configuration in this model (Module1.Module2...) + * @return + */ + public HashMap getInits(Configuration configuration, String prefix) { + HashMap inits = new HashMap(); + for (IElement element : configuration.getElements()) { + if (element instanceof Module) { + Module module = (Module) element; + Configuration conf = module.getType().getConfiguration(); + String prfx = prefix + module.getModelicaName() + "."; + inits.putAll(getInits(conf, prfx)); + for(ParameterOverride po : module.getParameterOverrides()) { + inits.put(prfx + po.getVariable().getName(), po.getExpression()); + } + } else if (element instanceof IndependentVariable) { + IndependentVariable variable = (IndependentVariable) element; + //FIXME: more general solution for finding out if the variable is a parameter + if(variable != null && variable.getExpressions() != null && variable.getExpressions().get(0) != null) { + IExpression expression = variable.getExpressions().get(0); + if (expression instanceof ParameterExpression) { + Double value = ((ParameterExpression)expression).getValue(); + if(value != null) + inits.put(prefix + variable.getName(), "" + value); + } + } + } else if(element instanceof Sheet) { + Sheet sheet = (Sheet) element; + for(String cell : sheet.getCells().keySet()) { + inits.put(sheet.getName() + "." + cell, sheet.getCells().get(cell).toString()); + } + } + } + return inits; + } + + + @SuppressWarnings("rawtypes") + /** + * Copy from AprosExperiment + * @param subscription + */ + @Override + public void addVariableValueSubscription(VariableValueSubscription subscription) { + assert subscription != null; + synchronized (variableValueSubscriptions) { + variableValueSubscriptions.add(subscription); + variableValueSubscriptionsSnapshot = null; + } + } + + @SuppressWarnings("rawtypes") + /** + * Copy from AprosExperiment + * @param subscription + */ + @Override + public void removeVariableValueSubscription(VariableValueSubscription subscription) { + assert subscription != null; + synchronized (variableValueSubscriptions) { + variableValueSubscriptions.remove(subscription); + variableValueSubscriptionsSnapshot = null; + } + } + + @SuppressWarnings("rawtypes") + /** + * Copy from AprosExperiment + * @return + */ + @Override + public VariableValueSubscription[] getListenerSnapshot() { + VariableValueSubscription[] snapshot = variableValueSubscriptionsSnapshot; + if (snapshot == null) { + synchronized (variableValueSubscriptions) { + snapshot = variableValueSubscriptionsSnapshot; + if (snapshot == null) { + snapshot = variableValueSubscriptionsSnapshot = variableValueSubscriptions.toArray(new VariableValueSubscription[variableValueSubscriptions.size()]); + } + } + } + return snapshot; + } + + @SuppressWarnings("rawtypes") + /** + * Modified copy from AporsExperiment + */ + @Override + public void updateSubscriptions() { + VariableValueSubscription[] snapShot = getListenerSnapshot(); + for(VariableValueSubscription subscription : snapShot) + subscription.update(); + } + + + public boolean isStructureModified() { + return structureModified; + } + + public void setStructureModified(boolean structureModified) { + this.structureModified = structureModified; + } +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModelManager.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModelManager.java new file mode 100644 index 00000000..c902f9cc --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModelManager.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (c) 2010 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.manager; + +import java.util.WeakHashMap; + +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.Session; +import org.simantics.db.common.request.ReadRequest; +import org.simantics.db.exception.DatabaseException; + +/** + * Manages system dynamic models. + * @author Hannu Niemistö + */ +public class SysdynModelManager { + WeakHashMap models = + new WeakHashMap(); // FIXME: Resources are weak, there is no guarantee that model exists in this map as long as needed. + // HashTable with a disposal procedure could be better solution.. + Session session; + + public SysdynModelManager(Session session) { + this.session = session; + } + + /** + * Use only if not inside a transaction + */ + public SysdynModel getModel(final Resource resource) { + synchronized(models) { + SysdynModel model = models.get(resource); + if(model == null) { + try { + session.syncRequest(new ReadRequest() { + @Override + public void run(ReadGraph graph) throws DatabaseException { + SysdynModel model = new SysdynModel(graph, resource); + models.put(resource, model); + } + }); + } catch (DatabaseException e) { + e.printStackTrace(); + } + + model = models.get(resource); + } + return model; + } + } + + /** + * Should be used if called inside a transaction + */ + public SysdynModel getModel(ReadGraph g, Resource resource) { + synchronized(models) { + SysdynModel model = models.get(resource); + if(model == null) { + model = new SysdynModel(g, resource); + models.put(resource, model); + } + return model; + } + } + + public synchronized static SysdynModelManager getInstance(Session session) { + SysdynModelManager manager = + session.peekService(SysdynModelManager.class); + if(manager == null) { + manager = new SysdynModelManager(session); + session.registerService(SysdynModelManager.class, manager); + } + return manager; + } +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynPlaybackExperiment.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynPlaybackExperiment.java new file mode 100644 index 00000000..38ae0385 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynPlaybackExperiment.java @@ -0,0 +1,285 @@ +/******************************************************************************* + * Copyright (c) 2007, 2012 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.manager; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.common.request.ReadRequest; +import org.simantics.db.exception.DatabaseException; +import org.simantics.Simantics; +import org.simantics.db.request.Read; +import org.simantics.simulation.experiment.ExperimentState; +import org.simantics.simulation.ontology.SimulationResource; +import org.simantics.sysdyn.SysdynResource; + +public class SysdynPlaybackExperiment extends OldSysdynExperiment { + + public static long DURATION_SLOW = 20000; + public static long DURATION_NORMAL = 10000; + public static long DURATION_FAST = 5000; + + double time, startTime, endTime; + public static final long VARIABLE_UPDATE_INTERVAL = 500000000; + private static final double UPDATES_PER_TIME_UNIT = 0.015; + private long playbackDuration = DURATION_NORMAL; + private Collection timeListeners = new ArrayList(); + + ScheduledExecutorService playbackExecutionService; + PlaybackConfiguration playbackConfiguration; + + public SysdynPlaybackExperiment(Resource experiment, Resource model) { + super(experiment, model); + this.time = 0; + } + + + /** + * Interrupts a possible ongoing playback + * + * @param time + */ + public void setTimeInterrupting(double time) { + stopPlayback(); + setTime(time); + } + + /** + * Sets a new time and continues playback from that point if + * playback was running + * @param time + */ + public void setTimeAndContinue(double time) { + if(isPlaybackRunning()) { + stopPlayback(); + setTime(time); + startPlayback(500); + } else { + setTime(time); + } + } + + private void setTime(double time) { + this.time = time; + resultsChanged(); + } + + public double getTime() { + return this.time; + } + + public double getStartTime() { + return this.startTime; + } + + public double getEndTime() { + return this.endTime; + } + + public void setPlaybackDuration(long duration) { + this.playbackDuration = duration; + if(isPlaybackRunning()) { + //Restart playback with different time settings + startPlayback(); + } + } + + public long getPlaybackDuration() { + return this.playbackDuration; + } + + @Override + public void init(ReadGraph g) { + this.session = g.getSession(); + session.asyncRequest(new ReadRequest() { + + @Override + public void run(ReadGraph graph) throws DatabaseException { + changeState(ExperimentState.RUNNING); + final Resource configuration = graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration); + sysdynModel = SysdynModelManager.getInstance(session).getModel(graph, configuration); + toggleActivation(graph, true); + getPlaybackConfiguration(graph); + startSimulationJob(); + } + }); + } + + + // PLAYBACK CONTROLS + public void startPlayback() { + startPlayback(0); + } + public void startPlayback(long initialDelay) { + if(isPlaybackRunning()) { + stopPlayback(); + } + playbackConfiguration = getPlaybackConfiguration(); + playbackExecutionService = Executors.newScheduledThreadPool(1); + + if(time >= playbackConfiguration.endTime) { + setTime(playbackConfiguration.startTime); + playbackConfiguration = getPlaybackConfiguration(); + } + + Runnable playbackSimulationTask = new PlaybackSimulationTask(time, playbackConfiguration.simulationStepLength); + + long delay = (long) (playbackConfiguration.playbackDuration / playbackConfiguration.intervals); + ScheduledFuture stepper = playbackExecutionService.scheduleWithFixedDelay( + playbackSimulationTask, initialDelay, delay, TimeUnit.MILLISECONDS + ); + + Runnable stopSimulationTask = new StopSimulationTask(stepper, playbackConfiguration.endTime); + playbackExecutionService.schedule(stopSimulationTask, playbackConfiguration.playbackDuration + initialDelay, TimeUnit.MILLISECONDS); + + changeState(ExperimentState.RUNNING); + } + + public boolean isPlaybackRunning() { + return playbackExecutionService != null && !playbackExecutionService.isShutdown(); + } + + public void resetPlayback() { + double startTime = 0.0; + if(isPlaybackRunning() && playbackConfiguration != null) { + startTime = playbackConfiguration.startTime; + } else { + startTime = getPlaybackConfiguration().startTime; + } + setTimeInterrupting(startTime); + } + + public void stopPlayback() { + if(isPlaybackRunning()) { + playbackExecutionService.shutdownNow(); + playbackExecutionService.shutdown(); + if(playbackConfiguration != null) + playbackConfiguration = null; + changeState(ExperimentState.STOPPED); + } + } + + + private class PlaybackSimulationTask implements Runnable { + private int stepCount; + private double startTime, stepLength; + + public PlaybackSimulationTask(double startTime, double stepLength) { + this.startTime = startTime; + this.stepLength = stepLength; + } + + public void run() { + ++stepCount; + setTime(startTime + stepCount * stepLength); +// System.out.println("Playback step at time: " + (startTime + stepCount * stepLength) + " (step: " + stepCount + ")"); + } + } + + private class StopSimulationTask implements Runnable { + + private ScheduledFuture scheduledFuture; + private double endTime; + + public StopSimulationTask(ScheduledFuture aSchedFuture, double endTime){ + scheduledFuture = aSchedFuture; + this.endTime = endTime; + } + public void run() { +// System.out.println("Stopping playback"); + scheduledFuture.cancel(false); + stopPlayback(); + setTime(endTime); + } + + } + + private PlaybackConfiguration getPlaybackConfiguration() { + PlaybackConfiguration config = null; + try { + config = Simantics.getSession().syncRequest(new Read() { + + @Override + public PlaybackConfiguration perform(ReadGraph graph) throws DatabaseException { + return getPlaybackConfiguration(graph); + } + + }); + } catch (DatabaseException e) { + e.printStackTrace(); + } + return config; + } + private PlaybackConfiguration getPlaybackConfiguration(ReadGraph graph) throws DatabaseException { + Double[] numbers = new Double[3]; + Resource model = getModel(); + SysdynResource sr = SysdynResource.getInstance(graph); + numbers[0] = graph.getRelatedValue(model, sr.SysdynModel_startTime); + numbers[1] = graph.getRelatedValue(model, sr.SysdynModel_stopTime); + + PlaybackConfiguration config = new PlaybackConfiguration(); + config.simulationDuration = numbers[1] - numbers[0] - time; + config.playbackDuration = (long) (config.simulationDuration / (config.simulationDuration + time) * playbackDuration); + config.intervals = config.playbackDuration * UPDATES_PER_TIME_UNIT; + config.simulationStepLength = config.simulationDuration / config.intervals; + config.endTime = numbers[1]; + config.startTime = numbers[0]; + + this.startTime = config.startTime; + this.endTime = config.endTime; + return config; + } + + private class PlaybackConfiguration { + public double simulationDuration, simulationStepLength, intervals, endTime, startTime; + public long playbackDuration; + } + + protected void localStateChange() { + super.localStateChange(); + + ExperimentState state = getState(); + if(ExperimentState.DISPOSED.equals(state)) { + stopPlayback(); + } + } + + // TIME LISTENERS + public void addTimeListener(Runnable timeListener) { + if(!this.timeListeners.contains(timeListener)) + this.timeListeners.add(timeListener); + } + + public Collection getTimeListeners() { + return this.timeListeners; + } + + public void removeTimeListener(Runnable timeListener) { + this.timeListeners.remove(timeListener); + } + + @Override + public void resultsChanged() { + for(Runnable listener : timeListeners) { + listener.run(); + } + super.resultsChanged(); + + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynResult.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynResult.java new file mode 100644 index 00000000..e564d591 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynResult.java @@ -0,0 +1,41 @@ +/******************************************************************************* + * Copyright (c) 2010, 2013 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + * Semantum Oy - Bug #4180 + *******************************************************************************/ +package org.simantics.sysdyn.manager; + + +import java.io.File; + +import org.eclipse.core.runtime.IProgressMonitor; + +/** + * + * @author Teemu Lempinen + * + */ +public abstract class SysdynResult { + + private String resultName; + + public SysdynResult(String resultName) { + this.resultName = resultName; + } + + public String getResultName() { + return this.resultName; + } + + public abstract SysdynDataSet getDataSet(String variable); + + public abstract void saveToFile(File file, IProgressMonitor progressMonitor); + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynSensitivityAnalysisExperiment.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynSensitivityAnalysisExperiment.java new file mode 100644 index 00000000..063c3867 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynSensitivityAnalysisExperiment.java @@ -0,0 +1,378 @@ +/******************************************************************************* + * Copyright (c) 2007, 2012 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.manager; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.simantics.databoard.Bindings; +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.WriteGraph; +import org.simantics.db.common.request.ReadRequest; +import org.simantics.db.common.request.WriteRequest; +import org.simantics.db.common.utils.ListUtils; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.request.Read; +import org.simantics.layer0.utils.direct.GraphUtils; +import org.simantics.modelica.IModelicaMonitor; +import org.simantics.modelica.ModelicaKeys; +import org.simantics.modelica.ModelicaManager; +import org.simantics.modelica.SimulationLocation; +import org.simantics.modelica.data.CSVSimulationResult; +import org.simantics.modelica.data.MatSimulationResult; +import org.simantics.modelica.data.SimulationResult; +import org.simantics.sysdyn.SysdynResource; +import org.simantics.sysdyn.adapter.SensitivityExperimentParameter; +import org.simantics.sysdyn.adapter.generator.IGenerator; + +/** + * Sensitivity analysis experiment + * @author Tuomas Miettinen + * + */ +public class SysdynSensitivityAnalysisExperiment extends OldSysdynExperiment { + + private ArrayList results = null; + private int numberOfRuns = 0; + private IGenerator valueGenerator = null; + + public SysdynSensitivityAnalysisExperiment(Resource experiment, Resource model) { + super(experiment, model); + } + + private void findValuesAndRun(List parameters, HashMap values, HashMap experimentParameters) { + ArrayList> parameterMaps = new ArrayList>(); + int parametersSize = parameters.size(); + + // Get method and number of runs + try { + session.syncRequest(new WriteRequest() { + @Override + public void perform(WriteGraph graph) throws DatabaseException { + SysdynResource SR = SysdynResource.getInstance(graph); + numberOfRuns = graph.getPossibleRelatedValue(experiment, SR.SensitivityAnalysisExperiment_numberOfValues, Bindings.INTEGER); + Resource methodResource = graph.getPossibleObject(experiment, SR.SensitivityAnalysisExperiment_method); + if (methodResource == null) { + methodResource = GraphUtils.create2(graph, SR.RandomGenerator); + graph.claim(experiment, SR.SensitivityAnalysisExperiment_method, methodResource); + } + valueGenerator = graph.adapt(methodResource, IGenerator.class); + } + + }); + } catch (DatabaseException e) { + e.printStackTrace(); + } + + // Refresh rate for charts + refreshRate = numberOfRuns / 20 + 1; + + // Initialize the random generator + valueGenerator.initialize(); + + // Determine the changed parameters and their values for each individual run + for (int i = 0; i < numberOfRuns; ++i) { + List randoms = valueGenerator.next();// multi-dimensional random + HashMap parameterMap = new HashMap(parametersSize); + for (int j = 0; j < parametersSize; ++j) { + SensitivityExperimentParameter p = parameters.get(j); + // Get the random value + double value = p.getDistribution().inverseCDF(randoms.get(j)); + // Add the new parameter-value-pair + parameterMap.put(p.getFullModelicaName(), Double.toString(value)); + } + // Add the complete list of one individual run parameter-value-pairs. + parameterMaps.add(parameterMap); + } + + // Set the parameters for each individual experiment and run them. + for (HashMap parameterSet : parameterMaps) { + values.putAll(parameterSet); + runSensitivityRun(values, experimentParameters); + } + } + + private void runSensitivityRun(HashMap values, HashMap experimentParameters) { + int indexOfDot = simulationLocation.resultFile.toString().lastIndexOf('.'); + if (indexOfDot > 1) { + String resFile = simulationLocation.resultFile.toString(); + String newResFile = resFile.substring(0, indexOfDot) + currentRun + resFile.substring(indexOfDot); + experimentParameters.put(ModelicaManager.RESULT_FILE_NAME, newResFile); + } + // Simulate the model for one parameter set + progressMonitor.subTask("Simulation iteration " + (currentRun+1) + "/" + numberOfRuns); + + + try { + process = ModelicaManager.runModelica( + simulationLocation, + monitor, + experimentParameters, + values + ); + } catch (IOException e) { + e.printStackTrace(); + } + + ModelicaManager.printProcessOutput(process, monitor); + + File resFile = new File(experimentParameters.get(ModelicaManager.RESULT_FILE_NAME)); + boolean updateMonitors = currentRun % refreshRate == 0 || currentRun == numberOfRuns - 1; + Thread resultThread = getResultThread(resFile, experimentParameters, monitor, progressMonitor, updateMonitors, currentRun); + resultThread.run(); + + process = null; + + progressMonitor.worked(1); + currentRun++; + + } + + private SimulationLocation simulationLocation; + private IModelicaMonitor monitor; + private IProgressMonitor progressMonitor; +// private HashMap experimentParameters; + private int currentRun = 0; + private int refreshRate = 1; + private List parameters = new ArrayList(); + + @Override + protected void runModelica(SimulationLocation simulationLocation, IModelicaMonitor monitor, IProgressMonitor progressMonitor, HashMap experimentParameters, HashMap changes) throws IOException { + results = null; + + this.simulationLocation = simulationLocation; + this.monitor = monitor; + this.progressMonitor = progressMonitor; + + if (changes == null) { + changes = new HashMap(); + } + + String version = ModelicaManager.getOMVersion(simulationLocation.omHome); + experimentParameters.put(ModelicaManager.OMC_VERSION, version); + + + loadConfiguration(); + + currentRun = 0; + + + findValuesAndRun(parameters, changes, experimentParameters); + } + + private void loadConfiguration(){ + try { + session.syncRequest(new ReadRequest() { + @Override + public void run(ReadGraph graph) throws DatabaseException { + + SysdynResource SR = SysdynResource.getInstance(graph); + + Integer rRate = graph.getPossibleRelatedValue(experiment, SR.SensitivityAnalysisExperiment_resultRefreshRate, Bindings.INTEGER); + if(rRate != null) + refreshRate = rRate; + + Resource parameterListResource = graph.getPossibleObject(experiment, SR.SensitivityAnalysisExperiment_parameterList); + List parameterResources = ListUtils.toList(graph, parameterListResource); + + if(parameters != null) { + parameters.clear(); + for(Resource p : parameterResources) { + SensitivityExperimentParameter parameter = graph.adapt(p, SensitivityExperimentParameter.class); + if (parameter.getFullName() != null) + parameters.add(parameter); + } + } + } + }); + } catch (DatabaseException e) { + e.printStackTrace(); + } + } + + /** + * Get a thread for reading and saving reuslts from a normal simulation + * @param simulationLocation + * @param inits + * @param monitor + * @param progressMonitor + * @param currentRun + * @return + */ + protected Thread getResultThread(final File resFile, + final HashMap experimentParameters, + final IModelicaMonitor monitor, + final IProgressMonitor progressMonitor, + final boolean updateMonitors, + final int currentRun) { + return new Thread() { + @Override + public void run() { + try { + process.waitFor(); + + if(!canceled) { + // Get and store results + SimulationResult result; + if(resFile.getName().endsWith(".csv")) + result = new CSVSimulationResult(); + else if(resFile.getName().endsWith(".plt")) + result = new SimulationResult(); + else + result = new MatSimulationResult(); // The latest format + + // The interval of results saved. Every result? Every other result? etc... + int outIntervalInt = 1; + String outputInterval = experimentParameters.get(ModelicaKeys.OUTPUT_INTERVAL); + if(outputInterval != null) { + String stepTime = experimentParameters.get(ModelicaKeys.STEP_VALUE); + String stopTime = experimentParameters.get(ModelicaKeys.STOP_VALUE); + + Double step = Double.parseDouble(stepTime); + Double stop = Double.parseDouble(stopTime); + Double outInterval = Double.parseDouble(outputInterval); + + outIntervalInt = (int)getInterval(outInterval, step); + // Actually you might be able to use an outInterval one or two longer. + int maxIntervalInt = (int)Math.round(stop / step); + if (outIntervalInt > maxIntervalInt) + outIntervalInt = maxIntervalInt; + } + + result.initRead(resFile); + result.readTime(resFile, outIntervalInt); + //result.readInits(simulationLocation.initFile); // Parameter values are read from .mat + result.filter(); + + MemoryResult currentResult = new MemoryResult(null, null); + getCurrentResults().add(currentResult); + currentResult.setResult(result); + currentResult.setResultFile(resFile); + currentResult.setResultIndex(currentRun); + + if(updateMonitors) + resultsChanged(); + + simulate(false); + + String errorString = result.getResultReadErrors(); + if(errorString != null && !errorString.isEmpty()) + monitor.message(errorString); + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }; + } + + public ArrayList getCurrentResults() { + if(this.results == null) { + this.results = new ArrayList(); + } + return this.results; + } + + @Override + public Collection getActiveResults() { + ArrayList result = new ArrayList(); + result.addAll(getCurrentResults()); + result.addAll(sysdynModel.getDisplayedResults()); + return result; + } + + @Override + public MemoryResult getCurrentResult() { + if (this.results == null || this.results.size() < 1) + return null; + /* There should be a better alternative solution for this. Currently + * the return value is next to nonsense. + */ + return this.results.get(0); + } + + @Override + public void resultsChanged() { + long time = System.nanoTime(); + updateSubscriptions(); + previousVariableUpdateTime = time; + } + + @Override + public void saveState() { + if(results == null || !(results instanceof ArrayList)) + return; + SaveResultSetJob saveResultSetJob = new SaveResultSetJob((OldSysdynExperiment)this, session, results); + saveResultSetJob.schedule(); + } + + @Override + public int numberOfSimulationRunSteps() { + try { + Integer numberOfIterations = session.syncRequest(new Read() { + @Override + public Integer perform(ReadGraph graph) throws DatabaseException { + SysdynResource SR = SysdynResource.getInstance(graph); + Integer numberOfIterations = graph.getPossibleRelatedValue(experiment, SR.SensitivityAnalysisExperiment_numberOfValues, Bindings.INTEGER); + + return numberOfIterations; + } + }); + + if(numberOfIterations == null) + numberOfIterations = 0; + + // 3 steps before sensitivity iterations + return 3 + numberOfIterations; + } catch (DatabaseException e) { + e.printStackTrace(); + } + + return super.numberOfSimulationRunSteps(); + + } + + + @Override + public synchronized void simulate(IModelicaMonitor monitor, IProgressMonitor progressMonitor, String modelName) throws IOException { + + omcVersion = ModelicaManager.getDefaultOMVersion(); + + // Make sure that omc version is 1.9 or higher. + // Builtin version during this change is 1.9 beta 4 + if(omcVersion != null) { + try { + double v = Double.parseDouble(omcVersion.substring(0, 3)); + if(v < 1.9) { + monitor.message("Error: Sensitivity analysis requires OMC version >= 1.9 \n" + + "Current version is " + omcVersion +"\n" + + "Change version from Window->Preferences->Modelica"); + simulate(false); + return; + } + } catch (NumberFormatException e) {} + } + + super.simulate(monitor, progressMonitor, modelName); + } +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/VariableSubscriptionManager.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/VariableSubscriptionManager.java new file mode 100644 index 00000000..d55010c9 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/VariableSubscriptionManager.java @@ -0,0 +1,16 @@ +package org.simantics.sysdyn.manager; + +import org.simantics.sysdyn.adapter.VariableValueSubscription; + +@SuppressWarnings("rawtypes") +public interface VariableSubscriptionManager { + + public void addVariableValueSubscription(VariableValueSubscription subscription); + + public void removeVariableValueSubscription(VariableValueSubscription subscription); + + public VariableValueSubscription[] getListenerSnapshot(); + + public void updateSubscriptions(); + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelExport/ExportConstants.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelExport/ExportConstants.java new file mode 100644 index 00000000..19695ffc --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelExport/ExportConstants.java @@ -0,0 +1,10 @@ +package org.simantics.sysdyn.modelExport; + +public class ExportConstants { + + public static final String MODEL_FILE_EXTENSION = ".sysdyn"; + public static final String CURRENT_MODEL_EXPORT_FORMAT = ".sysdyn"; + public static final int CURRENT_MODEL_EXPORT_VERSION = 1; + //public static final int SMALLEST_MIGRATED_MODEL_EXPORT_VERSION = 0; + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelExport/SysdynModelExporter.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelExport/SysdynModelExporter.java new file mode 100644 index 00000000..333a654d --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelExport/SysdynModelExporter.java @@ -0,0 +1,133 @@ +package org.simantics.sysdyn.modelExport; + +import gnu.trove.map.hash.THashMap; + +import java.io.File; +import java.lang.reflect.InvocationTargetException; +import java.text.DateFormat; +import java.util.Date; +import java.util.LinkedList; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.SubMonitor; +import org.simantics.Simantics; +import org.simantics.databoard.binding.mutable.Variant; +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.Session; +import org.simantics.db.common.request.ObjectsWithType; +import org.simantics.db.common.request.ReadRequest; +import org.simantics.db.common.request.UniqueRead; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.adapter.CopyHandler; +import org.simantics.db.layer0.util.ClipboardUtils; +import org.simantics.db.layer0.util.ModelDependenciesBean; +import org.simantics.db.layer0.util.ModelDependency; +import org.simantics.db.layer0.util.ModelTransferableGraphSource; +import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest; +import org.simantics.db.layer0.util.SimanticsClipboard.Representation; +import org.simantics.db.layer0.util.SimanticsClipboardImpl; +import org.simantics.db.layer0.util.SimanticsKeys; +import org.simantics.db.layer0.util.TransferableGraphConfiguration2; +import org.simantics.graph.db.TransferableGraphs; +import org.simantics.graph.representation.TransferableGraph1; +import org.simantics.layer0.Layer0; +import org.simantics.modeling.ModelingResources; + +public class SysdynModelExporter { + + private SysdynModelExporter() { + } + + + public static void exportModel(IProgressMonitor monitor, final Resource model, File exportLocation, String description, boolean dependencies) throws InvocationTargetException { + try { + final SubMonitor mon = SubMonitor.convert(monitor, 100); + mon.beginTask("Exporting Sysdyn Model...", 100); + final Map tgExtensions = new THashMap(); + Session session = Simantics.getSession(); + if (dependencies) { + session.syncRequest(new ReadRequest() { + + @Override + public void run(ReadGraph graph) throws DatabaseException { + mon.setTaskName("Scanning model dependencies.."); + mon.worked(10); + LinkedList modelDependencies = new LinkedList(); + scanDependencies(graph, model, modelDependencies); + if (!modelDependencies.isEmpty()) + tgExtensions.put(ModelDependenciesBean.EXTENSION_KEY, new Variant(ModelDependenciesBean.BINDING, new ModelDependenciesBean(modelDependencies.toArray(new ModelDependency[modelDependencies.size()])))); + } + + private void scanDependencies(ReadGraph graph, Resource resource, LinkedList modelDependencies) throws DatabaseException { + Layer0 L0 = Layer0.getInstance(graph); + ModelingResources MOD = ModelingResources.getInstance(graph); + for(Resource library : graph.syncRequest(new ObjectsWithType(resource, L0.IsLinkedTo, MOD.SharedOntology))) { + String uri = graph.getPossibleURI(library); + if(uri == null) continue; + CopyHandler ch = graph.adapt(library, CopyHandler.class); + SimanticsClipboardImpl clipboard = new SimanticsClipboardImpl(); + ch.copyToClipboard(graph, clipboard); + for (Set object : clipboard.getContents()) { + TransferableGraph1 tg = ClipboardUtils.accept(graph, object, SimanticsKeys.KEY_TRANSFERABLE_GRAPH); + if(tg != null) modelDependencies.addFirst(new ModelDependency(uri, tg)); + } + scanDependencies(graph, library, modelDependencies); + } + } + }); + } + + mon.setTaskName("Creating transferable graph source..."); + mon.worked(10); + ModelTransferableGraphSource source = session.sync(new UniqueRead() { + @Override + public ModelTransferableGraphSource perform(ReadGraph graph) throws DatabaseException { + mon.worked(10); + TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, model); + mon.worked(10); + if (!tgExtensions.isEmpty()) + conf.baseExtensions.putAll(tgExtensions); + mon.worked(10); + return new ModelTransferableGraphSourceRequest(conf).perform(graph); + } + }); + + mon.worked(10); + mon.setTaskName("Writing metadata..."); + TreeMap metadata = getModelExportMetadata(description); + mon.worked(10); + mon.setTaskName("Writing transferable graph..."); + + try { + TransferableGraphs.writeTransferableGraph(session, + ExportConstants.CURRENT_MODEL_EXPORT_FORMAT, ExportConstants.CURRENT_MODEL_EXPORT_VERSION, metadata, source, exportLocation); + mon.worked(20); + source.closeStreams(); + } catch (Exception e) { + throw new InvocationTargetException(e); + } + + for(File f : source.getFiles()) + f.delete(); + + mon.worked(10); + mon.setTaskName("Done!"); + } catch (DatabaseException e) { + throw new InvocationTargetException(e); + } + } + + + private static TreeMap getModelExportMetadata(String description) { + TreeMap metadata = new TreeMap(); + metadata.put("date", Variant.ofInstance(DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date()))); + metadata.put("author", Variant.ofInstance(System.getProperty("user.name", ""))); + metadata.put("description", Variant.ofInstance(description)); + + return metadata; + } +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/BPMNParser.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/BPMNParser.java new file mode 100644 index 00000000..d273e94b --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/BPMNParser.java @@ -0,0 +1,105 @@ +package org.simantics.sysdyn.modelImport; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; + +import org.simantics.sysdyn.modelImport.bpmn.BPMNDiagram; +import org.simantics.sysdyn.modelImport.bpmn.TDefinitions; +import org.simantics.sysdyn.modelImport.bpmn.TEndEvent; +import org.simantics.sysdyn.modelImport.bpmn.TEvent; +import org.simantics.sysdyn.modelImport.bpmn.TFlowElement; +import org.simantics.sysdyn.modelImport.bpmn.TGateway; +import org.simantics.sysdyn.modelImport.bpmn.TProcess; +import org.simantics.sysdyn.modelImport.bpmn.TSequenceFlow; +import org.simantics.sysdyn.modelImport.bpmn.TStartEvent; +import org.simantics.sysdyn.modelImport.bpmn.TTask; +import org.simantics.sysdyn.modelImport.model.Cloud; +import org.simantics.sysdyn.modelImport.model.Connection; +import org.simantics.sysdyn.modelImport.model.Flow; +import org.simantics.sysdyn.modelImport.model.Model; +import org.simantics.sysdyn.modelImport.model.Stock; +import org.simantics.sysdyn.modelImport.model.Symbol; +import org.simantics.sysdyn.modelImport.model.Valve; +import org.simantics.sysdyn.modelImport.model.Valve.Orientation; +import org.simantics.sysdyn.modelImport.model.Valve.TextPosition; + +public class BPMNParser implements IModelParser { + + private static final double[] DEF_DIM = { 1, 1, 0, 0 }; + + @Override + public Model parse(File file) throws Exception { + Map symbols = new HashMap(); + Map connections = new HashMap(); + + Model model = new Model("BPMN prototype"); + + JAXBContext context = JAXBContext.newInstance("org.simantics.sysdyn.modelImport.bpmn"); + JAXBElement parent = (JAXBElement)context.createUnmarshaller().unmarshal(file); + + TDefinitions definitions = (TDefinitions)parent.getValue(); + + // TODO: can there be more than one process and/or diagram? + + TProcess process = (TProcess)definitions.getRootElement().iterator().next().getValue(); + + System.err.println("process "+process.getId()); + + for (int i = 0; i < process.getFlowElement().size(); i++) { + TFlowElement element = (TFlowElement)process.getFlowElement().get(i).getValue(); + // start and end events should be clouds + if (element instanceof TStartEvent || element instanceof TEndEvent) { + System.err.println("start or end event"); + TEvent event = (TEvent)element; + + Cloud cloud = new Cloud(DEF_DIM); + symbols.put(event, cloud); + model.addSymbol(cloud); + } + else if (element instanceof TEvent) { + System.err.println("events other than start or end events are nod handled"); + } + else if (element instanceof TGateway) { + System.err.println("gateway"); + } + else if (element instanceof TTask) { + System.err.println("task"); + TTask task = (TTask)element; + + Stock stock = new Stock(DEF_DIM, task.getName(), null, null, null, null); + symbols.put(task, stock); + model.addVariable(stock); + } + else if (element instanceof TSequenceFlow) { + System.err.println("sequence"); + TSequenceFlow sequence = (TSequenceFlow)element; + + Symbol tail = symbols.get(sequence.getSourceRef()); + Symbol head = symbols.get(sequence.getTargetRef()); + + String name = sequence.getName(); + + Valve valve = new Valve(DEF_DIM, sequence.getId(), null, null, null, null, Orientation.HORIZONTAL, TextPosition.UNSET); + + Flow first = new Flow(tail, valve); + Flow second = new Flow(valve, head); + + model.addVariable(valve); + model.addConnection(first); + model.addConnection(second); + } + else { + System.err.println("element type "+element.getClass()+" not handled"); + } + } + + BPMNDiagram diagram = (BPMNDiagram)definitions.getBPMNDiagram().iterator().next(); + + return model; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/IModelParser.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/IModelParser.java new file mode 100644 index 00000000..a179b6c5 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/IModelParser.java @@ -0,0 +1,9 @@ +package org.simantics.sysdyn.modelImport; + +import java.io.File; + +import org.simantics.sysdyn.modelImport.model.Model; + +public interface IModelParser { + public Model parse(File file) throws Exception; +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/MdlParser.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/MdlParser.java new file mode 100644 index 00000000..876390a5 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/MdlParser.java @@ -0,0 +1,325 @@ +/******************************************************************************* + * Copyright (c) 2007, 2011 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.sysdyn.modelImport; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStreamReader; +import java.util.regex.Pattern; + +import org.simantics.sysdyn.modelImport.mdl.Declaration; +import org.simantics.sysdyn.modelImport.mdl.Lookup; +import org.simantics.sysdyn.modelImport.mdl.MdlModel; +import org.simantics.sysdyn.modelImport.mdl.MdlVariable; +import org.simantics.sysdyn.modelImport.mdl.Sketch; +import org.simantics.sysdyn.modelImport.mdl.SketchComment; +import org.simantics.sysdyn.modelImport.mdl.SketchConnection; +import org.simantics.sysdyn.modelImport.mdl.SketchObject; +import org.simantics.sysdyn.modelImport.mdl.SketchValve; +import org.simantics.sysdyn.modelImport.mdl.SketchVariable; +import org.simantics.sysdyn.modelImport.mdl.Subscript; +import org.simantics.sysdyn.modelImport.mdl.SubscriptVariable; +import org.simantics.sysdyn.modelImport.model.Comment; +import org.simantics.sysdyn.modelImport.model.Connection; +import org.simantics.sysdyn.modelImport.model.Model; +import org.simantics.sysdyn.modelImport.model.Variable; +import org.simantics.sysdyn.modelImport.model.Shadow; +import org.simantics.sysdyn.modelImport.model.Symbol; +import org.simantics.sysdyn.modelImport.model.Valve; + +public class MdlParser implements IModelParser { + + private static final String UTF_8 = "{UTF-8}"; + private static final String SKETCH_VERSION = "V300"; + private static final String SKETCH_START = "\\\\\\---///"; + private static final String SKETCH_END = "///---\\\\\\"; + + private static final String PARAMETER_START = "INITIAL TIME"; + private static final String PARAMETER_STOP = "FINAL TIME"; + private static final String PARAMETER_STEP = "TIME STEP"; + + @Override + public Model parse(File file) throws Exception { + // generate a mdl model based on the contents of the file + MdlModel mdl = parseFile(file); + + // generate a sysdyn model from the mdl model + Model model = new Model(mdl.getName()); + + // add (necessary) enumerations + for (Subscript subscript : mdl.getAllSubscripts()) { + if (!subscript.isEquivalent()) + model.addEnumeration(subscript.getEnumeration()); + } + + // add lookup functions + for (Lookup lookup : mdl.getAllLookups()) { + model.addFunction(lookup.getFunction()); + } + + int offset = 0; + + // add sketch labels and independent elements + for (Sketch sketch : mdl.getSketches()) { + + // add the sketch label to the diagram for the sake of clarity + model.addSymbol(new Comment( + MdlUtil.getSysdynDimensions(offset, 0, -1, -1), + "=== VENSIM SKETCH: "+sketch.getName()+" ======>")); + sketch.setLocation(offset, 20); + + for (SketchComment comment : sketch.getComments()) { + Symbol symbol = comment.getSymbol(); + if (symbol != null) { + comment.setModelObject(symbol); + model.addSymbol(symbol); + } + } + + for (SketchValve valve : sketch.getValves()) { + Valve symbol = valve.getSymbol(); + if (symbol != null) { + valve.setModelObject(symbol); + model.addVariable(symbol); + } + } + + for (SketchVariable variable : sketch.getNonShadowVariables()) { + Variable symbol = variable.getSymbol(); + if (symbol != null) { + variable.setModelObject(symbol); + model.addVariable(symbol); + } + } + + offset += sketch.getWidth(); + } + + // add dependent elements + for (Sketch sketch : mdl.getSketches()) { + for (SketchVariable variable : sketch.getShadowVariables()) { + Variable original = model.getVariable(variable.getName()); + if (original != null) { + // create a shadow variable if the original variable exists + Shadow symbol = new Shadow(variable.getDimensions(), original); + variable.setModelObject(symbol); + model.addShadow(symbol); + } + else { + // create a new original variable instead of a shadow variable if + // the original variable does not exist + Variable symbol = variable.getSymbol(); + if (symbol != null) { + variable.setModelObject(symbol); + model.addVariable(symbol); + } + } + } + + for (SketchConnection connection : sketch.getConnections()) { + Connection conn = connection.getConnection(); + if (conn != null) { + connection.setModelObject(conn); + model.addConnection(conn); + } + } + } + + // Set simulation parameters + MdlVariable start = mdl.getVariable(PARAMETER_START); + if (start != null && Pattern.matches(MdlUtil.DBL, start.getExpressionString())) + model.setStartTime(Double.parseDouble(start.getExpressionString())); + + MdlVariable stop = mdl.getVariable(PARAMETER_STOP); + if (stop != null && Pattern.matches(MdlUtil.DBL, stop.getExpressionString())) + model.setStopTime(Double.parseDouble(stop.getExpressionString())); + + MdlVariable step = mdl.getVariable(PARAMETER_STEP); + if (step != null && Pattern.matches(MdlUtil.DBL, step.getExpressionString())) { + model.setTimeStep(Double.parseDouble(step.getExpressionString())); + // TODO: for some reason sysdyn only accepts certain time units + // so this most definitely does not work in all cases + String unit = step.getUnit(); + if (unit.contains("[")) { + unit = unit.substring(0, unit.indexOf('[')).trim(); + } + model.setTimeUnit(unit.toLowerCase()); + } + + + // TODO: unit and result step thingamajig + + return model; + } + + private static MdlModel parseFile(File file) throws Exception { + // strip the file suffix from file name + String name = file.getName(); + if (file.getName().contains(".")) { + name = name.substring(0, name.indexOf('.')); + } + + MdlModel mdl = new MdlModel(name); + + // peek at the first line to see if we need to use UTF-8 + BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); + String line = reader.readLine(); + + if (line == null) { + // file is empty, nothing to do here + reader.close(); + return null; + } + + if (line.startsWith(UTF_8)) { + reader.close(); + reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); + // skip the first line + reader.readLine(); + line = reader.readLine(); + } + + // START READING VARIABLE DATA + + // keep track of the current category + String category = null; + + do { + // skip empty lines + if (line.isEmpty()) + continue; + + // combine the (possible) variable declaration into one line + StringBuilder buffer = new StringBuilder(); + do { + // strip leading whitespace if present + line = line.replaceFirst("^\\s*", ""); + // strip trailing '\' if present + line = line.replaceFirst("\\\\$", ""); + + buffer.append(line); + + // each variable declaration ends with '|' + if (line.endsWith("|")) + break; + } while ((line = reader.readLine()) != null); + String str = buffer.toString(); + + String cat; + Declaration decl; + + // parse the (possible) variable declaration + if ((cat = Declaration.parseCategory(str)) != null) { + category = cat; + } + else if ((decl = MdlVariable.getPossible(str, mdl)) != null) { + mdl.addVariable((MdlVariable)decl, category); + } + else if ((decl = SubscriptVariable.getPossible(str, mdl)) != null) { + mdl.addSubscriptVariable((SubscriptVariable)decl, category); + } + else if ((decl = Lookup.getPossible(str, mdl)) != null) { + mdl.addLookup((Lookup)decl); + } + else if ((decl = Subscript.getPossible(str, mdl)) != null) { + mdl.addSubscript((Subscript)decl); + } + else { + // if we got this far, the variable could not be parsed + throw new Exception("unrecognized variable "+str); + } + + } while ((line = reader.readLine()) != null && !line.startsWith(SKETCH_START)); + + // END READING VARIABLE DATA + + if (line == null) { + throw new Exception("unexpected end of file"); + } + + // START READING SKETCH DATA + + // keep track of the current sketch + Sketch sketch = null; + + do { + // skip empty lines + if (line.isEmpty()) + continue; + + SketchObject so; + + if (line.startsWith(SKETCH_START)) { + sketch = new Sketch(mdl); + mdl.addSketch(sketch); + } + else if (line.startsWith(SKETCH_VERSION)) { + // version declaration, nothing to do here + } + else if (line.startsWith("*")) { + sketch.setName(line.substring(1)); + } + else if (line.startsWith("$")) { + // font declaration, nothing to do here + } + else if ((so = SketchConnection.getPossible(line, sketch)) != null) { + sketch.addConnection((SketchConnection)so); + } + else if ((so = SketchVariable.getPossible(line, sketch)) != null) { + sketch.addVariable((SketchVariable)so); + } + else if ((so = SketchValve.getPossible(line, sketch)) != null) { + SketchValve valve = (SketchValve)so; + // the next row after a valve should always the variable associated with the valve + SketchVariable attached = SketchVariable.getPossible(reader.readLine(), sketch); + if (attached == null || !attached.isAttached()) { + throw new Exception("attached variable not found for valve"); + } + valve.setAttached(attached); + sketch.addValve(valve); + } + else if ((so = SketchComment.getPossible(line, sketch)) != null) { + SketchComment comment = (SketchComment)so; + if (comment.hasTextLine()) { + comment.setText(reader.readLine()); + } + // do not add i/o objects to the sketch currently + if (!comment.isInputOutput()) + sketch.addComment(comment); + } + else { + // if we got this far, the element could not be parsed + throw new Exception("unrecognized element "+line); + } + + } while ((line = reader.readLine()) != null && !line.startsWith(SKETCH_END)); + + // END READING SKETCH DATA + + if (line == null) { + throw new Exception("unexpected end of file"); + } + + // START READING OTHER DATA + + do { + // TODO: is there anything relevant here? + } while ((line = reader.readLine()) != null); + + // END READING OTHER DATA + + reader.close(); + return mdl; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/MdlUtil.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/MdlUtil.java new file mode 100644 index 00000000..980948d0 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/MdlUtil.java @@ -0,0 +1,310 @@ +package org.simantics.sysdyn.modelImport; + +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.simantics.sysdyn.modelImport.mdl.Lookup; +import org.simantics.sysdyn.modelImport.mdl.MdlModel; + +public class MdlUtil { + + // multiplier for dimension conversion between vensim and sysdyn + private static final double SCALE_MULTIPLIER = 0.45; + + // most of this is based on the documentation of the .mdl file format + // available in http://www.vensim.com/documentation/24305.htm + + // some regular expressions that are used commonly in the parser + public static final String DBL = "[+-]?(?:NaN|Infinity|\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?)"; + public static final String DBL_G = "("+DBL+")"; + public static final String INT = "[+-]?\\d+"; + public static final String INT_G = "("+INT+")"; + + // matches a basic vensim name (starts with a letter, may contain any word + // characters and white space) + public static final String BASIC_NAME = + "[A-Za-z]\\w*(?:\\s+\\w+)*"; + // matches a special vensim name (starts and ends with a quotation mark, + // may contain escaped special characters) + public static final String SPECIAL_NAME = + "\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\""; + + // matches a vensim variable (either basic name or special name) + public static final String VARIABLE = + "("+BASIC_NAME+"|"+SPECIAL_NAME+")"; + // matches a vensim variable inside an expression (basic name not followed + // by an open parenthesis or a special name) + public static final String VARIABLE_EXPRESSION = + "([A-Za-z](?![\\s\\w]*\\()\\w*(?:\\s+\\w+)*|"+SPECIAL_NAME+")"; + // matches a vensim subscript variable (basic name with a list of indices) + public static final String SUBSCRIPT = + "("+BASIC_NAME+")\\[("+BASIC_NAME+"\\!?(?:,"+BASIC_NAME+"\\!?)*)\\]"; + // matches a vensim function (basic name followed by an open parenthesis) + public static final String FUNCTION = + "("+BASIC_NAME+")\\s*\\("; + + public static String normalize(String str) { + // start by removing all tabs from the string, not really necessary + // but does make the equation cleaner + str = str.replaceAll("\t", ""); + + // normalize functions + str = normalizeFunctions(str); + // normalize variables + str = normalizeVariables(str); + + // replace inline operations + str = str.replaceAll(":AND:", " and "); + str = str.replaceAll(":OR:", " or "); + + // foo^-bar does not work in Modelica, it needs to be changed to foo^(-bar) + str = addParenthesesToExponents(str); + + // NOTE: something like this must be done to replace Vensim comparison + // "=" with Modelica comparison "==" but this solution breaks geq and leq + //str = str.replaceAll("=", "=="); + + return str; + } + + private static String normalizeVariables(String expression) { + StringBuilder result = new StringBuilder(); + int offset = 0; + + Matcher matcher = Pattern.compile(VARIABLE_EXPRESSION).matcher(expression); + while (matcher.find()) { + result.append(expression.substring(offset, matcher.start())); + + String variable = matcher.group(1); + + // TODO: fix this after proper support for quoted variable names + // is implemented + + if (variable.equalsIgnoreCase("time")) { + // replace all references to simulation time with references + // to the special purpose time variable + result.append("time"); + } + else if (variable.startsWith("\"") && variable.endsWith("\"")) { + // replace double quotes with single quotes in quoted variable + // names as per modelica syntax (currently useless and might + // actually break something) + result.append('\''); + result.append(variable.substring(1, variable.length() - 1)); + result.append('\''); + } + else { + // in all other cases, manipulate variable names slightly to + // make them conform to Modelica syntax (the proper way to do + // this would be to simply quote problematic variable names + // but quoted variable names are currently broken in sysdyn so + // that is not an option) + + // capitalize each part of the variable name to prevent + // collisions with reserved keywords (e.g. "public") + String[] parts = variable.split("\\s+"); + for (int i = 0; i < parts.length; i++) { + // a part of a variable name can not start with a number so + // concatenate the parts if this is the case + if (i > 0 && !Character.isDigit(parts[i].charAt(0))) + result.append(' '); + result.append(parts[i].substring(0, 1).toUpperCase() + parts[i].substring(1)); + } + } + + offset = matcher.end(); + } + if (offset < expression.length()) { + result.append(expression.substring(offset)); + } + + return result.toString(); + } + + private static String normalizeFunctions(String expression) { + StringBuilder result = new StringBuilder(); + int offset = 0; + + Matcher matcher = Pattern.compile(FUNCTION).matcher(expression); + while (matcher.find()) { + result.append(expression.substring(offset, matcher.start())); + + String function = matcher.group(1); + + if (function.equalsIgnoreCase("sum")) { + // vensim "sum" is similar to modelica "sum" if operations + // are replaced with dot-operations (e.g. * with .*) inside + // the parameters + result.append("sum("); + int closing = expression.indexOf(')', matcher.end()); + String parameters = expression.substring(matcher.end(), closing); + parameters = parameters.replaceAll("\\*", ".*"); + parameters = parameters.replaceAll("/", "./"); + parameters = parameters.replaceAll("\\+", ".+"); + parameters = parameters.replaceAll("-", ".-"); + result.append(parameters); + offset = closing; + } + else if (function.equalsIgnoreCase("if then else")) { + result.append("IFTHENELSE("); + offset = matcher.end(); + } + else { + // this will also capitalize lookups, is this ok? + result.append(function.toUpperCase()+"("); + offset = matcher.end(); + } + } + if (offset < expression.length()) { + result.append(expression.substring(offset)); + } + + return result.toString(); + } + + private static String addParenthesesToExponents(String expression) { + if (!expression.contains("^")) { + return expression; + } + + StringBuilder result = new StringBuilder(); + int offset = 0; + + Matcher matcher = Pattern.compile("\\^\\s*-\\s*"+VARIABLE_EXPRESSION).matcher(expression); + while (matcher.find()) { + result.append(expression.substring(offset, matcher.start())); + + result.append("^(-").append(matcher.group(1)).append(")"); + + offset = matcher.end(); + } + if (offset < expression.length()) { + result.append(expression.substring(offset)); + } + + return result.toString(); + } + + public static String finalize(String expression, MdlModel mdl) { + expression = expandIterations(expression, mdl); + expression = renameLookups(expression, mdl); + + return expression; + } + + private static String expandIterations(String expression, MdlModel mdl) { + StringBuilder result = new StringBuilder(); + int offset = 0; + + Matcher matcher = Pattern.compile(SUBSCRIPT).matcher(expression); + while (matcher.find()) { + result.append(expression.substring(offset, matcher.start())); + + String name = matcher.group(1); + String[] indices = matcher.group(2).split(","); + + result.append(name); + + result.append('['); + for (int i = 0; i < indices.length; i++) { + if (i > 0) + result.append(','); + + if (indices[i].endsWith("!")) { + String subscript = indices[i].substring(0, indices[i].length() - 1); + List values = mdl.getSubscript(subscript).getValues(); + result.append('{'); + for (int j = 0; j < values.size(); j++) { + if (j > 0) + result.append(','); + result.append(values.get(j)); + } + result.append('}'); + } + else { + result.append(indices[i]); + } + } + result.append(']'); + + offset = matcher.end(); + } + if (offset < expression.length()) { + result.append(expression.substring(offset)); + } + + return result.toString(); + } + + private static String renameLookups(String expression, MdlModel mdl) { + StringBuilder result = new StringBuilder(); + int offset = 0; + + Matcher matcher = Pattern.compile(FUNCTION).matcher(expression); + while (matcher.find()) { + result.append(expression.substring(offset, matcher.start())); + + String name = matcher.group(1); + + Lookup potential = mdl.getLookup(name); + + if (potential != null) { + name = name.replaceAll("\\s+", ""); + } + + result.append(name+"("); + offset = matcher.end(); + } + if (offset < expression.length()) { + result.append(expression.substring(offset)); + } + + return result.toString(); + } + + public static String replaceSubscripts(String expression, String subscript, String replacement) { + StringBuilder result = new StringBuilder(); + int offset = 0; + + Matcher matcher = Pattern.compile(SUBSCRIPT).matcher(expression); + while (matcher.find()) { + result.append(expression.substring(offset, matcher.start())); + + String name = matcher.group(1); + String[] indices = matcher.group(2).split(","); + + result.append(name); + + result.append('['); + for (int i = 0; i < indices.length; i++) { + if (i > 0) + result.append(','); + + if (indices[i].equals(subscript)) { + result.append(replacement); + } + else { + result.append(indices[i]); + } + } + result.append(']'); + + offset = matcher.end(); + } + if (offset < expression.length()) { + result.append(expression.substring(offset)); + } + + return result.toString(); + } + + public static double[] getSysdynDimensions(int x, int y, int width, int height) { + return new double[] { + x * SCALE_MULTIPLIER, + y * SCALE_MULTIPLIER, + width * SCALE_MULTIPLIER, + height * SCALE_MULTIPLIER + }; + } +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNDiagram.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNDiagram.java new file mode 100644 index 00000000..8d0a94c1 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNDiagram.java @@ -0,0 +1,106 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.08.21 at 03:38:57 PM EEST +// + + +package org.simantics.sysdyn.modelImport.bpmn; + +import java.util.ArrayList; +import java.util.List; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for BPMNDiagram complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="BPMNDiagram">
+ *   <complexContent>
+ *     <extension base="{http://www.omg.org/spec/DD/20100524/DI}Diagram">
+ *       <sequence>
+ *         <element ref="{http://www.omg.org/spec/BPMN/20100524/DI}BPMNPlane"/>
+ *         <element ref="{http://www.omg.org/spec/BPMN/20100524/DI}BPMNLabelStyle" maxOccurs="unbounded" minOccurs="0"/>
+ *       </sequence>
+ *     </extension>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "BPMNDiagram", namespace = "http://www.omg.org/spec/BPMN/20100524/DI", propOrder = { + "bpmnPlane", + "bpmnLabelStyle" +}) +public class BPMNDiagram + extends Diagram +{ + + @XmlElement(name = "BPMNPlane", required = true) + protected BPMNPlane bpmnPlane; + @XmlElement(name = "BPMNLabelStyle") + protected List bpmnLabelStyle; + + /** + * Gets the value of the bpmnPlane property. + * + * @return + * possible object is + * {@link BPMNPlane } + * + */ + public BPMNPlane getBPMNPlane() { + return bpmnPlane; + } + + /** + * Sets the value of the bpmnPlane property. + * + * @param value + * allowed object is + * {@link BPMNPlane } + * + */ + public void setBPMNPlane(BPMNPlane value) { + this.bpmnPlane = value; + } + + /** + * Gets the value of the bpmnLabelStyle property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the bpmnLabelStyle property. + * + *

+ * For example, to add a new item, do as follows: + *

+     *    getBPMNLabelStyle().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link BPMNLabelStyle } + * + * + */ + public List getBPMNLabelStyle() { + if (bpmnLabelStyle == null) { + bpmnLabelStyle = new ArrayList(); + } + return this.bpmnLabelStyle; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNEdge.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNEdge.java new file mode 100644 index 00000000..be206c5f --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNEdge.java @@ -0,0 +1,182 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.08.21 at 03:38:57 PM EEST +// + + +package org.simantics.sysdyn.modelImport.bpmn; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; +import javax.xml.namespace.QName; + + +/** + *

Java class for BPMNEdge complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="BPMNEdge">
+ *   <complexContent>
+ *     <extension base="{http://www.omg.org/spec/DD/20100524/DI}LabeledEdge">
+ *       <sequence>
+ *         <element ref="{http://www.omg.org/spec/BPMN/20100524/DI}BPMNLabel" minOccurs="0"/>
+ *       </sequence>
+ *       <attribute name="bpmnElement" type="{http://www.w3.org/2001/XMLSchema}QName" />
+ *       <attribute name="sourceElement" type="{http://www.w3.org/2001/XMLSchema}QName" />
+ *       <attribute name="targetElement" type="{http://www.w3.org/2001/XMLSchema}QName" />
+ *       <attribute name="messageVisibleKind" type="{http://www.omg.org/spec/BPMN/20100524/DI}MessageVisibleKind" />
+ *       <anyAttribute processContents='lax' namespace='##other'/>
+ *     </extension>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "BPMNEdge", namespace = "http://www.omg.org/spec/BPMN/20100524/DI", propOrder = { + "bpmnLabel" +}) +public class BPMNEdge + extends LabeledEdge +{ + + @XmlElement(name = "BPMNLabel") + protected BPMNLabel bpmnLabel; + @XmlAttribute(name = "bpmnElement") + protected QName bpmnElement; + @XmlAttribute(name = "sourceElement") + protected QName sourceElement; + @XmlAttribute(name = "targetElement") + protected QName targetElement; + @XmlAttribute(name = "messageVisibleKind") + protected MessageVisibleKind messageVisibleKind; + + /** + * Gets the value of the bpmnLabel property. + * + * @return + * possible object is + * {@link BPMNLabel } + * + */ + public BPMNLabel getBPMNLabel() { + return bpmnLabel; + } + + /** + * Sets the value of the bpmnLabel property. + * + * @param value + * allowed object is + * {@link BPMNLabel } + * + */ + public void setBPMNLabel(BPMNLabel value) { + this.bpmnLabel = value; + } + + /** + * Gets the value of the bpmnElement property. + * + * @return + * possible object is + * {@link QName } + * + */ + public QName getBpmnElement() { + return bpmnElement; + } + + /** + * Sets the value of the bpmnElement property. + * + * @param value + * allowed object is + * {@link QName } + * + */ + public void setBpmnElement(QName value) { + this.bpmnElement = value; + } + + /** + * Gets the value of the sourceElement property. + * + * @return + * possible object is + * {@link QName } + * + */ + public QName getSourceElement() { + return sourceElement; + } + + /** + * Sets the value of the sourceElement property. + * + * @param value + * allowed object is + * {@link QName } + * + */ + public void setSourceElement(QName value) { + this.sourceElement = value; + } + + /** + * Gets the value of the targetElement property. + * + * @return + * possible object is + * {@link QName } + * + */ + public QName getTargetElement() { + return targetElement; + } + + /** + * Sets the value of the targetElement property. + * + * @param value + * allowed object is + * {@link QName } + * + */ + public void setTargetElement(QName value) { + this.targetElement = value; + } + + /** + * Gets the value of the messageVisibleKind property. + * + * @return + * possible object is + * {@link MessageVisibleKind } + * + */ + public MessageVisibleKind getMessageVisibleKind() { + return messageVisibleKind; + } + + /** + * Sets the value of the messageVisibleKind property. + * + * @param value + * allowed object is + * {@link MessageVisibleKind } + * + */ + public void setMessageVisibleKind(MessageVisibleKind value) { + this.messageVisibleKind = value; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNLabel.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNLabel.java new file mode 100644 index 00000000..89badd7a --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNLabel.java @@ -0,0 +1,69 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.08.21 at 03:38:57 PM EEST +// + + +package org.simantics.sysdyn.modelImport.bpmn; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlType; +import javax.xml.namespace.QName; + + +/** + *

Java class for BPMNLabel complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="BPMNLabel">
+ *   <complexContent>
+ *     <extension base="{http://www.omg.org/spec/DD/20100524/DI}Label">
+ *       <attribute name="labelStyle" type="{http://www.w3.org/2001/XMLSchema}QName" />
+ *       <anyAttribute processContents='lax' namespace='##other'/>
+ *     </extension>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "BPMNLabel", namespace = "http://www.omg.org/spec/BPMN/20100524/DI") +public class BPMNLabel + extends Label +{ + + @XmlAttribute(name = "labelStyle") + protected QName labelStyle; + + /** + * Gets the value of the labelStyle property. + * + * @return + * possible object is + * {@link QName } + * + */ + public QName getLabelStyle() { + return labelStyle; + } + + /** + * Sets the value of the labelStyle property. + * + * @param value + * allowed object is + * {@link QName } + * + */ + public void setLabelStyle(QName value) { + this.labelStyle = value; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNLabelStyle.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNLabelStyle.java new file mode 100644 index 00000000..d2bced50 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNLabelStyle.java @@ -0,0 +1,71 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.08.21 at 03:38:57 PM EEST +// + + +package org.simantics.sysdyn.modelImport.bpmn; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for BPMNLabelStyle complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="BPMNLabelStyle">
+ *   <complexContent>
+ *     <extension base="{http://www.omg.org/spec/DD/20100524/DI}Style">
+ *       <sequence>
+ *         <element ref="{http://www.omg.org/spec/DD/20100524/DC}Font"/>
+ *       </sequence>
+ *     </extension>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "BPMNLabelStyle", namespace = "http://www.omg.org/spec/BPMN/20100524/DI", propOrder = { + "font" +}) +public class BPMNLabelStyle + extends Style +{ + + @XmlElement(name = "Font", namespace = "http://www.omg.org/spec/DD/20100524/DC", required = true) + protected Font font; + + /** + * Gets the value of the font property. + * + * @return + * possible object is + * {@link Font } + * + */ + public Font getFont() { + return font; + } + + /** + * Sets the value of the font property. + * + * @param value + * allowed object is + * {@link Font } + * + */ + public void setFont(Font value) { + this.font = value; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNPlane.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNPlane.java new file mode 100644 index 00000000..8a49a312 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNPlane.java @@ -0,0 +1,69 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.08.21 at 03:38:57 PM EEST +// + + +package org.simantics.sysdyn.modelImport.bpmn; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlType; +import javax.xml.namespace.QName; + + +/** + *

Java class for BPMNPlane complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="BPMNPlane">
+ *   <complexContent>
+ *     <extension base="{http://www.omg.org/spec/DD/20100524/DI}Plane">
+ *       <attribute name="bpmnElement" type="{http://www.w3.org/2001/XMLSchema}QName" />
+ *       <anyAttribute processContents='lax' namespace='##other'/>
+ *     </extension>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "BPMNPlane", namespace = "http://www.omg.org/spec/BPMN/20100524/DI") +public class BPMNPlane + extends Plane +{ + + @XmlAttribute(name = "bpmnElement") + protected QName bpmnElement; + + /** + * Gets the value of the bpmnElement property. + * + * @return + * possible object is + * {@link QName } + * + */ + public QName getBpmnElement() { + return bpmnElement; + } + + /** + * Sets the value of the bpmnElement property. + * + * @param value + * allowed object is + * {@link QName } + * + */ + public void setBpmnElement(QName value) { + this.bpmnElement = value; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNShape.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNShape.java new file mode 100644 index 00000000..c2087077 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/BPMNShape.java @@ -0,0 +1,263 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.08.21 at 03:38:57 PM EEST +// + + +package org.simantics.sysdyn.modelImport.bpmn; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; +import javax.xml.namespace.QName; + + +/** + *

Java class for BPMNShape complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="BPMNShape">
+ *   <complexContent>
+ *     <extension base="{http://www.omg.org/spec/DD/20100524/DI}LabeledShape">
+ *       <sequence>
+ *         <element ref="{http://www.omg.org/spec/BPMN/20100524/DI}BPMNLabel" minOccurs="0"/>
+ *       </sequence>
+ *       <attribute name="bpmnElement" type="{http://www.w3.org/2001/XMLSchema}QName" />
+ *       <attribute name="isHorizontal" type="{http://www.w3.org/2001/XMLSchema}boolean" />
+ *       <attribute name="isExpanded" type="{http://www.w3.org/2001/XMLSchema}boolean" />
+ *       <attribute name="isMarkerVisible" type="{http://www.w3.org/2001/XMLSchema}boolean" />
+ *       <attribute name="isMessageVisible" type="{http://www.w3.org/2001/XMLSchema}boolean" />
+ *       <attribute name="participantBandKind" type="{http://www.omg.org/spec/BPMN/20100524/DI}ParticipantBandKind" />
+ *       <attribute name="choreographyActivityShape" type="{http://www.w3.org/2001/XMLSchema}QName" />
+ *       <anyAttribute processContents='lax' namespace='##other'/>
+ *     </extension>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "BPMNShape", namespace = "http://www.omg.org/spec/BPMN/20100524/DI", propOrder = { + "bpmnLabel" +}) +public class BPMNShape + extends LabeledShape +{ + + @XmlElement(name = "BPMNLabel") + protected BPMNLabel bpmnLabel; + @XmlAttribute(name = "bpmnElement") + protected QName bpmnElement; + @XmlAttribute(name = "isHorizontal") + protected Boolean isHorizontal; + @XmlAttribute(name = "isExpanded") + protected Boolean isExpanded; + @XmlAttribute(name = "isMarkerVisible") + protected Boolean isMarkerVisible; + @XmlAttribute(name = "isMessageVisible") + protected Boolean isMessageVisible; + @XmlAttribute(name = "participantBandKind") + protected ParticipantBandKind participantBandKind; + @XmlAttribute(name = "choreographyActivityShape") + protected QName choreographyActivityShape; + + /** + * Gets the value of the bpmnLabel property. + * + * @return + * possible object is + * {@link BPMNLabel } + * + */ + public BPMNLabel getBPMNLabel() { + return bpmnLabel; + } + + /** + * Sets the value of the bpmnLabel property. + * + * @param value + * allowed object is + * {@link BPMNLabel } + * + */ + public void setBPMNLabel(BPMNLabel value) { + this.bpmnLabel = value; + } + + /** + * Gets the value of the bpmnElement property. + * + * @return + * possible object is + * {@link QName } + * + */ + public QName getBpmnElement() { + return bpmnElement; + } + + /** + * Sets the value of the bpmnElement property. + * + * @param value + * allowed object is + * {@link QName } + * + */ + public void setBpmnElement(QName value) { + this.bpmnElement = value; + } + + /** + * Gets the value of the isHorizontal property. + * + * @return + * possible object is + * {@link Boolean } + * + */ + public Boolean isIsHorizontal() { + return isHorizontal; + } + + /** + * Sets the value of the isHorizontal property. + * + * @param value + * allowed object is + * {@link Boolean } + * + */ + public void setIsHorizontal(Boolean value) { + this.isHorizontal = value; + } + + /** + * Gets the value of the isExpanded property. + * + * @return + * possible object is + * {@link Boolean } + * + */ + public Boolean isIsExpanded() { + return isExpanded; + } + + /** + * Sets the value of the isExpanded property. + * + * @param value + * allowed object is + * {@link Boolean } + * + */ + public void setIsExpanded(Boolean value) { + this.isExpanded = value; + } + + /** + * Gets the value of the isMarkerVisible property. + * + * @return + * possible object is + * {@link Boolean } + * + */ + public Boolean isIsMarkerVisible() { + return isMarkerVisible; + } + + /** + * Sets the value of the isMarkerVisible property. + * + * @param value + * allowed object is + * {@link Boolean } + * + */ + public void setIsMarkerVisible(Boolean value) { + this.isMarkerVisible = value; + } + + /** + * Gets the value of the isMessageVisible property. + * + * @return + * possible object is + * {@link Boolean } + * + */ + public Boolean isIsMessageVisible() { + return isMessageVisible; + } + + /** + * Sets the value of the isMessageVisible property. + * + * @param value + * allowed object is + * {@link Boolean } + * + */ + public void setIsMessageVisible(Boolean value) { + this.isMessageVisible = value; + } + + /** + * Gets the value of the participantBandKind property. + * + * @return + * possible object is + * {@link ParticipantBandKind } + * + */ + public ParticipantBandKind getParticipantBandKind() { + return participantBandKind; + } + + /** + * Sets the value of the participantBandKind property. + * + * @param value + * allowed object is + * {@link ParticipantBandKind } + * + */ + public void setParticipantBandKind(ParticipantBandKind value) { + this.participantBandKind = value; + } + + /** + * Gets the value of the choreographyActivityShape property. + * + * @return + * possible object is + * {@link QName } + * + */ + public QName getChoreographyActivityShape() { + return choreographyActivityShape; + } + + /** + * Sets the value of the choreographyActivityShape property. + * + * @param value + * allowed object is + * {@link QName } + * + */ + public void setChoreographyActivityShape(QName value) { + this.choreographyActivityShape = value; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Bounds.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Bounds.java new file mode 100644 index 00000000..610d10db --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Bounds.java @@ -0,0 +1,114 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.08.21 at 03:38:57 PM EEST +// + + +package org.simantics.sysdyn.modelImport.bpmn; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for Bounds complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="Bounds">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <attribute name="x" use="required" type="{http://www.w3.org/2001/XMLSchema}double" />
+ *       <attribute name="y" use="required" type="{http://www.w3.org/2001/XMLSchema}double" />
+ *       <attribute name="width" use="required" type="{http://www.w3.org/2001/XMLSchema}double" />
+ *       <attribute name="height" use="required" type="{http://www.w3.org/2001/XMLSchema}double" />
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "Bounds", namespace = "http://www.omg.org/spec/DD/20100524/DC") +public class Bounds { + + @XmlAttribute(name = "x", required = true) + protected double x; + @XmlAttribute(name = "y", required = true) + protected double y; + @XmlAttribute(name = "width", required = true) + protected double width; + @XmlAttribute(name = "height", required = true) + protected double height; + + /** + * Gets the value of the x property. + * + */ + public double getX() { + return x; + } + + /** + * Sets the value of the x property. + * + */ + public void setX(double value) { + this.x = value; + } + + /** + * Gets the value of the y property. + * + */ + public double getY() { + return y; + } + + /** + * Sets the value of the y property. + * + */ + public void setY(double value) { + this.y = value; + } + + /** + * Gets the value of the width property. + * + */ + public double getWidth() { + return width; + } + + /** + * Sets the value of the width property. + * + */ + public void setWidth(double value) { + this.width = value; + } + + /** + * Gets the value of the height property. + * + */ + public double getHeight() { + return height; + } + + /** + * Sets the value of the height property. + * + */ + public void setHeight(double value) { + this.height = value; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Diagram.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Diagram.java new file mode 100644 index 00000000..db823e10 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Diagram.java @@ -0,0 +1,157 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.08.21 at 03:38:57 PM EEST +// + + +package org.simantics.sysdyn.modelImport.bpmn; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlID; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlSeeAlso; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + + +/** + *

Java class for Diagram complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="Diagram">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
+ *       <attribute name="documentation" type="{http://www.w3.org/2001/XMLSchema}string" />
+ *       <attribute name="resolution" type="{http://www.w3.org/2001/XMLSchema}double" />
+ *       <attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" />
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "Diagram", namespace = "http://www.omg.org/spec/DD/20100524/DI") +@XmlSeeAlso({ + BPMNDiagram.class +}) +public abstract class Diagram { + + @XmlAttribute(name = "name") + protected String name; + @XmlAttribute(name = "documentation") + protected String documentation; + @XmlAttribute(name = "resolution") + protected Double resolution; + @XmlAttribute(name = "id") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + @XmlID + @XmlSchemaType(name = "ID") + protected String id; + + /** + * Gets the value of the name property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getName() { + return name; + } + + /** + * Sets the value of the name property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setName(String value) { + this.name = value; + } + + /** + * Gets the value of the documentation property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getDocumentation() { + return documentation; + } + + /** + * Sets the value of the documentation property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setDocumentation(String value) { + this.documentation = value; + } + + /** + * Gets the value of the resolution property. + * + * @return + * possible object is + * {@link Double } + * + */ + public Double getResolution() { + return resolution; + } + + /** + * Sets the value of the resolution property. + * + * @param value + * allowed object is + * {@link Double } + * + */ + public void setResolution(Double value) { + this.resolution = value; + } + + /** + * Gets the value of the id property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getId() { + return id; + } + + /** + * Sets the value of the id property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setId(String value) { + this.id = value; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/DiagramElement.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/DiagramElement.java new file mode 100644 index 00000000..cf5e3f6e --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/DiagramElement.java @@ -0,0 +1,205 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.08.21 at 03:38:57 PM EEST +// + + +package org.simantics.sysdyn.modelImport.bpmn; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAnyAttribute; +import javax.xml.bind.annotation.XmlAnyElement; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlID; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlSeeAlso; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import javax.xml.namespace.QName; + + +/** + *

Java class for DiagramElement complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="DiagramElement">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="extension" minOccurs="0">
+ *           <complexType>
+ *             <complexContent>
+ *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *                 <sequence>
+ *                   <any namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
+ *                 </sequence>
+ *               </restriction>
+ *             </complexContent>
+ *           </complexType>
+ *         </element>
+ *       </sequence>
+ *       <attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" />
+ *       <anyAttribute processContents='lax' namespace='##other'/>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "DiagramElement", namespace = "http://www.omg.org/spec/DD/20100524/DI", propOrder = { + "extension" +}) +@XmlSeeAlso({ + Node.class, + Edge.class +}) +public abstract class DiagramElement { + + protected DiagramElement.Extension extension; + @XmlAttribute(name = "id") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + @XmlID + @XmlSchemaType(name = "ID") + protected String id; + @XmlAnyAttribute + private Map otherAttributes = new HashMap(); + + /** + * Gets the value of the extension property. + * + * @return + * possible object is + * {@link DiagramElement.Extension } + * + */ + public DiagramElement.Extension getExtension() { + return extension; + } + + /** + * Sets the value of the extension property. + * + * @param value + * allowed object is + * {@link DiagramElement.Extension } + * + */ + public void setExtension(DiagramElement.Extension value) { + this.extension = value; + } + + /** + * Gets the value of the id property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getId() { + return id; + } + + /** + * Sets the value of the id property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setId(String value) { + this.id = value; + } + + /** + * Gets a map that contains attributes that aren't bound to any typed property on this class. + * + *

+ * the map is keyed by the name of the attribute and + * the value is the string value of the attribute. + * + * the map returned by this method is live, and you can add new attribute + * by updating the map directly. Because of this design, there's no setter. + * + * + * @return + * always non-null + */ + public Map getOtherAttributes() { + return otherAttributes; + } + + + /** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+     * <complexType>
+     *   <complexContent>
+     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+     *       <sequence>
+     *         <any namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
+     *       </sequence>
+     *     </restriction>
+     *   </complexContent>
+     * </complexType>
+     * 
+ * + * + */ + @XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "", propOrder = { + "any" + }) + public static class Extension { + + @XmlAnyElement(lax = true) + protected List any; + + /** + * Gets the value of the any property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the any property. + * + *

+ * For example, to add a new item, do as follows: + *

+         *    getAny().add(newItem);
+         * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Object } + * + * + */ + public List getAny() { + if (any == null) { + any = new ArrayList(); + } + return this.any; + } + + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Edge.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Edge.java new file mode 100644 index 00000000..81fc4603 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Edge.java @@ -0,0 +1,83 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.08.21 at 03:38:57 PM EEST +// + + +package org.simantics.sysdyn.modelImport.bpmn; + +import java.util.ArrayList; +import java.util.List; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlSeeAlso; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for Edge complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="Edge">
+ *   <complexContent>
+ *     <extension base="{http://www.omg.org/spec/DD/20100524/DI}DiagramElement">
+ *       <sequence>
+ *         <element name="waypoint" type="{http://www.omg.org/spec/DD/20100524/DC}Point" maxOccurs="unbounded" minOccurs="2"/>
+ *       </sequence>
+ *       <anyAttribute processContents='lax' namespace='##other'/>
+ *     </extension>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "Edge", namespace = "http://www.omg.org/spec/DD/20100524/DI", propOrder = { + "waypoint" +}) +@XmlSeeAlso({ + LabeledEdge.class +}) +public abstract class Edge + extends DiagramElement +{ + + @XmlElement(required = true) + protected List waypoint; + + /** + * Gets the value of the waypoint property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the waypoint property. + * + *

+ * For example, to add a new item, do as follows: + *

+     *    getWaypoint().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Point } + * + * + */ + public List getWaypoint() { + if (waypoint == null) { + waypoint = new ArrayList(); + } + return this.waypoint; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Font.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Font.java new file mode 100644 index 00000000..1ce4893e --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Font.java @@ -0,0 +1,200 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.08.21 at 03:38:57 PM EEST +// + + +package org.simantics.sysdyn.modelImport.bpmn; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for Font complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="Font">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
+ *       <attribute name="size" type="{http://www.w3.org/2001/XMLSchema}double" />
+ *       <attribute name="isBold" type="{http://www.w3.org/2001/XMLSchema}boolean" />
+ *       <attribute name="isItalic" type="{http://www.w3.org/2001/XMLSchema}boolean" />
+ *       <attribute name="isUnderline" type="{http://www.w3.org/2001/XMLSchema}boolean" />
+ *       <attribute name="isStrikeThrough" type="{http://www.w3.org/2001/XMLSchema}boolean" />
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "Font", namespace = "http://www.omg.org/spec/DD/20100524/DC") +public class Font { + + @XmlAttribute(name = "name") + protected String name; + @XmlAttribute(name = "size") + protected Double size; + @XmlAttribute(name = "isBold") + protected Boolean isBold; + @XmlAttribute(name = "isItalic") + protected Boolean isItalic; + @XmlAttribute(name = "isUnderline") + protected Boolean isUnderline; + @XmlAttribute(name = "isStrikeThrough") + protected Boolean isStrikeThrough; + + /** + * Gets the value of the name property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getName() { + return name; + } + + /** + * Sets the value of the name property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setName(String value) { + this.name = value; + } + + /** + * Gets the value of the size property. + * + * @return + * possible object is + * {@link Double } + * + */ + public Double getSize() { + return size; + } + + /** + * Sets the value of the size property. + * + * @param value + * allowed object is + * {@link Double } + * + */ + public void setSize(Double value) { + this.size = value; + } + + /** + * Gets the value of the isBold property. + * + * @return + * possible object is + * {@link Boolean } + * + */ + public Boolean isIsBold() { + return isBold; + } + + /** + * Sets the value of the isBold property. + * + * @param value + * allowed object is + * {@link Boolean } + * + */ + public void setIsBold(Boolean value) { + this.isBold = value; + } + + /** + * Gets the value of the isItalic property. + * + * @return + * possible object is + * {@link Boolean } + * + */ + public Boolean isIsItalic() { + return isItalic; + } + + /** + * Sets the value of the isItalic property. + * + * @param value + * allowed object is + * {@link Boolean } + * + */ + public void setIsItalic(Boolean value) { + this.isItalic = value; + } + + /** + * Gets the value of the isUnderline property. + * + * @return + * possible object is + * {@link Boolean } + * + */ + public Boolean isIsUnderline() { + return isUnderline; + } + + /** + * Sets the value of the isUnderline property. + * + * @param value + * allowed object is + * {@link Boolean } + * + */ + public void setIsUnderline(Boolean value) { + this.isUnderline = value; + } + + /** + * Gets the value of the isStrikeThrough property. + * + * @return + * possible object is + * {@link Boolean } + * + */ + public Boolean isIsStrikeThrough() { + return isStrikeThrough; + } + + /** + * Sets the value of the isStrikeThrough property. + * + * @param value + * allowed object is + * {@link Boolean } + * + */ + public void setIsStrikeThrough(Boolean value) { + this.isStrikeThrough = value; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Label.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Label.java new file mode 100644 index 00000000..1e9eed72 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Label.java @@ -0,0 +1,76 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.08.21 at 03:38:57 PM EEST +// + + +package org.simantics.sysdyn.modelImport.bpmn; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlSeeAlso; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for Label complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="Label">
+ *   <complexContent>
+ *     <extension base="{http://www.omg.org/spec/DD/20100524/DI}Node">
+ *       <sequence>
+ *         <element ref="{http://www.omg.org/spec/DD/20100524/DC}Bounds" minOccurs="0"/>
+ *       </sequence>
+ *       <anyAttribute processContents='lax' namespace='##other'/>
+ *     </extension>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "Label", namespace = "http://www.omg.org/spec/DD/20100524/DI", propOrder = { + "bounds" +}) +@XmlSeeAlso({ + BPMNLabel.class +}) +public abstract class Label + extends Node +{ + + @XmlElement(name = "Bounds", namespace = "http://www.omg.org/spec/DD/20100524/DC") + protected Bounds bounds; + + /** + * Gets the value of the bounds property. + * + * @return + * possible object is + * {@link Bounds } + * + */ + public Bounds getBounds() { + return bounds; + } + + /** + * Sets the value of the bounds property. + * + * @param value + * allowed object is + * {@link Bounds } + * + */ + public void setBounds(Bounds value) { + this.bounds = value; + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/LabeledEdge.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/LabeledEdge.java new file mode 100644 index 00000000..4b1dfe95 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/LabeledEdge.java @@ -0,0 +1,44 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.08.21 at 03:38:57 PM EEST +// + + +package org.simantics.sysdyn.modelImport.bpmn; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlSeeAlso; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for LabeledEdge complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="LabeledEdge">
+ *   <complexContent>
+ *     <extension base="{http://www.omg.org/spec/DD/20100524/DI}Edge">
+ *       <anyAttribute processContents='lax' namespace='##other'/>
+ *     </extension>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "LabeledEdge", namespace = "http://www.omg.org/spec/DD/20100524/DI") +@XmlSeeAlso({ + BPMNEdge.class +}) +public abstract class LabeledEdge + extends Edge +{ + + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/LabeledShape.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/LabeledShape.java new file mode 100644 index 00000000..9966a1be --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/LabeledShape.java @@ -0,0 +1,44 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.08.21 at 03:38:57 PM EEST +// + + +package org.simantics.sysdyn.modelImport.bpmn; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlSeeAlso; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for LabeledShape complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="LabeledShape">
+ *   <complexContent>
+ *     <extension base="{http://www.omg.org/spec/DD/20100524/DI}Shape">
+ *       <anyAttribute processContents='lax' namespace='##other'/>
+ *     </extension>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "LabeledShape", namespace = "http://www.omg.org/spec/DD/20100524/DI") +@XmlSeeAlso({ + BPMNShape.class +}) +public abstract class LabeledShape + extends Shape +{ + + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/MessageVisibleKind.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/MessageVisibleKind.java new file mode 100644 index 00000000..9886e446 --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/MessageVisibleKind.java @@ -0,0 +1,58 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.08.21 at 03:38:57 PM EEST +// + + +package org.simantics.sysdyn.modelImport.bpmn; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for MessageVisibleKind. + * + *

The following schema fragment specifies the expected content contained within this class. + *

+ *

+ * <simpleType name="MessageVisibleKind">
+ *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
+ *     <enumeration value="initiating"/>
+ *     <enumeration value="non_initiating"/>
+ *   </restriction>
+ * </simpleType>
+ * 
+ * + */ +@XmlType(name = "MessageVisibleKind", namespace = "http://www.omg.org/spec/BPMN/20100524/DI") +@XmlEnum +public enum MessageVisibleKind { + + @XmlEnumValue("initiating") + INITIATING("initiating"), + @XmlEnumValue("non_initiating") + NON_INITIATING("non_initiating"); + private final String value; + + MessageVisibleKind(String v) { + value = v; + } + + public String value() { + return value; + } + + public static MessageVisibleKind fromValue(String v) { + for (MessageVisibleKind c: MessageVisibleKind.values()) { + if (c.value.equals(v)) { + return c; + } + } + throw new IllegalArgumentException(v); + } + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Node.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Node.java new file mode 100644 index 00000000..c310837c --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/Node.java @@ -0,0 +1,46 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.08.21 at 03:38:57 PM EEST +// + + +package org.simantics.sysdyn.modelImport.bpmn; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlSeeAlso; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for Node complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="Node">
+ *   <complexContent>
+ *     <extension base="{http://www.omg.org/spec/DD/20100524/DI}DiagramElement">
+ *       <anyAttribute processContents='lax' namespace='##other'/>
+ *     </extension>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "Node", namespace = "http://www.omg.org/spec/DD/20100524/DI") +@XmlSeeAlso({ + Plane.class, + Shape.class, + Label.class +}) +public abstract class Node + extends DiagramElement +{ + + +} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/ObjectFactory.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/ObjectFactory.java new file mode 100644 index 00000000..e29a713b --- /dev/null +++ b/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/bpmn/ObjectFactory.java @@ -0,0 +1,2741 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.08.21 at 03:38:57 PM EEST +// + + +package org.simantics.sysdyn.modelImport.bpmn; + +import javax.xml.bind.JAXBElement; +import javax.xml.bind.annotation.XmlElementDecl; +import javax.xml.bind.annotation.XmlIDREF; +import javax.xml.bind.annotation.XmlRegistry; +import javax.xml.namespace.QName; + + +/** + * This object contains factory methods for each + * Java content interface and Java element interface + * generated in the org.simantics.sysdyn.modelImport.bpmn package. + *

An ObjectFactory allows you to programatically + * construct new instances of the Java representation + * for XML content. The Java representation of XML + * content can consist of schema derived interfaces + * and classes representing the binding of schema + * type definitions, element declarations and model + * groups. Factory methods for each of these are + * provided in this class. + * + */ +@XmlRegistry +public class ObjectFactory { + + private final static QName _ExtensionElements_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "extensionElements"); + private final static QName _HumanPerformer_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "humanPerformer"); + private final static QName _Collaboration_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "collaboration"); + private final static QName _ParticipantMultiplicity_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "participantMultiplicity"); + private final static QName _ScriptTask_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "scriptTask"); + private final static QName _SequenceFlow_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "sequenceFlow"); + private final static QName _GlobalBusinessRuleTask_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "globalBusinessRuleTask"); + private final static QName _DataAssociation_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "dataAssociation"); + private final static QName _InputSet_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "inputSet"); + private final static QName _DataInputAssociation_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "dataInputAssociation"); + private final static QName _IntermediateThrowEvent_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "intermediateThrowEvent"); + private final static QName _BPMNLabelStyle_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/DI", "BPMNLabelStyle"); + private final static QName _ErrorEventDefinition_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "errorEventDefinition"); + private final static QName _ReceiveTask_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "receiveTask"); + private final static QName _Conversation_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "conversation"); + private final static QName _Style_QNAME = new QName("http://www.omg.org/spec/DD/20100524/DI", "Style"); + private final static QName _ImplicitThrowEvent_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "implicitThrowEvent"); + private final static QName _InclusiveGateway_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "inclusiveGateway"); + private final static QName _IntermediateCatchEvent_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "intermediateCatchEvent"); + private final static QName _OutputSet_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "outputSet"); + private final static QName _LabeledEdge_QNAME = new QName("http://www.omg.org/spec/DD/20100524/DI", "LabeledEdge"); + private final static QName _BPMNLabel_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/DI", "BPMNLabel"); + private final static QName _LoopCharacteristics_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "loopCharacteristics"); + private final static QName _Relationship_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "relationship"); + private final static QName _Process_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "process"); + private final static QName _Extension_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "extension"); + private final static QName _ConditionalEventDefinition_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "conditionalEventDefinition"); + private final static QName _Assignment_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "assignment"); + private final static QName _Artifact_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "artifact"); + private final static QName _FlowNode_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "flowNode"); + private final static QName _EndPoint_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "endPoint"); + private final static QName _MessageFlow_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "messageFlow"); + private final static QName _SubProcess_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "subProcess"); + private final static QName _EndEvent_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "endEvent"); + private final static QName _Plane_QNAME = new QName("http://www.omg.org/spec/DD/20100524/DI", "Plane"); + private final static QName _Documentation_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "documentation"); + private final static QName _BaseElement_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "baseElement"); + private final static QName _TerminateEventDefinition_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "terminateEventDefinition"); + private final static QName _EventBasedGateway_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "eventBasedGateway"); + private final static QName _GlobalScriptTask_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "globalScriptTask"); + private final static QName _TimerEventDefinition_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "timerEventDefinition"); + private final static QName _ComplexGateway_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "complexGateway"); + private final static QName _ManualTask_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "manualTask"); + private final static QName _LabeledShape_QNAME = new QName("http://www.omg.org/spec/DD/20100524/DI", "LabeledShape"); + private final static QName _CallableElement_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "callableElement"); + private final static QName _CancelEventDefinition_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "cancelEventDefinition"); + private final static QName _ServiceTask_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "serviceTask"); + private final static QName _Operation_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "operation"); + private final static QName _SubChoreography_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "subChoreography"); + private final static QName _CorrelationSubscription_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "correlationSubscription"); + private final static QName _ChoreographyActivity_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "choreographyActivity"); + private final static QName _Event_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "event"); + private final static QName _GlobalConversation_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "globalConversation"); + private final static QName _Shape_QNAME = new QName("http://www.omg.org/spec/DD/20100524/DI", "Shape"); + private final static QName _Import_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "import"); + private final static QName _ResourceAssignmentExpression_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "resourceAssignmentExpression"); + private final static QName _EventDefinition_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "eventDefinition"); + private final static QName _Monitoring_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "monitoring"); + private final static QName _ThrowEvent_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "throwEvent"); + private final static QName _ItemDefinition_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "itemDefinition"); + private final static QName _AdHocSubProcess_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "adHocSubProcess"); + private final static QName _GlobalUserTask_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "globalUserTask"); + private final static QName _Category_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "category"); + private final static QName _StartEvent_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "startEvent"); + private final static QName _Participant_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "participant"); + private final static QName _Performer_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "performer"); + private final static QName _FormalExpression_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "formalExpression"); + private final static QName _MessageEventDefinition_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "messageEventDefinition"); + private final static QName _Edge_QNAME = new QName("http://www.omg.org/spec/DD/20100524/DI", "Edge"); + private final static QName _CatchEvent_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "catchEvent"); + private final static QName _ParticipantAssociation_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "participantAssociation"); + private final static QName _DataOutputAssociation_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "dataOutputAssociation"); + private final static QName _DataObjectReference_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "dataObjectReference"); + private final static QName _BoundaryEvent_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "boundaryEvent"); + private final static QName _SendTask_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "sendTask"); + private final static QName _CategoryValue_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "categoryValue"); + private final static QName _Choreography_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "choreography"); + private final static QName _GlobalChoreographyTask_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "globalChoreographyTask"); + private final static QName _CallChoreography_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "callChoreography"); + private final static QName _Bounds_QNAME = new QName("http://www.omg.org/spec/DD/20100524/DC", "Bounds"); + private final static QName _MultiInstanceLoopCharacteristics_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "multiInstanceLoopCharacteristics"); + private final static QName _PotentialOwner_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "potentialOwner"); + private final static QName _CorrelationPropertyBinding_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "correlationPropertyBinding"); + private final static QName _Signal_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "signal"); + private final static QName _UserTask_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "userTask"); + private final static QName _ParallelGateway_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "parallelGateway"); + private final static QName _Lane_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "lane"); + private final static QName _SubConversation_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "subConversation"); + private final static QName _BPMNEdge_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/DI", "BPMNEdge"); + private final static QName _BaseElementWithMixedContent_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "baseElementWithMixedContent"); + private final static QName _DataStore_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "dataStore"); + private final static QName _SignalEventDefinition_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "signalEventDefinition"); + private final static QName _RootElement_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "rootElement"); + private final static QName _DataState_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "dataState"); + private final static QName _CorrelationPropertyRetrievalExpression_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "correlationPropertyRetrievalExpression"); + private final static QName _Node_QNAME = new QName("http://www.omg.org/spec/DD/20100524/DI", "Node"); + private final static QName _IoSpecification_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "ioSpecification"); + private final static QName _ConversationAssociation_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "conversationAssociation"); + private final static QName _LaneSet_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "laneSet"); + private final static QName _Activity_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "activity"); + private final static QName _GlobalTask_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "globalTask"); + private final static QName _Diagram_QNAME = new QName("http://www.omg.org/spec/DD/20100524/DI", "Diagram"); + private final static QName _Error_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "error"); + private final static QName _Task_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "task"); + private final static QName _Resource_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "resource"); + private final static QName _Interface_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "interface"); + private final static QName _CorrelationKey_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "correlationKey"); + private final static QName _Rendering_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "rendering"); + private final static QName _ResourceParameterBinding_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "resourceParameterBinding"); + private final static QName _ExclusiveGateway_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "exclusiveGateway"); + private final static QName _CorrelationProperty_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "correlationProperty"); + private final static QName _Message_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "message"); + private final static QName _DataStoreReference_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "dataStoreReference"); + private final static QName _GlobalManualTask_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "globalManualTask"); + private final static QName _Escalation_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "escalation"); + private final static QName _CallActivity_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "callActivity"); + private final static QName _TextAnnotation_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "textAnnotation"); + private final static QName _Group_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "group"); + private final static QName _Auditing_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "auditing"); + private final static QName _DataOutput_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "dataOutput"); + private final static QName _Point_QNAME = new QName("http://www.omg.org/spec/DD/20100524/DC", "Point"); + private final static QName _Expression_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "expression"); + private final static QName _Transaction_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "transaction"); + private final static QName _ChoreographyTask_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "choreographyTask"); + private final static QName _Gateway_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "gateway"); + private final static QName _ResourceRole_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "resourceRole"); + private final static QName _Label_QNAME = new QName("http://www.omg.org/spec/DD/20100524/DI", "Label"); + private final static QName _PartnerEntity_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "partnerEntity"); + private final static QName _PartnerRole_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "partnerRole"); + private final static QName _BPMNDiagram_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/DI", "BPMNDiagram"); + private final static QName _BusinessRuleTask_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "businessRuleTask"); + private final static QName _IoBinding_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "ioBinding"); + private final static QName _FlowElement_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "flowElement"); + private final static QName _DataObject_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "dataObject"); + private final static QName _LinkEventDefinition_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "linkEventDefinition"); + private final static QName _ResourceParameter_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "resourceParameter"); + private final static QName _Text_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "text"); + private final static QName _Association_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "association"); + private final static QName _CallConversation_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "callConversation"); + private final static QName _EscalationEventDefinition_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "escalationEventDefinition"); + private final static QName _Definitions_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "definitions"); + private final static QName _Property_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "property"); + private final static QName _DiagramElement_QNAME = new QName("http://www.omg.org/spec/DD/20100524/DI", "DiagramElement"); + private final static QName _Script_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "script"); + private final static QName _DataInput_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "dataInput"); + private final static QName _BPMNShape_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/DI", "BPMNShape"); + private final static QName _BPMNPlane_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/DI", "BPMNPlane"); + private final static QName _ConversationNode_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "conversationNode"); + private final static QName _CompensateEventDefinition_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "compensateEventDefinition"); + private final static QName _Font_QNAME = new QName("http://www.omg.org/spec/DD/20100524/DC", "Font"); + private final static QName _ComplexBehaviorDefinition_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "complexBehaviorDefinition"); + private final static QName _ConversationLink_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "conversationLink"); + private final static QName _MessageFlowAssociation_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "messageFlowAssociation"); + private final static QName _StandardLoopCharacteristics_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "standardLoopCharacteristics"); + private final static QName _TInputSetWhileExecutingInputRefs_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "whileExecutingInputRefs"); + private final static QName _TInputSetOutputSetRefs_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "outputSetRefs"); + private final static QName _TInputSetOptionalInputRefs_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "optionalInputRefs"); + private final static QName _TInputSetDataInputRefs_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "dataInputRefs"); + private final static QName _TLaneFlowNodeRef_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "flowNodeRef"); + private final static QName _TDataAssociationSourceRef_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "sourceRef"); + private final static QName _TOutputSetDataOutputRefs_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "dataOutputRefs"); + private final static QName _TOutputSetOptionalOutputRefs_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "optionalOutputRefs"); + private final static QName _TOutputSetWhileExecutingOutputRefs_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "whileExecutingOutputRefs"); + private final static QName _TOutputSetInputSetRefs_QNAME = new QName("http://www.omg.org/spec/BPMN/20100524/MODEL", "inputSetRefs"); + + /** + * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.simantics.sysdyn.modelImport.bpmn + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link TComplexGateway } + * + */ + public TComplexGateway createTComplexGateway() { + return new TComplexGateway(); + } + + /** + * Create an instance of {@link TTimerEventDefinition } + * + */ + public TTimerEventDefinition createTTimerEventDefinition() { + return new TTimerEventDefinition(); + } + + /** + * Create an instance of {@link TManualTask } + * + */ + public TManualTask createTManualTask() { + return new TManualTask(); + } + + /** + * Create an instance of {@link TCallableElement } + * + */ + public TCallableElement createTCallableElement() { + return new TCallableElement(); + } + + /** + * Create an instance of {@link TServiceTask } + * + */ + public TServiceTask createTServiceTask() { + return new TServiceTask(); + } + + /** + * Create an instance of {@link TCancelEventDefinition } + * + */ + public TCancelEventDefinition createTCancelEventDefinition() { + return new TCancelEventDefinition(); + } + + /** + * Create an instance of {@link TSubChoreography } + * + */ + public TSubChoreography createTSubChoreography() { + return new TSubChoreography(); + } + + /** + * Create an instance of {@link TOperation } + * + */ + public TOperation createTOperation() { + return new TOperation(); + } + + /** + * Create an instance of {@link TCorrelationSubscription } + * + */ + public TCorrelationSubscription createTCorrelationSubscription() { + return new TCorrelationSubscription(); + } + + /** + * Create an instance of {@link TGlobalConversation } + * + */ + public TGlobalConversation createTGlobalConversation() { + return new TGlobalConversation(); + } + + /** + * Create an instance of {@link TCollaboration } + * + */ + public TCollaboration createTCollaboration() { + return new TCollaboration(); + } + + /** + * Create an instance of {@link TImport } + * + */ + public TImport createTImport() { + return new TImport(); + } + + /** + * Create an instance of {@link TResourceAssignmentExpression } + * + */ + public TResourceAssignmentExpression createTResourceAssignmentExpression() { + return new TResourceAssignmentExpression(); + } + + /** + * Create an instance of {@link TMonitoring } + * + */ + public TMonitoring createTMonitoring() { + return new TMonitoring(); + } + + /** + * Create an instance of {@link TItemDefinition } + * + */ + public TItemDefinition createTItemDefinition() { + return new TItemDefinition(); + } + + /** + * Create an instance of {@link TAdHocSubProcess } + * + */ + public TAdHocSubProcess createTAdHocSubProcess() { + return new TAdHocSubProcess(); + } + + /** + * Create an instance of {@link TGlobalUserTask } + * + */ + public TGlobalUserTask createTGlobalUserTask() { + return new TGlobalUserTask(); + } + + /** + * Create an instance of {@link TCategory } + * + */ + public TCategory createTCategory() { + return new TCategory(); + } + + /** + * Create an instance of {@link TStartEvent } + * + */ + public TStartEvent createTStartEvent() { + return new TStartEvent(); + } + + /** + * Create an instance of {@link TPerformer } + * + */ + public TPerformer createTPerformer() { + return new TPerformer(); + } + + /** + * Create an instance of {@link TResourceRole } + * + */ + public TResourceRole createTResourceRole() { + return new TResourceRole(); + } + + /** + * Create an instance of {@link TParticipant } + * + */ + public TParticipant createTParticipant() { + return new TParticipant(); + } + + /** + * Create an instance of {@link TFormalExpression } + * + */ + public TFormalExpression createTFormalExpression() { + return new TFormalExpression(); + } + + /** + * Create an instance of {@link TExpression } + * + */ + public TExpression createTExpression() { + return new TExpression(); + } + + /** + * Create an instance of {@link TMessageEventDefinition } + * + */ + public TMessageEventDefinition createTMessageEventDefinition() { + return new TMessageEventDefinition(); + } + + /** + * Create an instance of {@link TExtensionElements } + * + */ + public TExtensionElements createTExtensionElements() { + return new TExtensionElements(); + } + + /** + * Create an instance of {@link THumanPerformer } + * + */ + public THumanPerformer createTHumanPerformer() { + return new THumanPerformer(); + } + + /** + * Create an instance of {@link TParticipantMultiplicity } + * + */ + public TParticipantMultiplicity createTParticipantMultiplicity() { + return new TParticipantMultiplicity(); + } + + /** + * Create an instance of {@link TSequenceFlow } + * + */ + public TSequenceFlow createTSequenceFlow() { + return new TSequenceFlow(); + } + + /** + * Create an instance of {@link TScriptTask } + * + */ + public TScriptTask createTScriptTask() { + return new TScriptTask(); + } + + /** + * Create an instance of {@link TDataAssociation } + * + */ + public TDataAssociation createTDataAssociation() { + return new TDataAssociation(); + } + + /** + * Create an instance of {@link TGlobalBusinessRuleTask } + * + */ + public TGlobalBusinessRuleTask createTGlobalBusinessRuleTask() { + return new TGlobalBusinessRuleTask(); + } + + /** + * Create an instance of {@link TInputSet } + * + */ + public TInputSet createTInputSet() { + return new TInputSet(); + } + + /** + * Create an instance of {@link TIntermediateThrowEvent } + * + */ + public TIntermediateThrowEvent createTIntermediateThrowEvent() { + return new TIntermediateThrowEvent(); + } + + /** + * Create an instance of {@link TDataInputAssociation } + * + */ + public TDataInputAssociation createTDataInputAssociation() { + return new TDataInputAssociation(); + } + + /** + * Create an instance of {@link TErrorEventDefinition } + * + */ + public TErrorEventDefinition createTErrorEventDefinition() { + return new TErrorEventDefinition(); + } + + /** + * Create an instance of {@link TReceiveTask } + * + */ + public TReceiveTask createTReceiveTask() { + return new TReceiveTask(); + } + + /** + * Create an instance of {@link TConversation } + * + */ + public TConversation createTConversation() { + return new TConversation(); + } + + /** + * Create an instance of {@link TImplicitThrowEvent } + * + */ + public TImplicitThrowEvent createTImplicitThrowEvent() { + return new TImplicitThrowEvent(); + } + + /** + * Create an instance of {@link TInclusiveGateway } + * + */ + public TInclusiveGateway createTInclusiveGateway() { + return new TInclusiveGateway(); + } + + /** + * Create an instance of {@link TIntermediateCatchEvent } + * + */ + public TIntermediateCatchEvent createTIntermediateCatchEvent() { + return new TIntermediateCatchEvent(); + } + + /** + * Create an instance of {@link TOutputSet } + * + */ + public TOutputSet createTOutputSet() { + return new TOutputSet(); + } + + /** + * Create an instance of {@link TRelationship } + * + */ + public TRelationship createTRelationship() { + return new TRelationship(); + } + + /** + * Create an instance of {@link TProcess } + * + */ + public TProcess createTProcess() { + return new TProcess(); + } + + /** + * Create an instance of {@link TExtension } + * + */ + public TExtension createTExtension() { + return new TExtension(); + } + + /** + * Create an instance of {@link TAssignment } + * + */ + public TAssignment createTAssignment() { + return new TAssignment(); + } + + /** + * Create an instance of {@link TConditionalEventDefinition } + * + */ + public TConditionalEventDefinition createTConditionalEventDefinition() { + return new TConditionalEventDefinition(); + } + + /** + * Create an instance of {@link TEndPoint } + * + */ + public TEndPoint createTEndPoint() { + return new TEndPoint(); + } + + /** + * Create an instance of {@link TMessageFlow } + * + */ + public TMessageFlow createTMessageFlow() { + return new TMessageFlow(); + } + + /** + * Create an instance of {@link TSubProcess } + * + */ + public TSubProcess createTSubProcess() { + return new TSubProcess(); + } + + /** + * Create an instance of {@link TEndEvent } + * + */ + public TEndEvent createTEndEvent() { + return new TEndEvent(); + } + + /** + * Create an instance of {@link TDocumentation } + * + */ + public TDocumentation createTDocumentation() { + return new TDocumentation(); + } + + /** + * Create an instance of {@link TTerminateEventDefinition } + * + */ + public TTerminateEventDefinition createTTerminateEventDefinition() { + return new TTerminateEventDefinition(); + } + + /** + * Create an instance of {@link TEventBasedGateway } + * + */ + public TEventBasedGateway createTEventBasedGateway() { + return new TEventBasedGateway(); + } + + /** + * Create an instance of {@link TGlobalScriptTask } + * + */ + public TGlobalScriptTask createTGlobalScriptTask() { + return new TGlobalScriptTask(); + } + + /** + * Create an instance of {@link TGateway } + * + */ + public TGateway createTGateway() { + return new TGateway(); + } + + /** + * Create an instance of {@link TTransaction } + * + */ + public TTransaction createTTransaction() { + return new TTransaction(); + } + + /** + * Create an instance of {@link TChoreographyTask } + * + */ + public TChoreographyTask createTChoreographyTask() { + return new TChoreographyTask(); + } + + /** + * Create an instance of {@link TPartnerRole } + * + */ + public TPartnerRole createTPartnerRole() { + return new TPartnerRole(); + } + + /** + * Create an instance of {@link TPartnerEntity } + * + */ + public TPartnerEntity createTPartnerEntity() { + return new TPartnerEntity(); + } + + /** + * Create an instance of {@link TBusinessRuleTask } + * + */ + public TBusinessRuleTask createTBusinessRuleTask() { + return new TBusinessRuleTask(); + } + + /** + * Create an instance of {@link TInputOutputBinding } + * + */ + public TInputOutputBinding createTInputOutputBinding() { + return new TInputOutputBinding(); + } + + /** + * Create an instance of {@link TDataObject } + * + */ + public TDataObject createTDataObject() { + return new TDataObject(); + } + + /** + * Create an instance of {@link TLinkEventDefinition } + * + */ + public TLinkEventDefinition createTLinkEventDefinition() { + return new TLinkEventDefinition(); + } + + /** + * Create an instance of {@link TText } + * + */ + public TText createTText() { + return new TText(); + } + + /** + * Create an instance of {@link TResourceParameter } + * + */ + public TResourceParameter createTResourceParameter() { + return new TResourceParameter(); + } + + /** + * Create an instance of {@link TAssociation } + * + */ + public TAssociation createTAssociation() { + return new TAssociation(); + } + + /** + * Create an instance of {@link TCallConversation } + * + */ + public TCallConversation createTCallConversation() { + return new TCallConversation(); + } + + /** + * Create an instance of {@link TEscalationEventDefinition } + * + */ + public TEscalationEventDefinition createTEscalationEventDefinition() { + return new TEscalationEventDefinition(); + } + + /** + * Create an instance of {@link TProperty } + * + */ + public TProperty createTProperty() { + return new TProperty(); + } + + /** + * Create an instance of {@link TDefinitions } + * + */ + public TDefinitions createTDefinitions() { + return new TDefinitions(); + } + + /** + * Create an instance of {@link TScript } + * + */ + public TScript createTScript() { + return new TScript(); + } + + /** + * Create an instance of {@link TDataInput } + * + */ + public TDataInput createTDataInput() { + return new TDataInput(); + } + + /** + * Create an instance of {@link TComplexBehaviorDefinition } + * + */ + public TComplexBehaviorDefinition createTComplexBehaviorDefinition() { + return new TComplexBehaviorDefinition(); + } + + /** + * Create an instance of {@link TCompensateEventDefinition } + * + */ + public TCompensateEventDefinition createTCompensateEventDefinition() { + return new TCompensateEventDefinition(); + } + + /** + * Create an instance of {@link TMessageFlowAssociation } + * + */ + public TMessageFlowAssociation createTMessageFlowAssociation() { + return new TMessageFlowAssociation(); + } + + /** + * Create an instance of {@link TConversationLink } + * + */ + public TConversationLink createTConversationLink() { + return new TConversationLink(); + } + + /** + * Create an instance of {@link TStandardLoopCharacteristics } + * + */ + public TStandardLoopCharacteristics createTStandardLoopCharacteristics() { + return new TStandardLoopCharacteristics(); + } + + /** + * Create an instance of {@link TParticipantAssociation } + * + */ + public TParticipantAssociation createTParticipantAssociation() { + return new TParticipantAssociation(); + } + + /** + * Create an instance of {@link TDataOutputAssociation } + * + */ + public TDataOutputAssociation createTDataOutputAssociation() { + return new TDataOutputAssociation(); + } + + /** + * Create an instance of {@link TDataObjectReference } + * + */ + public TDataObjectReference createTDataObjectReference() { + return new TDataObjectReference(); + } + + /** + * Create an instance of {@link TBoundaryEvent } + * + */ + public TBoundaryEvent createTBoundaryEvent() { + return new TBoundaryEvent(); + } + + /** + * Create an instance of {@link TCategoryValue } + * + */ + public TCategoryValue createTCategoryValue() { + return new TCategoryValue(); + } + + /** + * Create an instance of {@link TSendTask } + * + */ + public TSendTask createTSendTask() { + return new TSendTask(); + } + + /** + * Create an instance of {@link TChoreography } + * + */ + public TChoreography createTChoreography() { + return new TChoreography(); + } + + /** + * Create an instance of {@link TMultiInstanceLoopCharacteristics } + * + */ + public TMultiInstanceLoopCharacteristics createTMultiInstanceLoopCharacteristics() { + return new TMultiInstanceLoopCharacteristics(); + } + + /** + * Create an instance of {@link TCallChoreography } + * + */ + public TCallChoreography createTCallChoreography() { + return new TCallChoreography(); + } + + /** + * Create an instance of {@link TGlobalChoreographyTask } + * + */ + public TGlobalChoreographyTask createTGlobalChoreographyTask() { + return new TGlobalChoreographyTask(); + } + + /** + * Create an instance of {@link TUserTask } + * + */ + public TUserTask createTUserTask() { + return new TUserTask(); + } + + /** + * Create an instance of {@link TSignal } + * + */ + public TSignal createTSignal() { + return new TSignal(); + } + + /** + * Create an instance of {@link TCorrelationPropertyBinding } + * + */ + public TCorrelationPropertyBinding createTCorrelationPropertyBinding() { + return new TCorrelationPropertyBinding(); + } + + /** + * Create an instance of {@link TPotentialOwner } + * + */ + public TPotentialOwner createTPotentialOwner() { + return new TPotentialOwner(); + } + + /** + * Create an instance of {@link TParallelGateway } + * + */ + public TParallelGateway createTParallelGateway() { + return new TParallelGateway(); + } + + /** + * Create an instance of {@link TSubConversation } + * + */ + public TSubConversation createTSubConversation() { + return new TSubConversation(); + } + + /** + * Create an instance of {@link TLane } + * + */ + public TLane createTLane() { + return new TLane(); + } + + /** + * Create an instance of {@link TSignalEventDefinition } + * + */ + public TSignalEventDefinition createTSignalEventDefinition() { + return new TSignalEventDefinition(); + } + + /** + * Create an instance of {@link TDataStore } + * + */ + public TDataStore createTDataStore() { + return new TDataStore(); + } + + /** + * Create an instance of {@link TCorrelationPropertyRetrievalExpression } + * + */ + public TCorrelationPropertyRetrievalExpression createTCorrelationPropertyRetrievalExpression() { + return new TCorrelationPropertyRetrievalExpression(); + } + + /** + * Create an instance of {@link TDataState } + * + */ + public TDataState createTDataState() { + return new TDataState(); + } + + /** + * Create an instance of {@link TLaneSet } + * + */ + public TLaneSet createTLaneSet() { + return new TLaneSet(); + } + + /** + * Create an instance of {@link TConversationAssociation } + * + */ + public TConversationAssociation createTConversationAssociation() { + return new TConversationAssociation(); + } + + /** + * Create an instance of {@link TInputOutputSpecification } + * + */ + public TInputOutputSpecification createTInputOutputSpecification() { + return new TInputOutputSpecification(); + } + + /** + * Create an instance of {@link TGlobalTask } + * + */ + public TGlobalTask createTGlobalTask() { + return new TGlobalTask(); + } + + /** + * Create an instance of {@link TError } + * + */ + public TError createTError() { + return new TError(); + } + + /** + * Create an instance of {@link TTask } + * + */ + public TTask createTTask() { + return new TTask(); + } + + /** + * Create an instance of {@link TResource } + * + */ + public TResource createTResource() { + return new TResource(); + } + + /** + * Create an instance of {@link TCorrelationKey } + * + */ + public TCorrelationKey createTCorrelationKey() { + return new TCorrelationKey(); + } + + /** + * Create an instance of {@link TInterface } + * + */ + public TInterface createTInterface() { + return new TInterface(); + } + + /** + * Create an instance of {@link TCorrelationProperty } + * + */ + public TCorrelationProperty createTCorrelationProperty() { + return new TCorrelationProperty(); + } + + /** + * Create an instance of {@link TExclusiveGateway } + * + */ + public TExclusiveGateway createTExclusiveGateway() { + return new TExclusiveGateway(); + } + + /** + * Create an instance of {@link TResourceParameterBinding } + * + */ + public TResourceParameterBinding createTResourceParameterBinding() { + return new TResourceParameterBinding(); + } + + /** + * Create an instance of {@link TRendering } + * + */ + public TRendering createTRendering() { + return new TRendering(); + } + + /** + * Create an instance of {@link TMessage } + * + */ + public TMessage createTMessage() { + return new TMessage(); + } + + /** + * Create an instance of {@link TDataStoreReference } + * + */ + public TDataStoreReference createTDataStoreReference() { + return new TDataStoreReference(); + } + + /** + * Create an instance of {@link TGlobalManualTask } + * + */ + public TGlobalManualTask createTGlobalManualTask() { + return new TGlobalManualTask(); + } + + /** + * Create an instance of {@link TCallActivity } + * + */ + public TCallActivity createTCallActivity() { + return new TCallActivity(); + } + + /** + * Create an instance of {@link TEscalation } + * + */ + public TEscalation createTEscalation() { + return new TEscalation(); + } + + /** + * Create an instance of {@link TAuditing } + * + */ + public TAuditing createTAuditing() { + return new TAuditing(); + } + + /** + * Create an instance of {@link TGroup } + * + */ + public TGroup createTGroup() { + return new TGroup(); + } + + /** + * Create an instance of {@link TTextAnnotation } + * + */ + public TTextAnnotation createTTextAnnotation() { + return new TTextAnnotation(); + } + + /** + * Create an instance of {@link TDataOutput } + * + */ + public TDataOutput createTDataOutput() { + return new TDataOutput(); + } + + /** + * Create an instance of {@link BPMNLabel } + * + */ + public BPMNLabel createBPMNLabel() { + return new BPMNLabel(); + } + + /** + * Create an instance of {@link BPMNLabelStyle } + * + */ + public BPMNLabelStyle createBPMNLabelStyle() { + return new BPMNLabelStyle(); + } + + /** + * Create an instance of {@link BPMNPlane } + * + */ + public BPMNPlane createBPMNPlane() { + return new BPMNPlane(); + } + + /** + * Create an instance of {@link BPMNDiagram } + * + */ + public BPMNDiagram createBPMNDiagram() { + return new BPMNDiagram(); + } + + /** + * Create an instance of {@link BPMNEdge } + * + */ + public BPMNEdge createBPMNEdge() { + return new BPMNEdge(); + } + + /** + * Create an instance of {@link BPMNShape } + * + */ + public BPMNShape createBPMNShape() { + return new BPMNShape(); + } + + /** + * Create an instance of {@link Font } + * + */ + public Font createFont() { + return new Font(); + } + + /** + * Create an instance of {@link Bounds } + * + */ + public Bounds createBounds() { + return new Bounds(); + } + + /** + * Create an instance of {@link Point } + * + */ + public Point createPoint() { + return new Point(); + } + + /** + * Create an instance of {@link DiagramElement.Extension } + * + */ + public DiagramElement.Extension createDiagramElementExtension() { + return new DiagramElement.Extension(); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TExtensionElements }{@code >}} + * + */ + @XmlElementDecl(namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", name = "extensionElements") + public JAXBElement createExtensionElements(TExtensionElements value) { + return new JAXBElement(_ExtensionElements_QNAME, TExtensionElements.class, null, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link THumanPerformer }{@code >}} + * + */ + @XmlElementDecl(namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", name = "humanPerformer", substitutionHeadNamespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", substitutionHeadName = "performer") + public JAXBElement createHumanPerformer(THumanPerformer value) { + return new JAXBElement(_HumanPerformer_QNAME, THumanPerformer.class, null, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TCollaboration }{@code >}} + * + */ + @XmlElementDecl(namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", name = "collaboration", substitutionHeadNamespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", substitutionHeadName = "rootElement") + public JAXBElement createCollaboration(TCollaboration value) { + return new JAXBElement(_Collaboration_QNAME, TCollaboration.class, null, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TParticipantMultiplicity }{@code >}} + * + */ + @XmlElementDecl(namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", name = "participantMultiplicity") + public JAXBElement createParticipantMultiplicity(TParticipantMultiplicity value) { + return new JAXBElement(_ParticipantMultiplicity_QNAME, TParticipantMultiplicity.class, null, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TScriptTask }{@code >}} + * + */ + @XmlElementDecl(namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", name = "scriptTask", substitutionHeadNamespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", substitutionHeadName = "flowElement") + public JAXBElement createScriptTask(TScriptTask value) { + return new JAXBElement(_ScriptTask_QNAME, TScriptTask.class, null, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TSequenceFlow }{@code >}} + * + */ + @XmlElementDecl(namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", name = "sequenceFlow", substitutionHeadNamespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", substitutionHeadName = "flowElement") + public JAXBElement createSequenceFlow(TSequenceFlow value) { + return new JAXBElement(_SequenceFlow_QNAME, TSequenceFlow.class, null, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TGlobalBusinessRuleTask }{@code >}} + * + */ + @XmlElementDecl(namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", name = "globalBusinessRuleTask", substitutionHeadNamespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", substitutionHeadName = "rootElement") + public JAXBElement createGlobalBusinessRuleTask(TGlobalBusinessRuleTask value) { + return new JAXBElement(_GlobalBusinessRuleTask_QNAME, TGlobalBusinessRuleTask.class, null, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TDataAssociation }{@code >}} + * + */ + @XmlElementDecl(namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", name = "dataAssociation") + public JAXBElement createDataAssociation(TDataAssociation value) { + return new JAXBElement(_DataAssociation_QNAME, TDataAssociation.class, null, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TInputSet }{@code >}} + * + */ + @XmlElementDecl(namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", name = "inputSet") + public JAXBElement createInputSet(TInputSet value) { + return new JAXBElement(_InputSet_QNAME, TInputSet.class, null, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TDataInputAssociation }{@code >}} + * + */ + @XmlElementDecl(namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", name = "dataInputAssociation") + public JAXBElement createDataInputAssociation(TDataInputAssociation value) { + return new JAXBElement(_DataInputAssociation_QNAME, TDataInputAssociation.class, null, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TIntermediateThrowEvent }{@code >}} + * + */ + @XmlElementDecl(namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", name = "intermediateThrowEvent", substitutionHeadNamespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", substitutionHeadName = "flowElement") + public JAXBElement createIntermediateThrowEvent(TIntermediateThrowEvent value) { + return new JAXBElement(_IntermediateThrowEvent_QNAME, TIntermediateThrowEvent.class, null, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link BPMNLabelStyle }{@code >}} + * + */ + @XmlElementDecl(namespace = "http://www.omg.org/spec/BPMN/20100524/DI", name = "BPMNLabelStyle") + public JAXBElement createBPMNLabelStyle(BPMNLabelStyle value) { + return new JAXBElement(_BPMNLabelStyle_QNAME, BPMNLabelStyle.class, null, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TErrorEventDefinition }{@code >}} + * + */ + @XmlElementDecl(namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", name = "errorEventDefinition", substitutionHeadNamespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", substitutionHeadName = "eventDefinition") + public JAXBElement createErrorEventDefinition(TErrorEventDefinition value) { + return new JAXBElement(_ErrorEventDefinition_QNAME, TErrorEventDefinition.class, null, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TReceiveTask }{@code >}} + * + */ + @XmlElementDecl(namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", name = "receiveTask", substitutionHeadNamespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", substitutionHeadName = "flowElement") + public JAXBElement createReceiveTask(TReceiveTask value) { + return new JAXBElement(_ReceiveTask_QNAME, TReceiveTask.class, null, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TConversation }{@code >}} + * + */ + @XmlElementDecl(namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", name = "conversation", substitutionHeadNamespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", substitutionHeadName = "conversationNode") + public JAXBElement createConversation(TConversation value) { + return new JAXBElement(_Conversation_QNAME, TConversation.class, null, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link Style }{@code >}} + * + */ + @XmlElementDecl(namespace = "http://www.omg.org/spec/DD/20100524/DI", name = "Style") + public JAXBElement