aboutsummaryrefslogtreecommitdiffstats
path: root/Tests/MODELS2020-CaseStudies/case.study.pledge.run/src/run/GenerateFromConfig.xtend
blob: 859a445594e0fdfc734162bb2bb8491962a1cf61 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
package run

import hu.bme.mit.inf.dslreasoner.application.applicationConfiguration.ConfigSpecification
import hu.bme.mit.inf.dslreasoner.application.applicationConfiguration.ConfigurationScript
import hu.bme.mit.inf.dslreasoner.application.applicationConfiguration.FileSpecification
import hu.bme.mit.inf.dslreasoner.application.applicationConfiguration.GenerationTask
import hu.bme.mit.inf.dslreasoner.application.applicationConfiguration.IntervallNumber
import hu.bme.mit.inf.dslreasoner.application.applicationConfiguration.ObjectTypeScope
import hu.bme.mit.inf.dslreasoner.application.applicationConfiguration.RuntimeEntry
import hu.bme.mit.inf.dslreasoner.application.applicationConfiguration.ScopeSpecification
import hu.bme.mit.inf.dslreasoner.application.execution.ScriptExecutor
import hu.bme.mit.inf.dslreasoner.application.execution.StandaloneScriptExecutor
import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic
import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace
import hu.bme.mit.inf.dslreasoner.ecore2logic.EcoreMetamodelDescriptor
import hu.bme.mit.inf.dslreasoner.logic.model.builder.TracedOutput
import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type
import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem
import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicResult
import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult
import hu.bme.mit.inf.dslreasoner.logic2ecore.Logic2Ecore
import hu.bme.mit.inf.dslreasoner.viatra2logic.ViatraQuerySetDescriptor
import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretation2Gml
import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasoner
import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration
import hu.bme.mit.inf.dslreasoner.visualisation.pi2graphviz.GraphvizVisualiser
import hu.bme.mit.inf.dslreasoner.workspace.FileSystemWorkspace
import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace
import java.io.PrintWriter
import java.math.BigDecimal
import java.text.SimpleDateFormat
import java.util.ArrayList
import java.util.Date
import java.util.HashMap
import java.util.List
import java.util.Map
import org.eclipse.core.runtime.NullProgressMonitor
import org.eclipse.emf.ecore.EAttribute
import org.eclipse.emf.ecore.EClass
import org.eclipse.emf.ecore.EEnum
import org.eclipse.emf.ecore.EEnumLiteral
import org.eclipse.emf.ecore.EObject
import org.eclipse.emf.ecore.EPackage
import org.eclipse.emf.ecore.EReference
import org.eclipse.emf.ecore.resource.Resource
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl
import org.eclipse.viatra.query.runtime.api.IQueryGroup

class GenerateFromConfig {
	static val SIZE_LB = 1
	static val SIZE_UB = 1
	static val SIZE_MUL = 1
	static val SIZE_INC = 5

	static var REPS = 1
	static val RUNTIME = 2100

	static val DOMAIN = "Taxation" // "FamilyTree", "Taxation"
	static val QUERIES = true
	static val INITIAL = true
	static val INDIV_WRT = false
	static val GLOBAL_WRT = false
	static val q2t = if(QUERIES) "Y" else "N"

	def static void main(String[] args) {
		Resource.Factory.Registry.INSTANCE.extensionToFactoryMap.put("xmi", new XMIResourceFactoryImpl)

		// Workspace setup
		val Date date = new Date(System.currentTimeMillis)
		val SimpleDateFormat format = new SimpleDateFormat("dd-HHmm");
		val formattedDate = DOMAIN + "-" + format.format(date)

		val workspace = new FileSystemWorkspace('''output/''' + formattedDate + '''/''', "")
		workspace.initAndClear

		println("Input and output workspaces are created")

		val executor = new ScriptExecutor
		val path = "config//generic" + DOMAIN + ".vsconfig"
		var ConfigurationScript config = StandaloneScriptExecutor.loadScript(path)

		println("Config File loaded")

		// /////////////////////////
		// BEGIN RUN
		var PrintWriter global_writer = null
		val header = "domain, queries?,size,model?,timeout,measuredTime,TransformatonTime,SolverTime\n"
		if (GLOBAL_WRT) {
			global_writer = new PrintWriter(
				workspace.workspaceURI + "//_" + DOMAIN + SIZE_LB + "to" + SIZE_UB + "x" + REPS + "q" + q2t + "-" +
					formattedDate + ".csv")
			global_writer.append(header)
		}

		var NEXT_INC = SIZE_INC
		for (var size = SIZE_LB; size <= SIZE_UB; size += NEXT_INC) {
			NEXT_INC *= SIZE_MUL

			var PrintWriter indiv_writer = null
			if (INDIV_WRT) {
				indiv_writer = new PrintWriter( // TODO
				workspace.workspaceURI + "//__" + DOMAIN + "Sz" + size + "x" + REPS + "q" + q2t + "-" + formattedDate +
					".csv")
				indiv_writer.append(header)
			}

			println()
			println("DOMAIN: " + DOMAIN + ", SIZE=" + size)

			for (var i = 0; i < REPS; i++) {

				print("<<Run number " + i + ">> : ")


				// /////////////////////////////////////////////////////
				// Define Config File	
				val knownIntegers = new ArrayList<Integer>
				knownIntegers.addAll(0, 10, 20, 30, 40, 50)

				val knownReals = new ArrayList<BigDecimal>
				knownReals.addAll(new BigDecimal("0.0"))

				val knownStrings = new ArrayList<String>
				knownStrings.addAll("r0", "r1", "r2", "r3", "r4", "r5", "r6")

				val outputPath = "output/" + formattedDate + "/size" + size + "/run" + i + "/models/"
				val debugPath = "output/" + formattedDate + "/size" + size + "/run" + i + "/debug/"
				val logPath = debugPath + "log.txt"
				val statsPath = debugPath + "statistics.csv"

				// Adjust configuration
				val genTask = config.commands.get(0) as GenerationTask
				if(!QUERIES) genTask.patterns = null
				if(!INITIAL) genTask.partialModel = null

				val scopeSpec = genTask.scope as ScopeSpecification
				val objScope = scopeSpec.scopes.get(0) as ObjectTypeScope
				val interval = objScope.number as IntervallNumber
				interval.min = size
				interval.maxUnlimited = true

				val configScope = genTask.config as ConfigSpecification
				val runtimeEntry = configScope.entries.get(0) as RuntimeEntry
				runtimeEntry.millisecLimit = RUNTIME

				// TODO add known ints, reals, string...
				val debug = genTask.debugFolder as FileSpecification
				debug.path = debugPath
				val output = genTask.tagetFolder as FileSpecification
				output.path = outputPath
				val log = genTask.targetLogFile as FileSpecification
				log.path = logPath
				val stats = genTask.targetStatisticsFile as FileSpecification
				stats.path = statsPath

//				workspace.writeModel(config, '''x.xmi''')
				val startTime = System.currentTimeMillis
				executor.executeScript(config, new NullProgressMonitor)
				val measuredTime = System.currentTimeMillis - startTime

				println("<<END ->" + measuredTime / 1000.0 + "s >>\n")

//				val toAddtoCSV = DOMAIN + "," + QUERIES + "," + size + "," +
//					(solution.class == ModelResultImpl).toString + "," + RUNTIME + "," + measuredTime / 1000.0 + "," +
//					solution.statistics.transformationTime / 1000.0 + "," + solution.statistics.solverTime / 1000.0 +
//					"\n"
//
//				if(GLOBAL_WRT) global_writer.append(toAddtoCSV)
//				if(INDIV_WRT) indiv_writer.append(toAddtoCSV)
//				solution.writeStats(totalTime, solverConfig)
				// Run Garbage Collector
				val Runtime r = Runtime.getRuntime();
				r.gc();
				r.gc();
				r.gc();
				Thread.sleep(3000)
			}
			if(INDIV_WRT) indiv_writer.close
		}
		if(GLOBAL_WRT) global_writer.close
	}

