Commit 8fd5aa74 authored by VIGNET Pierre's avatar VIGNET Pierre
Browse files

[lib] Chart xml parser: black

parent a7415992
......@@ -59,8 +59,8 @@ class XmlVisitor:
def __init__(self, model):
self.model = model
self.fact_list = []
self.xml = "" # string: xml representation of model
self.symb = set() # symbol set used to check double naming of nodes
self.xml = "" # string: xml representation of model
self.symb = set() # symbol set used to check double naming of nodes
self.visit_chart_model()
def visit_chart_model(self):
......@@ -128,7 +128,6 @@ class XmlVisitor:
attr = [inn.name, inn.xloc, inn.yloc]
return [tag, attrname, attr]
def visit_cmacro_node(self, mnode):
"""
Generate xml representation of a macro node
......@@ -147,22 +146,22 @@ class XmlVisitor:
attr = properties[2]
attributes = macro.attrib
for i in range(0, len(attrname)):
attributes[attrname[i]] = str(attr[i])
attributes[attrname[i]] = str(attr[i])
# nodes
for snode in mnode.sub_nodes:
properties = snode.accept(self)
if properties[0] == 'CMacroNode':
if properties[0] == "CMacroNode":
self.current_element = macro
if properties[0] != 'CMacroNode':
if properties[0] != "CMacroNode":
subel = etree.SubElement(self.current_element, properties[0])
if len(properties) > 1:
attrname = properties[1]
attr = properties[2]
attributes = subel.attrib
for i in range(0, len(attrname)):
attributes[attrname[i]] = str(attr[i])
attributes[attrname[i]] = str(attr[i])
# transitions
for gtr in mnode.transitions:
......@@ -174,7 +173,7 @@ class XmlVisitor:
attr = properties[2]
attributes = sub_tr.attrib
for i in range(0, len(attrname)):
attributes[attrname[i]] = str(attr[i])
attributes[attrname[i]] = str(attr[i])
self.current_element = save_macro
return [tag, attrname, attr]
......@@ -187,11 +186,11 @@ class XmlVisitor:
"""
header = objectify.ElementMaker(
annotate=False,
#namespace="http://cadbiom.genouest.org/",
#nsmap={None: "http://cadbiom.genouest.org/"}
# namespace="http://cadbiom.genouest.org/",
# nsmap={None: "http://cadbiom.genouest.org/"}
namespace=self.model.xml_namespace,
# the default namespace (no prefix)
nsmap={None: self.model.xml_namespace}
nsmap={None: self.model.xml_namespace},
)
xmodel = header.model(name=self.model.name)
self.current_element = xmodel
......@@ -200,7 +199,7 @@ class XmlVisitor:
"""Create XML element and add it to root object"""
# get node or transition properties
properties = entity.accept(self)
if properties[0] != 'CMacroNode':
if properties[0] != "CMacroNode":
element = etree.Element(properties[0])
if len(properties) > 1:
attrname = properties[1]
......@@ -231,18 +230,23 @@ class XmlVisitor:
xmodel.append(const)
self.xml = etree.tostring(xmodel, pretty_print=True)
# print (etree.tostring(xmodel,pretty_print=True))
# print (etree.tostring(xmodel,pretty_print=True))
def visit_ctransition(self, trans):
"""
Generate xml representation of a transition
"""
tag = "transition"
attrname = ["ori", "ext", "event",
"condition", "action", "fact_ids"]
attr = [trans.ori.name, trans.ext.name, trans.event,
trans.condition, trans.action, trans.fact_ids]
attrname = ["ori", "ext", "event", "condition", "action", "fact_ids"]
attr = [
trans.ori.name,
trans.ext.name,
trans.event,
trans.condition,
trans.action,
trans.fact_ids,
]
fact_ids = trans.fact_ids
for fact in fact_ids:
......@@ -265,7 +269,7 @@ class XmlVisitor:
for i in self.fact_list:
if i in model_fact:
continue
else :
else:
model_fact.append(i)
return model_fact
......@@ -280,7 +284,7 @@ class MakeHandler(ContentHandler):
https://docs.python.org/2/library/xml.sax.handler.html
"""
def __init__(self, model = None):
def __init__(self, model=None):
self.pile_node = []
self.top_pile = None
self.pile_dict = []
......@@ -301,14 +305,13 @@ class MakeHandler(ContentHandler):
.. note:: Must be call after the init of self.top_pile with the xml root
object.
"""
self.add_node_functions = \
{
'CStartNode': self.top_pile.add_start_node,
'CTrapNode': self.top_pile.add_trap_node,
'CSimpleNode': self.top_pile.add_simple_node,
'CPermNode': self.top_pile.add_perm_node,
'CInputNode': self.top_pile.add_input_node,
}
self.add_node_functions = {
"CStartNode": self.top_pile.add_start_node,
"CTrapNode": self.top_pile.add_trap_node,
"CSimpleNode": self.top_pile.add_simple_node,
"CPermNode": self.top_pile.add_perm_node,
"CInputNode": self.top_pile.add_input_node,
}
def startElement(self, name, att):
"""Signal the start of an element
......@@ -324,29 +327,29 @@ class MakeHandler(ContentHandler):
:type arg1: <str>
:type arg2: <xml.sax.xmlreader.AttributesImpl>
"""
#print(att.getNames())
# print(att.getNames())
if name in self.nodes_types:
# TODO: Uniformization of API in CMacroNode() class;
# the attribute 'name' should be at the same last position...
element_name = att.get('name', '').encode('ascii')
element_name = att.get("name", "").encode("ascii")
self.current_element = self.add_node_functions[name](
name=element_name,
xcoord=float(att.get('xloc', '0')),
ycoord=float(att.get('yloc', '0')),
xcoord=float(att.get("xloc", "0")),
ycoord=float(att.get("yloc", "0")),
)
self.node_dict[element_name] = self.current_element
elif name == 'transition':
#name = att.get('name', '').encode('ascii')
ori = att.get('ori', '')
ext = att.get('ext', '')
event = att.get('event', '')
condition = att.get('condition', '')
action = att.get('action', '')
fact_ids_text = att.get('fact_ids','')[1:-1]
elif name == "transition":
# name = att.get('name', '').encode('ascii')
ori = att.get("ori", "")
ext = att.get("ext", "")
event = att.get("event", "")
condition = att.get("condition", "")
action = att.get("action", "")
fact_ids_text = att.get("fact_ids", "")[1:-1]
if len(fact_ids_text) > 0:
fact_ids = [int(id) for id in fact_ids_text.split(',')]
fact_ids = [int(id) for id in fact_ids_text.split(",")]
else:
fact_ids = []
......@@ -357,7 +360,7 @@ class MakeHandler(ContentHandler):
node_ori = self.node_dict[ori]
node_ext = self.node_dict[ext]
except Exception as exc:
print('Bad xml file - missing nodes', ori, ' -> ', ext)
print("Bad xml file - missing nodes", ori, " -> ", ext)
print(self.node_dict)
print(exc)
......@@ -373,15 +376,14 @@ class MakeHandler(ContentHandler):
self.current_element.set_action(action)
self.current_element.fact_ids = fact_ids
elif name == 'CMacroNode':
name = att.get('name', '').encode('ascii')
xloc = float(att.get('xloc', '0'))
yloc = float(att.get('yloc', '0'))
wloc = float(att.get('wloc', '5'))
hloc = float(att.get('hloc', '5'))
elif name == "CMacroNode":
name = att.get("name", "").encode("ascii")
xloc = float(att.get("xloc", "0"))
yloc = float(att.get("yloc", "0"))
wloc = float(att.get("wloc", "5"))
hloc = float(att.get("hloc", "5"))
node = self.top_pile.add_macro_subnode(name, xloc, yloc,
wloc, hloc)
node = self.top_pile.add_macro_subnode(name, xloc, yloc, wloc, hloc)
self.node_dict[name] = node
self.pile_node.append(node)
......@@ -391,16 +393,16 @@ class MakeHandler(ContentHandler):
self.top_pile = node
self.node_dict = new_node_dict
elif name == 'constraints':
elif name == "constraints":
self.in_constraints = True
self.constraints = ""
elif name == 'model':
elif name == "model":
if not self.model:
# Init CharModel: get name and namespace (default v1)
self.model = ChartModel(
att.get('name', ''),
att.get('xmlns', 'http://cadbiom.genouest.org/')
att.get("name", ""),
att.get("xmlns", "http://cadbiom.genouest.org/"),
)
# Root is a virtual macronode on top of the hierarchy.
# A model can be a list of hierarchy grouped under this node.
......@@ -431,7 +433,7 @@ class MakeHandler(ContentHandler):
# node or transition is currently opened in startElement()
self.current_element.note += chr
def endElement (self, name):
def endElement(self, name):
"""Called when an elements ends
.. note:: We handle only elements that need post processing like
......@@ -439,20 +441,20 @@ class MakeHandler(ContentHandler):
to load notes (inner text of xml object).
"""
if name == 'transition' or name in self.nodes_types:
if name == "transition" or name in self.nodes_types:
# Close the current node or transition opened in startElement()
self.current_element = None
elif name == 'CMacroNode':
#self.top_pile = self.pile_node.pop()
elif name == "CMacroNode":
# self.top_pile = self.pile_node.pop()
self.pile_node.remove(self.top_pile)
self.top_pile = self.pile_node[-1]
#self.node_dict = self.pile_dict.pop()
# self.node_dict = self.pile_dict.pop()
self.pile_dict.remove(self.node_dict)
self.node_dict = self.pile_dict[-1]
elif name == 'constraints':
elif name == "constraints":
self.in_constraints = False
self.model.constraints = self.constraints + '\n'
#elif name == 'model':
self.model.constraints = self.constraints + "\n"
# elif name == 'model':
# print(len([e for e in self.top_pile.transitions]))
# print(len(self.top_pile.new_transitions))
......@@ -475,10 +477,9 @@ class MakeModelFromXmlFile:
try:
self.parser.parse(xml_file)
except Exception:
print('ERROR while xml parsing')
print("ERROR while xml parsing")
raise
def get_model(self):
"""Return the model generated from the XML file
......@@ -486,6 +487,7 @@ class MakeModelFromXmlFile:
"""
return self.handler.model
class MakeModelFromXmlString:
"""Parse a xml description as string"""
......@@ -498,33 +500,12 @@ class MakeModelFromXmlString:
try:
parseString(xml_string, self.handler)
except Exception as exc:
print('ERROR while xml parsing')
print("ERROR while xml parsing")
print(exc)
def get_model(self):
"""Return the model generated from the XML string
:rtype: <ChartModel>
"""
return self.handler.model
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment