Parcourir la source

Added import possibility

rparedis il y a 5 ans
Parent
commit
f9e8a2aa1f

+ 2 - 0
.gitignore

@@ -0,0 +1,2 @@
+
+__pycache__/

+ 2 - 1
__main__.py

@@ -89,7 +89,8 @@ fields = {
 	"command": " ".join(sys.argv),
 	"nodes": nodes,
 	"ignore": setup["generator"]["ignore"],
-	"time": args.time
+	"time": args.time,
+	"imports": parser.get_imports()
 }
 for blueprint in setup["generator"]["templates"]:
 	if blueprint.get("auto", True) or args.all:

BIN
__pycache__/formatter.cpython-38.pyc


BIN
__pycache__/parser.cpython-38.pyc


+ 0 - 5
experiment.py

@@ -1,5 +0,0 @@
-#!/usr/bin/python3
-# This file was automatically generated from drawio2cbd with the command:
-#   __main__.py -avfs -F CBD -E delta=0.1 Fibonacci.xml -e FibonacciGen
-
-# TODO

Fichier diff supprimé car celui-ci est trop grand
+ 1 - 0
formalisms/CBD/CBDLibrary.xml


Fibonacci.xml → formalisms/CBD/Fibonacci.xml


Fichier diff supprimé car celui-ci est trop grand
+ 1 - 0
formalisms/CBD/Formalism.drawio


+ 3 - 0
formalisms/CBD/experiment.py.jinja

@@ -3,6 +3,9 @@
 #   {{command}}
 
 from model import {{entry}}
+{% for im in imports %}
+{{im}}
+{% endfor %}
 
 cbd = {{entry}}("{{entry}}")
 

+ 4 - 0
formalisms/CBD/model.py.jinja

@@ -3,6 +3,10 @@
 #   {{command}}
 
 from CBD.src.CBD import *
+from CBD.src.lib.std import *
+{% for im in imports %}
+{{ im }}
+{% endfor %}
 
 {% if delta is defined and delta is not none %}
 DELTA_T = {{delta}}

+ 0 - 45
formatter.py

@@ -1,45 +0,0 @@
-from string import Formatter
-
-
-class TemplateFormatter(Formatter):
-	def __init__(self, namespace=None):
-		super().__init__()
-		self.namespace = {} if namespace is None else namespace
-
-	def format(self, format_string, *args, **kwargs):
-		return super().format(format_string, *args, **kwargs, **self.namespace)
-
-	def format_field(self, value, format_spec):
-		if format_spec.startswith("if:"):
-			_, cond, res = format_spec.split(':')
-			if cond == "" and value:
-				return self.format(res, value=value)
-			elif eval(cond.format(self, value=value), {}, {}):
-				return self.format(res, value=value)
-			return ""
-		elif format_spec.startswith("repeat:"):
-			fsp = format_spec[7:]
-			idx = fsp[:fsp.find(':')]
-			fres = fsp[fsp.find(':')+1:]
-			res = ""
-			for item in value:
-				res += self.format(fres, **{idx: item})
-			return res
-		elif format_spec.startswith("call"):
-			return str(value())
-		else:
-			return super().format_field(value, format_spec)
-
-
-if __name__ == '__main__':
-	class Test:
-		def a(self):
-			return 5
-
-	fmt = TemplateFormatter({"test": "howdy", "chapters": [Test()], "manager": 1})
-	print(fmt.format("""Table of Contents: 
-		{chapters:repeat:item:
-		Chapter {{item.a:call}} {test};
-		}"""))
-	print(fmt.format('Action: Back / Logout {manager:if::/ Delete {test}}'))
-	print(fmt.format('Action: Back / Logout {manager:if:{{value}} == 1:/ Delete {manager}}'))

+ 0 - 61
model.py