	def static Map<Type, Integer> getTypeMap(Map<Class, Integer> classMap, EcoreMetamodelDescriptor metamodel,
		Ecore2Logic e2l, Ecore2Logic_Trace trace) {
		val typeMap = new HashMap<Type, Integer>
		val listMap = metamodel.classes.toMap[s|s.name]

		for (Class  elem : classMap.keySet) {
			typeMap.put(e2l.TypeofEClass(
				trace,
				listMap.get(elem.simpleName)
			), classMap.get(elem))
		}
		return typeMap
	}

	def static loadMetamodel(EPackage pckg) {
		val List<EClass> classes = pckg.getEClassifiers.filter(EClass).toList
		val List<EEnum> enums = pckg.getEClassifiers.filter(EEnum).toList
		val List<EEnumLiteral> literals = enums.map[getELiterals].flatten.toList
		val List<EReference> references = classes.map[getEReferences].flatten.toList
		val List<EAttribute> attributes = classes.map[getEAttributes].flatten.toList
		return new EcoreMetamodelDescriptor(classes, #{}, false, enums, literals, references, attributes)
	}

	def static loadPartialModel(ReasonerWorkspace inputs, String path) {
		Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("*", new XMIResourceFactoryImpl())
		inputs.readModel(EObject, path).eResource.contents
//		inputs.readModel(EObject,"FamInstance.xmi").eResource.allContents.toList
	}

	def static loadQueries(EcoreMetamodelDescriptor metamodel, IQueryGroup i) {
		val patterns = i.specifications.toList
		val wfPatterns = patterns.filter[it.allAnnotations.exists[it.name == "Constraint"]].toSet
		val derivedFeatures = emptyMap
		// NO DERIVED FEATURES
//		val derivedFeatures = new LinkedHashMap
//		derivedFeatures.put(i.type,metamodel.attributes.filter[it.name == "type"].head)
//		derivedFeatures.put(i.model,metamodel.references.filter[it.name == "model"].head)
		val res = new ViatraQuerySetDescriptor(
			patterns,
			wfPatterns,
			derivedFeatures
		)
		return res
	}

	def static writeInterpretation(LogicResult solution, Logic2Ecore logic2Ecore, ReasonerWorkspace workspace,
		String id, ViatraReasoner reasoner, TracedOutput<LogicProblem, Ecore2Logic_Trace> mgProb) {
		val interpretations = reasoner.getInterpretations(solution as ModelResult)
		for (interpIndex : 0 ..< interpretations.size) {
//				val extension b = new LogicStructureBuilder
//				val extension a = new LogicProblemBuilder
			val interpretation = interpretations.get(interpIndex)
			val model = logic2Ecore.transformInterpretation(interpretation, mgProb.trace)
//			println(model)
			workspace.writeModel(model, '''sol-«id»_«interpIndex».xmi''')
		}
	}

	def static writeRepresentation(LogicResult solution, ReasonerWorkspace workspace, String id) {
		val representations = solution.representation
		for (representationIndex : 0 ..< representations.size) {
			val representation = representations.get(representationIndex)
			if (representation instanceof PartialInterpretation) {
				val gml = (new PartialInterpretation2Gml).transform(representation)
				workspace.writeText('''sol-«id»_«representationIndex».gml''', gml)

				val png = (new GraphvizVisualiser).visualiseConcretization(representation)
//				println(png)
				png.writeToFile(workspace, '''sol-«id»_«representationIndex».png''')

//				workspace.writeModel(representation, '''solution«representationIndex».partialintrpretation''')
			} else {
				workspace.writeText('''sol-«representationIndex».txt''', representation.toString)
			}
		}
	}

	def static writeStats(LogicResult solution, long time, ViatraReasonerConfiguration config) {
		val stats = solution.statistics
		println("  Statistics:")
//		for (e : stats.entries.filter[name.substring(0, 9) == "_Solution"]) {
//			println("    " + e.name + ": " + (e as IntStatisticEntry).value + " ms")
//		}
		println(
			"    #new nodes    : [" + config.typeScopes.minNewElements + ".." +
				(if(config.typeScopes.maxNewElements == 2147483647) "*" else config.typeScopes.maxNewElements) + "]")
		println("    \"solve\" time: " + time as double / 1000 + " s")

//		println("<<End Statistics>>")
	}
}