-
Notifications
You must be signed in to change notification settings - Fork 12
/
content-builder.py
141 lines (113 loc) · 5.5 KB
/
content-builder.py
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
#!/usr/bin/env python3
"""
Simulix generates an FMU from a simulink model source code.
Copyright (C) 2018 Scania CV AB and Simulix contributors
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import lxml.etree as ET
import json
import uuid
import argparse
from os import getcwd, path, environ
import collections
import re
SOURCE_REXEG = re.compile(r"(\w+.c)$")
BAD_DLL_SOURCES = [
"fmuTemplate.c"
]
def read_json_file(src):
with open((src),'r') as json_file:
data = json.load(json_file, object_pairs_hook=collections.OrderedDict)
return data
def create_xml_subtree(root, name, dict_tree):
if isinstance(dict_tree, list): #type(dict_tree) == list:
if not dict_tree:
k1_ele = ET.SubElement(root, name)
return root
for i in dict_tree:
k1_ele = ET.SubElement(root, name)
for k2, v2 in i.items():
if isinstance(v2, list): #type(v2) == list:
create_xml_subtree(k1_ele, k2, v2)
else:
if k2 == 'start' and name == 'Real':
try:
v2 = str(float(v2))
except ValueError:
continue
k1_ele.set(k2, v2)
return root
def xmlgen(data):
step_size = str(float(data["StepSize"]))
name = data["Model"]
fmiMD = {"fmiVersion":"2.0", "modelName":name, "guid":data["GUID"], "numberOfEventIndicators":"0"}
co_simulation_dict = {"providesDirectionalDerivative":"false", "modelIdentifier":name, "canHandleVariableCommunicationStepSize":"false"}
category_dictlist = [{"name":"logAll", "description":"-"}, {"name":"logError", "description":"-"}, {"name":"logFmiCall", "description":"-"}, {"name":"logEvent", "description":"-"}]
step_size_dict = {"stepSize":step_size}
root = ET.Element("fmiModelDescription", fmiMD)
source_files_subelement = ET.SubElement(ET.SubElement(root,"CoSimulation",co_simulation_dict), "SourceFiles")
# $ENV{SIMX_SOURCE_LIST} is set in unpack.py
source_list = environ['SIMX_SOURCES_LIST'].split(';')
source_list.append("Simulix_dllmain.c")
for source in source_list:
match = SOURCE_REXEG.search(source)
if match and match.group(1) not in BAD_DLL_SOURCES:
ET.SubElement(source_files_subelement, "File").set("name", match.group(1))
LogCategories = ET.SubElement(root,"LogCategories")
for i in range(len(category_dictlist)):
ET.SubElement(LogCategories,"Category",category_dictlist[i])
ET.SubElement(root, "DefaultExperiment", step_size_dict)
create_xml_subtree(root, "ModelVariables", data['ModelVariables'])
create_xml_subtree(root, "ModelStructure", data['ModelStructure'])
ET.ElementTree(root).write(path.join('modelDescription.xml'),
encoding='utf-8', xml_declaration=True, method='xml', pretty_print=True)
def dllgen(dst, data):
src = path.join(path.dirname(path.realpath(__file__)), 'templates/')
template_replace = {
}
template_replace['numReal'] = int(data['numReal'])
template_replace['numInt'] = int(data['numInt'])
template_replace['numBoolean'] = int(data['numBoolean'])
template_replace['stepSize'] = data['StepSize']
template_replace['modelName'] = data['Model']
template_replace['GUID'] = data['GUID']
real_string = ""
int_string = ""
boolean_string = ""
for item in data['ModelVariables'][0]['ScalarVariable']:
if 'Real' in item.keys():
real_string+= "{{F64, {0}, {1}}},\n ".format(item['index'], item['offset'])
elif 'Integer' in item.keys():
int_string+= "{{S32, {0}, {1}}},\n ".format(item['index'], item['offset'])
else:
boolean_string+= "{{B, {0}, {1}}},\n ".format(item['index'], item['offset'])
template_replace['realString'] = real_string
template_replace['intString'] = int_string
template_replace['booleanString'] = boolean_string
with open(path.join(dst, 'Simulix_dllmain.c'), 'w') as dllmain:
with open(path.join(src, "Simulix_cg_license.txt"), 'r') as license_text:
dllmain.write(license_text.read())
with open(path.join(src, "Simulix_dllmain_template.c"), 'r') as dllmainTemplate:
dllmain.write(dllmainTemplate.read().format(**template_replace))
def main(dst):
data = read_json_file("ModelOutputs.json")
data["GUID"] = str(uuid.uuid4())
dllgen(dst, data)
# remove index and offset keys that must not be known to xmlgen
index_list = list(map(lambda d: d.pop('index'), data['ModelVariables'][0]['ScalarVariable']))
offset_list = list(map(lambda d: d.pop('offset'), data['ModelVariables'][0]['ScalarVariable']))
xmlgen(data)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Generate a C file for a FMU",prog="dllgen",usage="%(prog)s [options]")
parser.add_argument('-o', help='Path to Simulix_dllmain.c output', default=getcwd())
args = parser.parse_args()
main(args.o)