@@ -1,61 +0,0 @@
-#!/usr/bin/python3
-# This file was automatically generated from drawio2cbd with the command:
-#   __main__.py -vs -F CBD -E delta=0.1 Fibonacci.xml -e FibonacciGen
-
-from CBD import *
-
-DELTA_T = 0.1
-
-class InitialConditions(CBD):
-    """
-    Sets the initial conditions of the Fibonacci Generator.
-    """
-    def __init__(self, block_name):
-        super().__init__(block_name, inputs=[], outputs=['OUT2', 'OUT3', 'OUT1'])
-
-        # Create the Blocks
-        self.addBlock(ConstantBlock("one", value=(1.0)))
-        self.addBlock(ConstantBlock("two", value=(2.0)))
-        self.addBlock(AdderBlock("sum1"))
-        self.addBlock(AdderBlock("sum2"))
-        self.addBlock(NegatorBlock("neg1"))
-        self.addBlock(NegatorBlock("neg2"))
-        self.addBlock(RootBlock("root"))
-
-        # Create the Connections
-        self.addConnection("one", "neg2", output_port_name='OUT1', input_port_name='IN1')
-        self.addConnection("one", "root", output_port_name='OUT1', input_port_name='IN1')
-        self.addConnection("two", "sum1", output_port_name='OUT1', input_port_name='IN1')
-        self.addConnection("two", "root", output_port_name='OUT1', input_port_name='IN2')
-        self.addConnection("sum1", "sum2", output_port_name='OUT1', input_port_name='IN1')
-        self.addConnection("sum1", "neg1", output_port_name='OUT1', input_port_name='IN1')
-        self.addConnection("sum1", "OUT1", output_port_name='OUT1')
-        self.addConnection("neg1", "sum1", output_port_name='OUT1', input_port_name='IN2')
-        self.addConnection("neg2", "sum2", output_port_name='OUT1', input_port_name='IN2')
-        self.addConnection("sum2", "OUT2", output_port_name='OUT1')
-        self.addConnection("root", "OUT3", output_port_name='OUT1')
-
-
-class FibonacciGen(CBD):
-    def __init__(self, block_name):
-        super().__init__(block_name, inputs=[], outputs=['OutFib'])
-
-        # Create the Blocks
-        self.addBlock(InitialConditions("conditions"))
-        self.addBlock(DelayBlock("D1"))
-        self.addBlock(DelayBlock("D2"))
-        self.addBlock(DelayBlock("D3"))
-        self.addBlock(AdderBlock("sum"))
-
-        # Create the Connections
-        self.addConnection("conditions", "D1", output_port_name='OUT1', input_port_name='IC')
-        self.addConnection("conditions", "D2", output_port_name='OUT2', input_port_name='IC')
-        self.addConnection("conditions", "D3", output_port_name='OUT3', input_port_name='IC')
-        self.addConnection("D1", "D2", output_port_name='OUT1', input_port_name='IN1')
-        self.addConnection("D1", "sum", output_port_name='OUT1', input_port_name='IN1')
-        self.addConnection("D2", "sum", output_port_name='OUT1', input_port_name='IN2')
-        self.addConnection("D3", "OutFib", output_port_name='OUT1')
-        self.addConnection("sum", "D1", output_port_name='OUT1', input_port_name='IN1')
-        self.addConnection("sum", "D3", output_port_name='OUT1', input_port_name='IN1')
-
-

+ 14 - 0
parser.py

@@ -63,6 +63,7 @@ class Parser:
 		self.output_class = output_port_class_name
 		self.ignore_empty_nodes = ignore_empty_nodes
 		self.__signals = {}
+		self.__imports = []
 
 	@staticmethod
 	def decode_and_deflate(data):
@@ -94,6 +95,7 @@ class Parser:
 		root = tree.getroot()
 		compressed = len(root.findall(".//mxGraphModel")) == 0
 		class_object_path = ".//object/mxCell/mxGeometry/mxRectangle/../../..[@class_name]"
+		special_object_path = ".//object/mxCell/mxGeometry/../..[@role]"
 		if compressed:
 			# If compressed, first decode base64, then deflate, then url decode
 			pages = root.findall(".//diagram")
@@ -104,6 +106,15 @@ class Parser:
 					res = self.create_node(nroot, obj.attrib)
 					if res is not None:
 						yield res
+				special = nroot.findall(special_object_path)
+				for obj in special:
+					if obj.attrib["role"] == "import":
+						module = obj.attrib["module"]
+						if "objects" in obj.attrib:
+							objects = obj.attrib["objects"]
+							self.__imports.append(f"from {module} import {objects}")
+						else:
+							self.__imports.append(f"import {module}")
 		else:
 			objects = root.findall(class_object_path)
 			for obj in objects:
@@ -111,6 +122,9 @@ class Parser:
 				if res is not None:
 					yield res
 
+	def get_imports(self):
+		return self.__imports
+
 	def create_node(self, root, attr):
 		# TODO: detect duplicate class names
 		# TODO: detect spaces in class names

+ 132 - 5
whishlist.txt

@@ -2,8 +2,135 @@ A list of features that are wanted in this tool:
 
 * More flags:
     -g/--file: only generate specific file(s)
-	-i/--ignore: don't generate specific file(s)
-	-I/--import: add imports to the generated files
-* Allow Renaming of files?
-* Allow global variables/code?
-* Allow setting of drawio xpath
+    -i/--ignore: don't generate specific file(s)
+* Allow Renaming of files? => Via tabs?
+* Allow global variables/code? => Model specific; so no flag
+* Allow setting of drawio xpath => Formalism-specific; set in setup file
+
+
+
+* inverterblock: change symbol \frac{1}{N} to 1/
+  N is confusing as the input is IN1. Furthermore,
+  N seems to indicate that the input must be an integer.
+  Is this the same for the rootblock?
+  ---> Maybe use UTF-8 icons instead of LaTeX? MathJax does
+       not render in the sidebar/library panel (I opened
+       a feature request at drawio for this), so for now
+       using icons may be a better way to go?
+       OK
+  ---> fallback for complex symbols: render/draw and take snapshot
+
+* make the use (and inclusion!) of bokeh dependent 
+  on (1) whether there are any signals to plot and 
+  (2) whether the library can be loaded (with try:)
+  ---> Done!
+
+* low priority: allow the use of matplotlib instead of bokeh.
+  More generally, make it easy to (1) not plot at all,
+  but only save the date for those OutputPortBlocks
+  with a 'signal' property in a standard (.csv, .xml) format,
+  (2) use matplotlib, or (3) use bokeh.
+  ---> matplotlib (or mpl) is now the default for plotting,
+       a commandline argument (-P or --plot) can now switch
+       between mpl, bokeh and csv, or it can disable plotting
+       as a whole.
+  ---> I don't know what the structure of an XML would look like,
+       so it's not implemented (yet).
+       NOT IMPORTANT (for the time being)
+
+* The CBD simulator assumes that all blocks have a unique name. 
+  In what scope?
+  ---> In the scope of each individual CBD itself. This is clarified in the docs.
+  - within the scope of each CBD definition, blocks have a unique name (check this)
+  - CBD definitions must have unique class_name (check this)
+
+* Optionally, additional class parameters can be provided 
+  by adding more properties. 
+  These will be passed on as-is, allowing for complex values.
+  As-is? Indentation? Or declaring local variable?
+  ---> Indentation is now removed from the values.
+  ---> The property values should be expressions/rvalues. This should
+       be clearer in the docs now.
+
+* Otherwise, one may use a single input, as long as the 
+  'numberOfInputs' property is set to a value that is at least the total
+  number of incoming links. ???
+  ---> Unintentional 'feature' caused by the CBD-simulator's 'addConnection'
+       behaviour when 'input_port_name' is not defined. On the one hand, this
+       may add a shorthand for what could be a painful issue. On the other hand,
+       it causes less clean modeling.
+
+* When this option is set, even those ports will explicitly be set.??
+  ---> See previous answer. When set, this parameter will always add the
+       'input_port_name' and 'output_port_name' argument, even if it can be
+       deduced from the context. Counteracts the previous 'feature'.
+
+* Function block (e.g., sin()): GenericBlock?
+  ---> See 'examples/SinGen/' example
+
+* Property 'block_name' is the name of the block if this class is the top-level CBD?
+  OK? Property 'block_name' is the name of an instance of this hierarchical CBD model.
+  ---> ONLY if this class/CBD is marked as 'entry' by the commandline arguments.
+
+* multiple pages: unique names?
+  ---> I agree, it should be nice to actually split up these models graphically, yet
+       a commandline argument to toggle this behaviour seems in order. I only see this
+       possible if every page would create a unique file, which is included where needed.
+       The argument would than probably be --singlefile.
+  ---> As far as I am aware, drawio plugins cannot access the page names, which is why
+       it is now page-independent.
+       TODO: ask Joeri
+
+* online documentation using 
+  https://www.sphinx-doc.org/en/master/usage/restructuredtext/index.html
+  ---> Done!
+
+* be printed to the console --> stdio?
+  ---> Currently, it uses the 'print' function. Using 'sys.stdout' shouldn't be an issue.
+
+* represents an input file (uncompressed or compressed XML) ?OK compressed?
+  ---> I removed that from the documentation. Either is fine, though the compressed might be
+       better performance-wise (and space-wise on your system).
+
+* Generation of LaTeX ... in drawio2cdf and/or in generated "simulator"?
+  ---> In the generated file only. Though, I am not fully convinced the current syntax/way
+       of doing it is 'clean'.
+       TODO: LaTeX functions must be checked/altered (they must be ordered)
+  ---> Add LaTeX generation of the flattened CBDs!
+
+* Generate FMU (in the near future)
+
+* Restructure simulator based on Claudio's version
+
+* In the future: refactor simulator to use internal (graph) structure from ModelverseState (MvS).
+  This is the first step to full integration with the Modelverse. drawio will then be 
+  one possible visual interface for formalism-specific syntax-directed editing of Modelverse models
+
+* currently, remove graphViz (or keep for dependency graph)
+
+* Re-add the "plotting" module, but provide functionality for bokeh, matplotlib, gnuplot, csv, xml... that way
+
+* Move "get_block" function from generated scripts to "CBD" module
+  ---> Done!
+
+* Move __docstring__ attribute to custom shape (Text/Textbox/...) in drawio?
+
+* Add possibility to import other libraries into your custom library, allowing multiple files.
+
+* Custom LaTeX representation for custom blocks?
+
+* RootBlock: is linear if its root is <= 1
+
+* Don't override "if __name__ == '__main__':" option?
+  ---> Maybe only override the classes?
+
+* Reduce the amount of whitespaces for imports
+  ---> Use a list of all import statements instead of making it variable
+       with the file generation.
+
+* Have multiple entry points for the ports possible
+
+* Cleaner/better code generation, that is easily expandible to other frameworks (C [FMU], Java...)
+
+* Fix issues that appear in "troublesome.xml" -- Thank you Nils Charlet for pointing this out!
+