Advertisement
Guest User

Untitled

a guest
Sep 12th, 2017
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import time as tm
  2. import six
  3. import os
  4.  
  5. #ordered dic for C
  6. import collections
  7.  
  8. from .diagram import *
  9. from .sim import *
  10. from functools import partial
  11.  
  12. from .stage import *
  13.  
  14. from xml.dom import minidom, Node
  15. from xml.dom.minidom import parse, parseString, Document
  16. import numpy
  17. import tempfile
  18.  
  19. from PyQt5.QtCore import *
  20. from PyQt5.QtGui import *
  21. from PyQt5.QtWidgets import *
  22.  
  23.  
  24. class esExporterWindow(QMainWindow):
  25.     def __init__(self):
  26.         super().__init__()
  27.         self.initUI()
  28.  
  29.  
  30.     def initUI(self):
  31.         # Window
  32.         self.setGeometry(500, 300, 500, 300)
  33.         self.setWindowTitle('esExporter')
  34.  
  35.         inBrowseButton = QPushButton('Browse', self)
  36.         inBrowseButton.move(370, 95)
  37.         inBrowseButton.clicked.connect(self.addInAddress)
  38.  
  39.         self.inAddress = QLineEdit(self)
  40.         self.inAddress.move(30, 96)
  41.         self.inAddress.dragEnabled()
  42.         self.inAddress.setFixedWidth(330)
  43.  
  44.         outBrowseButton = QPushButton('Browse', self)
  45.         outBrowseButton.move(370, 180)
  46.         outBrowseButton.clicked.connect(self.addOutAddress)
  47.  
  48.         self.outAddress = QLineEdit(self)
  49.         self.outAddress.move(30, 181)
  50.         self.outAddress.dragEnabled()
  51.         self.outAddress.setFixedWidth(330)
  52.  
  53.         exportButton = QPushButton('Export', self)
  54.         exportButton.move(200, 250)
  55.         exportButton.clicked.connect(self.Export)
  56.  
  57.         self.exportFormat=QComboBox(self)
  58.         self.exportFormat.addItem('VHDL')      # self.exportFormat.currentIndex()=0
  59.         self.exportFormat.addItem('XML')       # self.exportFormat.currentIndex()=1
  60.         self.exportFormat.addItem('GraphML')   # self.exportFormat.currentIndex()=2
  61.         self.exportFormat.addItem('C')         # self.exportFormat.currentIndex()=3
  62.         self.exportFormat.move(50, 250)
  63.  
  64.  
  65.         # Texts
  66.         titleText=QLabel('esExporter', self)
  67.         titleText.move(200,20)
  68.  
  69.         inputText=QLabel('Input file (.esdf only)', self)
  70.         inputText.move(30,65)
  71.         inputText.setFixedWidth(200)
  72.  
  73.         outputText=QLabel('Output file', self)
  74.         outputText.move(30, 153)
  75.         inputText.setFixedWidth(200)
  76.  
  77.         conversionFormatText=QLabel('Format', self)
  78.         conversionFormatText.move(80, 225)
  79.         self.show()
  80.  
  81.  
  82.     def addInAddress(self):
  83.         fn = QFileDialog.getOpenFileName(self, 'Open', '..', filter='*.esdf')
  84.         self.inAddress.setText(fn[0])
  85.  
  86.  
  87.     def addOutAddress(self):
  88.         fn = QFileDialog.getSaveFileName(self, 'Save', '..')
  89.         self.outAddress.setText(fn[0])
  90.  
  91.  
  92.     # Export programs
  93.  
  94.  
  95.     def Export(self):
  96.  
  97.         # Analyse which format is asked by the user and select the right conversion program
  98.         if self.exportFormat.currentIndex() == 0:
  99.             self.exportToVHDL()
  100.         elif self.exportFormat.currentIndex() == 1:
  101.             self.exportToXML()
  102.         elif self.exportFormat.currentIndex() == 2:
  103.             self.exportToGRAPHML()
  104.         elif self.exportFormat.currentIndex() == 3:
  105.             self.exportToC()
  106.  
  107.  
  108.     def exportToVHDL(self):
  109.  
  110.         # Creating variables
  111.         inFileAddress=self.inAddress.text()
  112.         outFileAddress=self.outAddress.text()
  113.  
  114.         # Check if the output file has the right extension
  115.         if outFileAddress is not None:
  116.             if outFileAddress.endswith('.vhd') is False:
  117.                 outFileAddress+='.vhd'
  118.  
  119.         # Create a diagram based on the input file and convert it in XML
  120.         diagram = Actors_Canvas(inFileAddress)
  121.         xml_file = convertXML(diagram)
  122.  
  123.         # Create XML file
  124.         fileNameXML = open(outFileAddress + '.xml', 'w')
  125.         fileNameXML.write(xml_file)
  126.         fileNameXML.close()
  127.  
  128.         # Parse the XML file to extract all the information
  129.         dom = parse(outFileAddress + '.xml')
  130.         nbComponent = 1
  131.         components = {}
  132.  
  133.         nbEdge = 1
  134.         edges = {}
  135.  
  136.         componentNames = []
  137.         terminalCheck = []
  138.  
  139.         for component in dom.getElementsByTagName('component'):
  140.             components['cmp' + str(nbComponent)] = {}
  141.  
  142.             for name in component.getElementsByTagName('name'):
  143.                 components['cmp' + str(nbComponent)]['name'] = extractItem(name)
  144.  
  145.             for ref in component.getElementsByTagName('ref'):
  146.                 components['cmp' + str(nbComponent)]['ref'] = extractItem(ref)
  147.  
  148.             nbTerminal = 1
  149.             components['cmp' + str(nbComponent)]['terminals'] = {}
  150.  
  151.             for terminal in component.getElementsByTagName('terminal'):
  152.                 components['cmp' + str(nbComponent)]['terminals']['t' + str(nbTerminal)] = {}
  153.  
  154.                 for type in terminal.getElementsByTagName('type'):
  155.                     components['cmp' + str(nbComponent)]['terminals']['t' + str(nbTerminal)]['type'] = extractItem(type)
  156.  
  157.                 for data_type in terminal.getElementsByTagName('data_type'):
  158.                     components['cmp' + str(nbComponent)]['terminals']['t' + str(nbTerminal)]['data_type'] = extractItem(
  159.                         data_type)
  160.  
  161.                 nbTerminal += 1
  162.  
  163.             nbComponent += 1
  164.  
  165.         for edge in dom.getElementsByTagName('edge'):
  166.  
  167.             for name in edge.getElementsByTagName('name'):
  168.                 edges[extractItem(name)] = {}
  169.  
  170.             for delay in edge.getElementsByTagName('delay'):
  171.                 edges[extractItem(name)]['delay'] = extractItem(delay)
  172.  
  173.             for source in edge.getElementsByTagName('source'):
  174.                 edges[extractItem(name)]['source'] = {}
  175.  
  176.                 for actor in source.getElementsByTagName('actor'):
  177.                     edges[extractItem(name)]['source']['actor'] = extractItem(actor)
  178.  
  179.                 for port in source.getElementsByTagName('port'):
  180.                     edges[extractItem(name)]['source']['port'] = extractItem(port)
  181.  
  182.             for Dest in edge.getElementsByTagName('dest'):
  183.                 edges[extractItem(name)]['dest'] = {}
  184.  
  185.                 for actor in Dest.getElementsByTagName('actor'):
  186.                     edges[extractItem(name)]['dest']['actor'] = extractItem(actor)
  187.  
  188.                 for port in Dest.getElementsByTagName('port'):
  189.                     edges[extractItem(name)]['dest']['port'] = extractItem(port)
  190.  
  191.             nbEdge += 1
  192.  
  193.  
  194.         # Analysing datas
  195.  
  196.         # Edges
  197.         signals_1b_ToCreate = []
  198.         signals_32b_ToCreate = []
  199.  
  200.         for edge_key in edges.keys():
  201.             start = edges[edge_key]['source']['actor'] + edges[edge_key]['source']['port']
  202.             stop = edges[edge_key]['dest']['actor'] + edges[edge_key]['dest']['port']
  203.             signals_1b_ToCreate.append(start + '_TxRdy')
  204.             signals_32b_ToCreate.append(start + '_dOut')
  205.             signals_1b_ToCreate.append(start + '_RxRdy')  # Creating all the FIFO signals
  206.  
  207.             signals_32b_ToCreate.append(stop + '_dIn')
  208.             signals_1b_ToCreate.append(stop + '_TxRdy')
  209.             signals_1b_ToCreate.append(stop + '_RxRdy')
  210.             signals_32b_ToCreate.append(stop + '_dCount')
  211.  
  212.         for item in signals_1b_ToCreate:
  213.             if signals_1b_ToCreate.count(item) != 1:
  214.                 while 1:
  215.                     signals_1b_ToCreate.remove(item)
  216.  
  217.                     if signals_1b_ToCreate.count(item) == 1:
  218.                         break
  219.  
  220.         for item in signals_32b_ToCreate:
  221.             if signals_32b_ToCreate.count(item) != 1:
  222.                 while 1:
  223.                     signals_32b_ToCreate.remove(item)
  224.  
  225.                     if signals_32b_ToCreate.count(item) == 1:
  226.                         break
  227.  
  228.         # Create The VHDL File
  229.         vhdl_file = '-- Diagram to VHDL Exporter\n\n'
  230.         vhdl_file += 'Library IEEE;\n'
  231.         vhdl_file += 'Use IEEE.std_logic_1164.all;\n'
  232.         vhdl_file += 'Use IEEE.numeric_std.all;\n\n'
  233.  
  234.         vhdl_file += 'Library work;\n'
  235.         vhdl_file += 'Use work.SDF_PACKAGE.all;\n\n'
  236.  
  237.         vhdl_file += 'entity bench is\n'
  238.         vhdl_file += '    port(\n'
  239.         vhdl_file += '        clk:   in  std_logic; \n'
  240.         vhdl_file += '        aRstN: in  std_logic;\n'
  241.         vhdl_file += '        sRst:  in  std_logic\n'
  242.         vhdl_file += '        );\n'
  243.         vhdl_file += 'end bench;\n'
  244.  
  245.         vhdl_file += '\nArchitecture ar of bench is\n'
  246.  
  247.         vhdl_file += 'Signal en : std_logic; \n'
  248.  
  249.         for Signal_1b in signals_1b_ToCreate:
  250.             vhdl_file = vhdl_file + 'Signal ' + Signal_1b + ' : std_logic;\n'
  251.  
  252.         for Signal_32b in signals_32b_ToCreate:
  253.             vhdl_file = vhdl_file + 'Signal ' + Signal_32b + ' : std_logic_vector(31 downto 0);\n'
  254.  
  255.         vhdl_file += '\n'
  256.         vhdl_file += ' Begin\n\n'
  257.  
  258.         # Instantiate all the FIFOs
  259.         vhdl_file += '--        Instantiate all the FIFOs \n\n'
  260.  
  261.         for edge_key in edges.keys():
  262.             vhdl_file = vhdl_file + '    FIFO_' + edge_key[1:] + ': FIFO\n'
  263.             vhdl_file = vhdl_file + '        port map ( clk       => clk,\n'
  264.             vhdl_file = vhdl_file + '                   aRstN     => aRstN, \n'
  265.             vhdl_file = vhdl_file + '                   sRst      => sRst, \n'
  266.             vhdl_file = vhdl_file + '                   wrEn      => ' + (
  267.             edges[edge_key]['source']['actor'] + edges[edge_key]['source']['port']) + '_TxRdy' + ',\n'
  268.             vhdl_file = vhdl_file + '                   dIn       => ' + (
  269.             edges[edge_key]['source']['actor'] + edges[edge_key]['source']['port']) + '_dOut' + ',\n'
  270.             vhdl_file = vhdl_file + '                   rdEn      => ' + (
  271.             edges[edge_key]['source']['actor'] + edges[edge_key]['source']['port']) + '_RxRdy' + ',\n'
  272.             vhdl_file = vhdl_file + '                   dOut      => ' + (
  273.             edges[edge_key]['dest']['actor'] + edges[edge_key]['dest']['port']) + '_dIn' + ',\n'
  274.             vhdl_file = vhdl_file + '                   empty     => ' + (
  275.             edges[edge_key]['dest']['actor'] + edges[edge_key]['dest']['port']) + '_TxRdy' + ',\n'
  276.             vhdl_file = vhdl_file + '                   full      => ' + (
  277.             edges[edge_key]['dest']['actor'] + edges[edge_key]['dest']['port']) + '_RxRdy' + ',\n'
  278.             vhdl_file = vhdl_file + '                   dCount    => ' + (
  279.             edges[edge_key]['dest']['actor'] + edges[edge_key]['dest']['port']) + '_dCount' + '\n'
  280.             vhdl_file = vhdl_file + '                  );\n\n'
  281.  
  282.             # Instantiate the components
  283.         vhdl_file += '\n--        Instantiate all the components \n\n'
  284.         for component_key in components.keys():
  285.             if components[component_key]['name'] != 'Solver_SDF' and components[component_key]['name'] != 'Connection':
  286.                 componentNames.append(components[component_key]['name'])
  287.                 nbComponent = componentNames.count(components[component_key]['name'])
  288.                 vhdl_file = vhdl_file + '    ' + components[component_key]['name'] + '_' + str(nbComponent - 1) + ': ' + \
  289.                             components[component_key]['name'] + '\n'
  290.                 vhdl_file = vhdl_file + '        port map ( clk       => clk,\n'
  291.                 vhdl_file = vhdl_file + '                   aRstN     => aRstN,\n'
  292.                 vhdl_file = vhdl_file + '                   sRst      => sRst,\n'
  293.                 vhdl_file = vhdl_file + '                   en        => en,\n'
  294.  
  295.                 nbInOut = 1
  296.  
  297.                 terminalCheck.clear()
  298.                 nbTermComponent = 0
  299.  
  300.                 for terminal_key in components[component_key]['terminals'].keys():
  301.                     if components[component_key]['terminals'][terminal_key]['type'] == 'OUT':
  302.                         for edge_key in edges.keys():
  303.                             if components[component_key]['ref'] == edges[edge_key]['source']['actor']:
  304.                                 if (edges[edge_key]['dest']['actor'] + edges[edge_key]['dest'][
  305.                                     'port']) not in terminalCheck:
  306.                                     terminalCheck.append(
  307.                                         edges[edge_key]['dest']['actor'] + edges[edge_key]['dest']['port'])
  308.                                     vhdl_file = vhdl_file + '                   ' + (
  309.                                     edges[edge_key]['source']['port']) + '_dOut' + '  => ' + (
  310.                                                 edges[edge_key]['source']['actor'] + edges[edge_key]['source'][
  311.                                                     'port']) + '_dOut' + ',\n'
  312.                                     vhdl_file = vhdl_file + '                   ' + (
  313.                                     edges[edge_key]['source']['port']) + '_RxRdy' + ' => ' + (
  314.                                                 edges[edge_key]['source']['actor'] + edges[edge_key]['source'][
  315.                                                     'port']) + '_RxRdy' + ',\n'
  316.                                     vhdl_file = vhdl_file + '                   ' + (
  317.                                     edges[edge_key]['source']['port']) + '_TxRdy' + ' => ' + (
  318.                                                 edges[edge_key]['source']['actor'] + edges[edge_key]['source'][
  319.                                                     'port']) + '_TxRdy'
  320.                                 break
  321.  
  322.                     elif components[component_key]['terminals'][terminal_key]['type'] == 'IN':
  323.                         for edge_key in edges.keys():
  324.                             if components[component_key]['ref'] == edges[edge_key]['dest']['actor']:
  325.                                 if (edges[edge_key]['source']['actor'] + edges[edge_key]['source'][
  326.                                     'port']) not in terminalCheck:
  327.                                     terminalCheck.append(
  328.                                         edges[edge_key]['source']['actor'] + edges[edge_key]['source']['port'])
  329.                                     vhdl_file = vhdl_file + '                   ' + (
  330.                                     edges[edge_key]['dest']['port']) + '_dIn' + '    => ' + (
  331.                                                 edges[edge_key]['dest']['actor'] + edges[edge_key]['dest'][
  332.                                                     'port']) + '_dIn' + ',\n'
  333.                                     vhdl_file = vhdl_file + '                   ' + (
  334.                                     edges[edge_key]['dest']['port']) + '_RxRdy' + '  => ' + (
  335.                                                 edges[edge_key]['dest']['actor'] + edges[edge_key]['dest'][
  336.                                                     'port']) + '_RxRdy' + ',\n'
  337.                                     vhdl_file = vhdl_file + '                   ' + (
  338.                                     edges[edge_key]['dest']['port']) + '_TxRdy' + '  => ' + (
  339.                                                 edges[edge_key]['dest']['actor'] + edges[edge_key]['dest'][
  340.                                                     'port']) + '_TxRdy'
  341.                                     break
  342.  
  343.  
  344.                     elif components[component_key]['terminals'][terminal_key]['type'] == 'INOUT':
  345.                         vhdl_file = vhdl_file + 'INOUT_' + str(nbInOut)
  346.                         nbInOut += 1
  347.  
  348.                     nbTermComponent += 1
  349.  
  350.                     if len(components[component_key]['terminals']) != nbTermComponent:
  351.                         vhdl_file += (',\n')
  352.  
  353.                     else:
  354.                         vhdl_file += ('\n')
  355.  
  356.                 vhdl_file = vhdl_file + '                 );\n\n'
  357.  
  358.                 # Finish the file
  359.         vhdl_file += 'End ar;\n'
  360.         file = open(outFileAddress, 'w')
  361.         file.write(vhdl_file)
  362.         file.close()
  363.  
  364.         os.remove(outFileAddress+ '.xml')
  365.  
  366.  
  367.     def exportToXML(self):
  368.         # Creating variables
  369.         inFileAddress = self.inAddress.text()
  370.         outFileAddress = self.outAddress.text()
  371.  
  372.         # Check if the output file has the right extension
  373.         if outFileAddress is not None:
  374.             if outFileAddress.endswith('.xml') is False:
  375.                 outFileAddress += '.xml'
  376.  
  377.         # Create a diagram based on the input file and convert it in XML
  378.         diagram = Actors_Canvas(inFileAddress)
  379.         xml_file = convertXML(diagram)
  380.  
  381.         # Create XML file
  382.         fileNameXML = open(outFileAddress, 'w')
  383.         fileNameXML.write(xml_file)
  384.         fileNameXML.close()
  385.  
  386.  
  387.     def exportToGRAPHML(self):
  388.         # Creating variables
  389.         inFileAddress = self.inAddress.text()
  390.         outFileAddress = self.outAddress.text()
  391.  
  392.         # Check if the output file has the right extension
  393.         if outFileAddress is not None:
  394.             if outFileAddress.endswith('.graphml') is False:
  395.                 outFileAddress += '.graphml'
  396.  
  397.         # Create a diagram based on the input file and convert it in XML
  398.         diagram = Actors_Canvas(inFileAddress)
  399.  
  400.         # Create GraphML document
  401.         nbTermComponent = 0
  402.         netNameCheck = []
  403.  
  404.         doc = minidom.Document()
  405.         doc.appendChild(doc.createComment("Diagram to GraphML Exporter"))
  406.         root = doc.createElement('root')
  407.         doc.appendChild(root)
  408.  
  409.         for Component in diagram.diagram.componentList:
  410.             if Component.className != 'Constant':
  411.                 component = doc.createElement('component')
  412.                 component.setAttribute('name', str(Component.className))
  413.                 component.setAttribute('Ref', str(Component.parameter['Ref'].value))
  414.                 root.appendChild(component)
  415.  
  416.                 for key in Component.terminal.keys():
  417.                     terminal = doc.createElement('terminal')
  418.  
  419.                     if Component.terminal[key].termType == 1:
  420.                         terminal.setAttribute('type', 'CONN')
  421.  
  422.                     if Component.terminal[key].termType == 2:
  423.                         terminal.setAttribute('type', 'IN')
  424.  
  425.                     if Component.terminal[key].termType == 4:
  426.                         terminal.setAttribute('type', 'OUT')
  427.  
  428.                     if Component.terminal[key].termType == 8:
  429.                         terminal.setAttribute('type', 'INOUT')
  430.  
  431.                     if str(type(Component.terminal[key].value)) == "<class 'float'>":
  432.                         terminal.setAttribute('data_type', 'float')
  433.  
  434.                     component.appendChild(terminal)
  435.  
  436.             if Component.className == 'Constant':
  437.                 constant = doc.createElement('constant')
  438.                 constant.setAttribute('name', str(Component.parameter['Ref'].value))
  439.                 for key in Component.terminal.keys():
  440.                     constant.setAttribute('value', str(Component.terminal[key].value))
  441.                 root.appendChild(constant)
  442.  
  443.         if diagram.simEngine is None:
  444.             diagram.simEngine = Action(diagram.diagram)
  445.  
  446.             netInfos = diagram.simEngine.checkNetwork()
  447.  
  448.         for key in netInfos.keys():
  449.  
  450.             if key not in netNameCheck:
  451.                 netNameCheck.append(key)
  452.  
  453.                 edge = doc.createElement('edge')
  454.                 edge.setAttribute('name', str(key))
  455.                 edge.setAttribute('delay', str(netInfos[key][4]))
  456.                 root.appendChild(edge)
  457.                 source = doc.createElement('source')
  458.                 source.setAttribute('actor', str(netInfos[key][0]))
  459.                 source.setAttribute('port', str(netInfos[key][1]))
  460.                 edge.appendChild(source)
  461.                 dest = doc.createElement('dest')
  462.                 dest.setAttribute('actor', str(netInfos[key][2]))
  463.                 dest.setAttribute('port', str(netInfos[key][3]))
  464.                 edge.appendChild(dest)
  465.  
  466.         file = open(outFileAddress, 'w')
  467.         file.write(doc.toprettyxml(indent='    '))
  468.         file.close()
  469.  
  470.  
  471.     def exportToC(self):
  472.         # Creating variables
  473.         inFileAddress = self.inAddress.text()
  474.         outFileAddress = self.outAddress.text()
  475.  
  476.         # Check if the output file has the right extension
  477.         if outFileAddress is not None:
  478.             if outFileAddress.endswith('.c') is False:
  479.                 outFileAddress += '.c'
  480.  
  481.         # Create a diagram based on the input file and convert it in XML
  482.         diagram = Actors_Canvas(inFileAddress)
  483.         xml_file = convertXML(diagram)
  484.  
  485.         # Create XML file
  486.         fileNameXML = open(outFileAddress + '.xml', 'w')
  487.         fileNameXML.write(xml_file)
  488.         fileNameXML.close()
  489.  
  490.         # Parse the XML file to extract all the information
  491.         dom = parse(outFileAddress + '.xml')
  492.         nbComponent = 1
  493.         components = {}
  494.  
  495.         nbEdge = 1
  496.         edges = {}
  497.  
  498.         componentNames = []
  499.         terminalCheck = []
  500.  
  501.         for component in dom.getElementsByTagName('component'):
  502.             components['cmp' + str(nbComponent)] = {}
  503.  
  504.             for name in component.getElementsByTagName('name'):
  505.                     components['cmp' + str(nbComponent)]['name'] = extractItem(name)
  506.  
  507.             for gain in component.getElementsByTagName('gain') :
  508.                     components['cmp' + str(nbComponent)]['gain'] = extractItem(gain)
  509.  
  510.             for offset in component.getElementsByTagName('offset'):
  511.                     components['cmp' + str(nbComponent)]['offset'] = extractItem(offset)
  512.  
  513.             for amplitude in component.getElementsByTagName('amplitude') :
  514.                     components['cmp' + str(nbComponent)]['amplitude'] = extractItem(amplitude)
  515.  
  516.             for frequency in component.getElementsByTagName('frequency') :
  517.                     components['cmp' + str(nbComponent)]['frequency'] = extractItem(frequency)
  518.  
  519.             for phase in component.getElementsByTagName('phase') :
  520.                     components['cmp' + str(nbComponent)]['phase'] = extractItem(phase)
  521.  
  522.             for slope in component.getElementsByTagName('slope') :
  523.                     components['cmp' + str(nbComponent)]['slope'] = extractItem(slope)
  524.  
  525.             for upper_random in component.getElementsByTagName('upper_random') :
  526.                     components['cmp' + str(nbComponent)]['upper_random'] = extractItem(upper_random)
  527.  
  528.             for lower_random in component.getElementsByTagName('lower_random') :
  529.                     components['cmp' + str(nbComponent)]['lower_random'] = extractItem(lower_random)
  530.  
  531.             for constant_value in component.getElementsByTagName('constant_value') :
  532.                     components['cmp' + str(nbComponent)]['constant_value'] = extractItem(constant_value)
  533.  
  534.             for pulse_width in component.getElementsByTagName('pulse_width') :
  535.                     components['cmp' + str(nbComponent)]['pulse_width'] = extractItem(pulse_width)
  536.  
  537.             for polarity in component.getElementsByTagName('polarity') :
  538.                     components['cmp' + str(nbComponent)]['polarity'] = extractItem(polarity)
  539.  
  540.             for ref in component.getElementsByTagName('ref'):
  541.                 components['cmp' + str(nbComponent)]['ref'] = extractItem(ref)
  542.  
  543.             nbTerminal = 1
  544.             components['cmp' + str(nbComponent)]['terminals'] = {}
  545.  
  546.             for terminal in component.getElementsByTagName('terminal'):
  547.                 components['cmp' + str(nbComponent)]['terminals']['t' + str(nbTerminal)] = {}
  548.  
  549.                 for type in terminal.getElementsByTagName('type'):
  550.                     components['cmp' + str(nbComponent)]['terminals']['t' + str(nbTerminal)]['type'] = extractItem(type)
  551.  
  552.                 for data_type in terminal.getElementsByTagName('data_type'):
  553.                     components['cmp' + str(nbComponent)]['terminals']['t' + str(nbTerminal)]['data_type'] = extractItem(
  554.                         data_type)
  555.  
  556.                 nbTerminal += 1
  557.  
  558.             nbComponent += 1
  559.  
  560.         for edge in dom.getElementsByTagName('edge'):
  561.  
  562.             for name in edge.getElementsByTagName('name'):
  563.                 edges[extractItem(name)] = {}
  564.  
  565.             for delay in edge.getElementsByTagName('delay'):
  566.                 edges[extractItem(name)]['delay'] = extractItem(delay)
  567.  
  568.             for source in edge.getElementsByTagName('source'):
  569.                 edges[extractItem(name)]['source'] = {}
  570.  
  571.                 for actor in source.getElementsByTagName('actor'):
  572.                     edges[extractItem(name)]['source']['actor'] = extractItem(actor)
  573.  
  574.                 for port in source.getElementsByTagName('port'):
  575.                     edges[extractItem(name)]['source']['port'] = extractItem(port)
  576.  
  577.             for Dest in edge.getElementsByTagName('dest'):
  578.                 edges[extractItem(name)]['dest'] = {}
  579.  
  580.                 for actor in Dest.getElementsByTagName('actor'):
  581.                     edges[extractItem(name)]['dest']['actor'] = extractItem(actor)
  582.  
  583.                 for port in Dest.getElementsByTagName('port'):
  584.                     edges[extractItem(name)]['dest']['port'] = extractItem(port)
  585.  
  586.             nbEdge += 1
  587.  
  588.         # Analysing datas
  589.  
  590.         # SDF structure : getting the scheduler from the data in the XMl
  591.         compRef = []
  592.         edgeNames = []
  593.         quu = []
  594.         cpt = 0
  595.         v0 = []
  596.         S0 = []
  597.         b0 = [np.asarray([edges[edge]['delay'] for edge in edges], dtype=np.int64)]
  598.  
  599.         for comp in components.keys():
  600.             if (components[comp]['name'] != 'Connection' and components[comp]['name'] != 'Solver_SDF'):
  601.                 compRef.append(components[comp]['ref'])
  602.  
  603.         nbComponent -= 2
  604.         nbEdge -= 1
  605.         gamma = np.zeros((nbEdge, nbComponent), dtype=np.int64)
  606.  
  607.         component_RateByRef = {}
  608.  
  609.         # getting the rates of the different components
  610.         for component in diagram.diagram.componentList:
  611.             component_ref = component.parameter["Ref"].value
  612.             for terminal in component.terminal:
  613.                 key = component_ref + '_' + component.terminal[terminal].name
  614.                 component_RateByRef[key] = component.terminal[terminal].rate
  615.  
  616.  
  617.         cpt = 0
  618.         for i in edges:
  619.             src_col = compRef.index(edges[i]['source']['actor'])
  620.             snk_col = compRef.index(edges[i]['dest']['actor'])
  621.             gamma[cpt][src_col] = component_RateByRef[edges[i]['source']['actor'] + '_' + edges[i]['source']['port']]
  622.             gamma[cpt][snk_col] = - component_RateByRef[edges[i]['dest']['actor'] + '_' + edges[i]['dest']['port']]
  623.             edgeNames.append(i)
  624.             cpt += 1
  625.  
  626.         quu = nullspace(gamma).flatten()
  627.         quu = (quu / quu.max())
  628.         quu = np.rint(quu).astype(int)
  629.  
  630.         rem0 = [quu]
  631.  
  632.         while rem0[-1].any() != 0:
  633.             v0.append(np.zeros(nbComponent))
  634.             (b1, rem1) = (b0[-1], rem0[-1])
  635.             v1 = np.zeros(nbComponent, dtype=np.int64)
  636.             for i in range(gamma.shape[1]):
  637.                 # initialise remainder
  638.                 v1[i] = rem1[i]
  639.                 # iterate over elements of the column
  640.                 for j in range(gamma.shape[0]):
  641.                     # Â if actor consumes from this arc
  642.                     if gamma[j, i] < 0:
  643.                         # set number of reps to lower of v
  644.                         # or quotient of no. in buffer divide by rat
  645.                             v1[i] = min(v1[i], numpy.true_divide(-1 * b1[j], gamma[j, i]))
  646.  
  647.             if v1.any() != 0:
  648.                 v0[-1] = v1
  649.                 b0.append(np.dot(gamma, v1) + b1)
  650.                 rem0.append(rem1 - v1)
  651.                 # append the necessary firings to the schedule
  652.                 for k in range(len(v1)):
  653.                     for l in range(int(v1[k])):
  654.                         S0.append(compRef[k])
  655.  
  656.  
  657.         # creating pointer for the struct of the C
  658.  
  659.         actor_pointer = []
  660.         for component in components:
  661.             if components[component]["name"] != "Solver_SDF":
  662.                 d = collections.OrderedDict()
  663.                 for edge in edges:
  664.                     for node in edges[edge]:
  665.                         if node =="source":
  666.                             if edges[edge]["source"]["actor"] == components[component]["ref"]:
  667.                                 d[edges[edge]["source"]["port"]] = edge
  668.                         if node =="dest":
  669.                             if edges[edge]["dest"]["actor"] == components[component]["ref"]:
  670.                                 d[edges[edge]["dest"]["port"]] = edge
  671.                 actor_pointer.append(d)
  672.  
  673.  
  674.         #Creating the C file
  675.         C_file = '#include <stdio.h>\n'
  676.         C_file += '#include <stdlib.h>\n'
  677.         C_file += '#include <string.h>\n'
  678.         C_file += '#include <math.h>\n\n'
  679.         #Must end all others includes
  680.  
  681.         C_file += "#define STEP_TIME 0.05\n"
  682.         C_file += "#define END_SIMULATION 4.0\n\n"
  683.  
  684.         #declare needed variables
  685.         #Beginning the instanciation of the FiFo
  686.         C_file += '///////////////////////////////First In First Out///////////////////////////////\n'
  687.  
  688.         file = open(outFileAddress, 'w+')
  689.         file.write(C_file)
  690.         file.close()
  691.  
  692.         # Opening another C file, Fifo
  693.         location = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'fifo.txt')
  694.         Fifo_file = open(location, 'r+', encoding='utf-8-sig')
  695.         C_file = Fifo_file.read()
  696.         Fifo_file.close()
  697.  
  698.  
  699.  
  700.  
  701.         #Beginning the prototypes of each function
  702.         C_file += '\n///////////////////////////////Function prototypes///////////////////////////////\n\n'
  703.  
  704.         file = open(outFileAddress, 'a', encoding='utf-8-sig')
  705.         file.write(C_file)
  706.         file.close()
  707.  
  708.         ComponentNameByRef = {}
  709.         # looking at the component list to write the function head
  710.         for component_key in components.keys():
  711.             if components[component_key]['name'] != 'Solver_SDF' and components[component_key]['name'] != 'Connection':
  712.                 componentNames.append(components[component_key]['name'])
  713.  
  714.                 nbComponent = componentNames.count(components[component_key]['name'])
  715.                 ComponentNameByRef[components[component_key]['ref']] = components[component_key]['name'] + '_' + str(nbComponent - 1)
  716.  
  717.                 C_file = 'int ' + ComponentNameByRef[components[component_key]['ref']] \
  718.                           + '( Actor_context *data_structure '
  719.                 if (components[component_key]['name'] == 'GenSine' or components[component_key]['name'] == 'GenCos'
  720.                     or components[component_key]['name'] == 'GenSineContr' or components[component_key]['name'] == 'GenRamp'):
  721.                     C_file += ', float time'
  722.  
  723.                 C_file += ')\n'
  724.                 C_file += '{\n'
  725.                 C_file += compFunctionC(components, component_key)
  726.                 C_file += '}\n\n'
  727.                 file = open(outFileAddress, 'a', encoding='utf-8-sig')
  728.                 file.write(C_file)
  729.                 file.close()
  730.  
  731.         # Beginning the Main
  732.         C_file = '///////////////////////////////Main function///////////////////////////////\n\n'
  733.         C_file += '\nvoid main (void)\n{\n//initialization of the Fifos\n\n'
  734.         i= 0
  735.  
  736.         max_size_fifo = 2
  737.         for rate_key in component_RateByRef:
  738.             rate = component_RateByRef[rate_key]
  739.             if rate>max_size_fifo:
  740.                 max_size_fifo = rate
  741.  
  742.         C_file += "\n//max fifo_size = %s \n//note : default size of Fifo is 2 instead of 1, because we want to use an array\n\n" % (str(max_size_fifo))
  743.  
  744.         i=0
  745.         for edge in edges:
  746.  
  747.             max_size_fifo = 2
  748.             for token_list in b0:
  749.                 if token_list[i]>max_size_fifo:
  750.                     max_size_fifo = token_list[i]
  751.  
  752.             C_file += "float fifodata_%s[2];\n" % edge
  753.             C_file += "Float_fifo *fifo_%s = Fifo_initialize(fifodata_%s, %s);\n\n" % (edge, edge, str(max_size_fifo))
  754.             i += 1
  755.  
  756.         C_file += "\n //Initialization of the different actor_context\n\n"
  757.         i = 0
  758.         for component in components:
  759.             if components[component]["name"] != "Solver_SDF":
  760.                 if(len(actor_pointer[i]) == 1 ):
  761.                     value = next (iter (actor_pointer[i].values()))
  762.                     C_file += "Float_fifo *tab_tempo%i = fifo_%s;\n" % (i, value)
  763.                 else:
  764.                     C_file += "Float_fifo *tab_tempo%i[%i] = " % (i, len(actor_pointer[i]))
  765.                     C_file += "{"
  766.                     for j in range(len(actor_pointer[i])):
  767.                         if j>0:
  768.                             C_file += ','
  769.                         C_file +="fifo_"
  770.                         C_file += list(actor_pointer[i].values())[j]
  771.                     C_file += "};\n"
  772.  
  773.                 l = actor_pointer[i].keys()
  774.                 nb_in = 0
  775.                 nb_out = 0
  776.  
  777.                 if 'IN' in l:
  778.                     nb_in = 1
  779.                 else:
  780.                     j = 1
  781.                     while(j != 0):
  782.                         tempo = "IN" + str(j)
  783.                         if tempo in l:
  784.                             nb_in += 1
  785.                             j += 1
  786.                         else:
  787.                             j = 0
  788.  
  789.                 if 'OUT' in l:
  790.                     nb_out = 1
  791.                 else:
  792.                     j = 1
  793.                     while(j != 0):
  794.                         tempo = "OUT" + str(j)
  795.                         if tempo in l:
  796.                             nb_out += 1
  797.                             j += 1
  798.                         else:
  799.                             j = 0
  800.  
  801.                 C_file += "// nb in : %i, nb_out : %i \n" % (nb_in, nb_out)
  802.                 C_file += "Actor_context *struct_%s = Structure_initialize(%i,%i, tab_tempo%i);\n\n" % ( ComponentNameByRef[components[component]["ref"]],nb_in,nb_out,i)
  803.                 i += 1
  804.  
  805.  
  806.         C_file += "\n//initialization of time :\nfloat time = 0;\n\n"
  807.         C_file += 'while(time < END_SIMULATION)\n    {\n'
  808.         C_file += "    //incrementing of time\n    time = time + STEP_TIME;\n\n"
  809.  
  810.         for item in S0:
  811.             for component in components:
  812.                 if components[component]["ref"] == item:
  813.                     #@todo check if some other components need time variable
  814.                     if(components[component]["name"] == "GenRamp" or components[component]["name"] == "GenSine" or components[component]["name"] == "GenCos"):
  815.                         tempo = '(struct_' + ComponentNameByRef[components[component]["ref"]] + ', time);\n'
  816.                     else:
  817.                         tempo = '(struct_' + ComponentNameByRef[components[component]["ref"]] + ');\n'
  818.  
  819.                     C_file += '    ' + ComponentNameByRef[components[component]["ref"]] + tempo
  820.  
  821.         C_file += '\n    }\n}'
  822.  
  823.  
  824.         file = open(outFileAddress, 'a')
  825.         file.write(C_file)
  826.         file.close()
  827.  
  828.         """with open(outFileAddress, "a") as file:
  829.            myfile.write(C_file)
  830.        file.close()"""
  831.  
  832.  
  833. def compFunctionC(comp, compKey):
  834.     # looking at the component name to fill the function body with the right functionning
  835.     cfile = ''
  836.     if comp[compKey]['name'] == 'Gain':
  837.         cfile += '     // Gain formula : output = input * gain + offset\n'
  838.         cfile += '    float tempo;\n\n'
  839.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo);\n'
  840.         cfile += '    Fifo_push_data(data_structure->Fifo[1], (tempo * ' + comp[compKey]['gain'] + ' + ' \
  841.                   + comp[compKey]['offset'] + '));\n'
  842.         cfile += '    return 1;\n'
  843.  
  844.     if (comp[compKey]['name'] == 'Sum21' or comp[compKey]['name'] == 'Sum22' or comp[compKey]['name'] == 'Sum31'):
  845.         cfile += '    // Component is is a simple sum block, summing all its input in the output\n'
  846.         cfile += '    float tempo1, tempo2'
  847.  
  848.         if comp[compKey]['name'] == 'Sum31':
  849.             cfile += ', tempo3;\n\n'
  850.         else :
  851.             cfile += ';\n\n'
  852.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo1);\n'
  853.         cfile += '    Fifo_pop_data(data_structure->Fifo[1], &tempo2);\n'
  854.  
  855.         if comp[compKey]['name'] == 'Sum31' :
  856.             cfile += '    Fifo_pop_data(data_structure->Fifo[2], &tempo3);\n'
  857.             cfile += '    Fifo_push_data(data_structure->Fifo[3], tempo1 + tempo2 + tempo3);\n'
  858.         else :
  859.             cfile += '    Fifo_push_data(data_structure->Fifo[2], tempo1 + tempo2);\n'
  860.         cfile += 'return 1;\n'
  861.  
  862.     if (comp[compKey]['name'] == 'Mult21' or comp[compKey]['name'] == 'Mult22' or comp[compKey]['name'] == 'Mult31'):
  863.         cfile += '    // Component is is a simple multiplication block, multiplicating all its input and putting ' \
  864.                  'the result in the output\n'
  865.         cfile += '    float tempo1, tempo2'
  866.  
  867.         if comp[compKey]['name'] == 'Mult31':
  868.             cfile += ', tempo3;\n\n'
  869.         else:
  870.             cfile += ';\n\n'
  871.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo1);\n'
  872.         cfile += '    Fifo_pop_data(data_structure->Fifo[1], &tempo2);\n'
  873.  
  874.         if comp[compKey]['name'] == 'Mult31':
  875.             cfile += '    Fifo_pop_data(data_structure->Fifo[2], &tempo3);\n'
  876.             cfile += '    Fifo_push_data(data_structure->Fifo[3], tempo1 * tempo2 * tempo3);\n'
  877.         else:
  878.             cfile += '    Fifo_push_data(data_structure->Fifo[2], tempo1 * tempo2);\n'
  879.         cfile += '    return 1;\n'
  880.  
  881.     if (comp[compKey]['name'] == 'GenSine' or comp[compKey]['name'] == 'GenCos') :
  882.         cfile += '    // Component is a '
  883.         if comp[compKey]['name'] == 'GenSine':
  884.             cfile += 'Sine'
  885.         elif comp[compKey]['name'] == 'GenCos':
  886.             cfile += 'Cos'
  887.  
  888.         cfile += ' generator and the formula used is :\n    // amplitude * '
  889.         if comp[compKey]['name'] == 'GenSine':
  890.             cfile += 'sin'
  891.         elif comp[compKey]['name'] == 'GenCos' :
  892.             cfile += 'cos'
  893.  
  894.         cfile += '(2 * M_PI * frequency * time + phase) + offset\n'
  895.         cfile += '    Fifo_push_data(data_structure->Fifo[0],(float)(' + comp[compKey]['amplitude'] + ' * '
  896.         if comp[compKey]['name'] == 'GenSine':
  897.             cfile += 'sin'
  898.         elif comp[compKey]['name'] == 'GenCos' :
  899.             cfile += 'cos'
  900.         cfile += '( 2 * M_PI * ' + comp[compKey]['frequency']  + ' * time + ' + comp[compKey]['phase'] + ') + ' \
  901.                  + comp[compKey]['offset'] + '));\n'
  902.         cfile += '    return 1;\n'
  903.  
  904.     if comp[compKey]['name'] == 'GenRandInt' :
  905.         cfile += '    // Component is a random integer generator and the formula used is : output = rand()%(max-min)+min;\n'
  906.         cfile += '    // max and min are the values that limit the generation of thoses integers\n'
  907.         cfile += '    srand(time(NULL));\n'
  908.         cfile += '    Fifo_push_data(data_structure->Fifo[0], (rand()%(' + comp[compKey]['upper_random'] + '-' \
  909.                  + comp[compKey]['lower_random'] + ')' + comp[compKey]['lower_random'] + '));\n'
  910.  
  911.     if comp[compKey]['name'] == 'GenRamp' :
  912.         cfile += '    // component is a ramp generator, using this formula : output = time * slope + offset\n'
  913.         cfile += '    Fifo_push_data(data_structure->Fifo[0], (time * ' + comp[compKey]['slope'] + ' + ' \
  914.                  + comp[compKey]['offset'] + '));\n'
  915.  
  916.     if comp[compKey]['name'] == 'GenPulse' :
  917.         cfile += '    // Component is a Pulse generator.'
  918.         cfile += '    float temp;\nfloat value;\n'
  919.         cfile += '    temp = fmod(time + ' + comp[compKey]['phase'] + ', 1 / ' + comp[compKey]['frequency'] + ');\n'
  920.         cfile += '    if(temp * ' + comp[compKey]['frequency'] + ' <= ' + comp[compKey]['pulse_width'] + ' * 0.01)\n'
  921.         cfile += '        value = ' + comp[compKey]['amplitude'] + ' ;\n'
  922.         cfile += '    else\n'
  923.         cfile += '        value = -' + comp[compKey]['amplitude'] + ' ;\n'
  924.         cfile += '    Fifo_push_data(data_structure->Fifo[0], (value + ' + comp[compKey]['offset'] + '));\n'
  925.  
  926.     if comp[compKey]['name'] == 'GenConst' :
  927.         cfile += '    Fifo_push_data(data_structure->Fifo[0],' + comp[compKey]['constant_value'] + ');\n'
  928.  
  929.     if comp[compKey]['name'] == 'GenSineContr' :
  930.         cfile += '    // Data on the first port is the amplitude and the one on the second port is the frequency'
  931.         cfile += '    float tempo1, tempo2;\n'
  932.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo1);\n'
  933.         cfile += '    Fifo_pop_data(data_structure->Fifo[1], &tempo2);\n'
  934.         cfile += '    Fifo_push_data(data_structure->Fifo[2], (tempo1 * sin( 2 * pi * tempo2 * time)));\n'
  935.         cfile += '    return 1;\n'
  936.  
  937.     if comp[compKey]['name'] == 'Console' :
  938.         cfile += '    float tempo;\n'
  939.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo);\n'
  940.         cfile += '    printf("Output value : %f \\n\\n\\r",tempo);\n'
  941.         cfile += '    return 1;\n'
  942.  
  943.     if comp[compKey]['name'] == 'Sqrt' :
  944.         cfile += '    float tempo;\n'
  945.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo);\n'
  946.         cfile += '    Fifo_push_data(data_structure->Fifo[1], sqrt(tempo));\n'
  947.         cfile += '    return 1;\n'
  948.  
  949.     if comp[compKey]['name'] == 'Cos' :
  950.         cfile += '    float tempo;\n'
  951.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo);\n'
  952.         cfile += '    Fifo_push_data(data_structure->Fifo[1], cos(tempo));\n'
  953.         cfile += '    return 1;\n'
  954.  
  955.     if comp[compKey]['name'] == 'Sin' :
  956.         cfile += '    float tempo;\n'
  957.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo);\n'
  958.         cfile += '    Fifo_push_data(data_structure->Fifo[1], sin(tempo));\n'
  959.         cfile += '    return 1;\n'
  960.  
  961.     if comp[compKey]['name'] == 'Abs' :
  962.         cfile += '    float tempo;\n'
  963.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo);\n'
  964.         cfile += '    Fifo_push_data(data_structure->Fifo[1], abs(tempo));\n'
  965.         cfile += '    return 1;\n'
  966.  
  967.     if comp[compKey]['name'] == 'Exp' :
  968.         cfile += '    float tempo;\n'
  969.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo);\n'
  970.         cfile += '    Fifo_push_data(data_structure->Fifo[1], exp(tempo));\n'
  971.         cfile += '    return 1;\n'
  972.  
  973.     if comp[compKey]['name'] == 'Pow2' :
  974.         cfile += '    float tempo;\n'
  975.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo);\n'
  976.         cfile += '    Fifo_push_data(data_structure->Fifo[1], tempo * tempo);\n'
  977.         cfile += '    return 1;\n'
  978.  
  979.     if comp[compKey]['name'] == 'Ln' :
  980.         cfile += '    float tempo;\n'
  981.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo);\n'
  982.         cfile += '    Fifo_push_data(data_structure->Fifo[1], log(tempo));\n'
  983.         cfile += '    return 1;\n'
  984.  
  985.     if comp[compKey]['name'] == 'Log10' :
  986.         cfile += '    float tempo;\n'
  987.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo);\n'
  988.         cfile += '    Fifo_push_data(data_structure->Fifo[1], log10(tempo));\n'
  989.         cfile += '    return 1;\n'
  990.  
  991.     if comp[compKey]['name'] == 'FuncEval' :
  992.         cfile += '    float tempo;\n'
  993.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo);\n'
  994.         cfile += '    Fifo_push_data(data_structure->Fifo[1], (4*sin(tempo)+tempo));\n'
  995.         cfile += '    return 1;\n'
  996.  
  997.     if comp[compKey]['name'] == 'Min' :
  998.         cfile += '    static double minVal;\n    float tempo;\n    unsigned char lock = 0;\n\n'
  999.         cfile += '    if(lock == 0)\n    {\n'
  1000.         cfile += '        lock = 1;\n'
  1001.         cfile += '        minVal = 1*exp(38);\n    }\n\n'
  1002.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo);\n'
  1003.         cfile += '    if(tempo < minVal)\n'
  1004.         cfile += '        minVal = tempo;\n\n'
  1005.         cfile += '    Fifo_push_data(data_structure->Fifo[1], minVal);\n'
  1006.         cfile += '    return 1 ;\n'
  1007.  
  1008.     if comp[compKey]['name'] == 'Max' :
  1009.         cfile += '    static double maxVal;\n    float tempo;\n    unsigned char lock = 0;\n\n'
  1010.         cfile += '    if(lock == 0)\n    {\n'
  1011.         cfile += '        lock = 1;\n'
  1012.         cfile += '        maxVal = -1*exp(38);\n    }\n\n'
  1013.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo);\n'
  1014.         cfile += '    if(tempo > maxVal)\n'
  1015.         cfile += '        maxVal = tempo;\n\n'
  1016.         cfile += '    Fifo_push_data(data_structure->Fifo[1], maxVal);\n'
  1017.         cfile += '    return 1 ;\n'
  1018.  
  1019.     if comp[compKey]['name'] == 'Ratio' :
  1020.         cfile += '    float tempo;\n'
  1021.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo);\n'
  1022.         cfile += '    Fifo_push_data(data_structure->Fifo[1], (1.0 / tempo));\n'
  1023.         cfile += '    return 1;\n'
  1024.  
  1025.     if comp[compKey]['name'] == 'Buffer':
  1026.         cfile += '    float tempo;\n'
  1027.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo);\n'
  1028.         cfile += '    Fifo_push_data(data_structure->Fifo[1],tempo);\n'
  1029.         cfile += '    return 1;\n'
  1030.  
  1031.     if comp[compKey]['name'] == 'Invertor':
  1032.         cfile += '    float tempo;\n'
  1033.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo);\n'
  1034.         cfile += '    Fifo_push_data(data_structure->Fifo[1], NOT tempo);\n'
  1035.         cfile += '    return 1;\n'
  1036.  
  1037.     if comp[compKey]['name'] == 'And3':
  1038.         cfile += '    float tempo1, tempo2, tempo3;\n'
  1039.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo1);\n'
  1040.         cfile += '    Fifo_pop_data(data_structure->Fifo[1], &tempo2);\n'
  1041.         cfile += '    Fifo_pop_data(data_structure->Fifo[2], &tempo3);\n'
  1042.         cfile += '    Fifo_push_data(data_structure->Fifo[3],(tempo1 and tempo2 and tempo 3));\n'
  1043.         cfile += '    return 1;\n'
  1044.  
  1045.     if comp[compKey]['name'] == 'Nand3':
  1046.         cfile += '    float tempo1, tempo2, tempo3;\n'
  1047.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo1);\n'
  1048.         cfile += '    Fifo_pop_data(data_structure->Fifo[1], &tempo2);\n'
  1049.         cfile += '    Fifo_pop_data(data_structure->Fifo[2], &tempo3);\n'
  1050.         cfile += '    Fifo_push_data(data_structure->Fifo[3], NOT(tempo1 and tempo2 and tempo 3));\n'
  1051.         cfile += '    return 1;\n'
  1052.  
  1053.     if comp[compKey]['name'] == 'And2':
  1054.         cfile += '    float tempo1, tempo2;\n'
  1055.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo1);\n'
  1056.         cfile += '    Fifo_pop_data(data_structure->Fifo[1], &tempo2);\n'
  1057.         cfile += '    Fifo_push_data(data_structure->Fifo[2],(tempo1 and tempo2));\n'
  1058.         cfile += '    return 1;\n'
  1059.  
  1060.     if comp[compKey]['name'] == 'Nand2':
  1061.         cfile += '    float tempo1, tempo2;\n'
  1062.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo1);\n'
  1063.         cfile += '    Fifo_pop_data(data_structure->Fifo[1], &tempo2);\n'
  1064.         cfile += '    Fifo_push_data(data_structure->Fifo[2], NOT(tempo1 and tempo2));\n'
  1065.         cfile += '    return 1;\n'
  1066.  
  1067.     if comp[compKey]['name'] == 'Nor2':
  1068.         cfile += '    float tempo1, tempo2;\n'
  1069.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo1);\n'
  1070.         cfile += '    Fifo_pop_data(data_structure->Fifo[1], &tempo2);\n'
  1071.         cfile += '    Fifo_push_data(data_structure->Fifo[2], NOT(tempo1 or tempo2));\n'
  1072.         cfile += '    return 1;\n'
  1073.  
  1074.     if comp[compKey]['name'] == 'Or2':
  1075.         cfile += '    float tempo1, tempo2;\n'
  1076.         cfile += '    Fifo_pop_data(data_structure->Fifo[0], &tempo1);\n'
  1077.         cfile += '    Fifo_pop_data(data_structure->Fifo[1], &tempo2);\n'
  1078.         cfile += '    Fifo_push_data(data_structure->Fifo[2],(tempo1 or tempo2));\n'
  1079.         cfile += '    return 1;\n'
  1080.  
  1081.     return cfile
  1082.  
  1083.  
  1084. def constantValuesXML(comp, tabgain, taboffs, item, ItemNb, doc, tabslope, tabconst, tabamp, tabfreq, tabphase,
  1085.                       tabpolarity, tabpulseWidth, tabUpRand, tabLowRand):
  1086.     # extract informations of the graph into the XML for others exports
  1087.  
  1088.     if (comp.className == 'Gain' or comp.className == 'Integ'):
  1089.         tabgain.append(doc.createElement('gain'))
  1090.         item[ItemNb].appendChild(tabgain[ItemNb])
  1091.         tabgain[ItemNb].appendChild(doc.createTextNode(str(comp.parameter['Gain'].value)))
  1092.     else:
  1093.         tabgain.append([])
  1094.  
  1095.     if (comp.className == 'Gain' or comp.className == 'GenPulse' or comp.className == 'GenRamp' or
  1096.                 comp.className == 'GenSine' or comp.className == 'GenCos'):
  1097.         taboffs.append(doc.createElement('offset'))
  1098.         item[ItemNb].appendChild(taboffs[ItemNb])
  1099.         taboffs[ItemNb].appendChild(doc.createTextNode(str(comp.parameter['Offset'].value)))
  1100.     else:
  1101.         taboffs.append([])
  1102.  
  1103.     if (comp.className == 'GenRamp'):
  1104.         tabslope.append(doc.createElement('slope'))
  1105.         item[ItemNb].appendChild(tabslope[ItemNb])
  1106.         tabslope[ItemNb].appendChild(doc.createTextNode(str(comp.parameter['Slope'].value)))
  1107.     else:
  1108.         tabslope.append([])
  1109.  
  1110.     if (comp.className == 'GenConst'):
  1111.         tabconst.append(doc.createElement('constant_value'))
  1112.         item[ItemNb].appendChild(tabconst[ItemNb])
  1113.         tabconst[ItemNb].appendChild(doc.createTextNode(str(comp.parameter['Value'].value)))
  1114.     elif comp.className == 'FuncEval' :
  1115.         tabconst.append(doc.createElement('constant_value'))
  1116.         item[ItemNb].appendChild(tabconst[ItemNb])
  1117.         tabconst[ItemNb].appendChild(doc.createTextNode(str(comp.parameter['f(x)'].value)))
  1118.     else:
  1119.         tabconst.append([])
  1120.  
  1121.     if (comp.className == 'GenSine' or comp.className == 'GenPulse' or comp.className == 'GenCos'):
  1122.         tabamp.append(doc.createElement('amplitude'))
  1123.         item[ItemNb].appendChild(tabamp[ItemNb])
  1124.         tabamp[ItemNb].appendChild(doc.createTextNode(str(comp.parameter['Amplitude'].value)))
  1125.  
  1126.         tabfreq.append(doc.createElement('frequency'))
  1127.         item[ItemNb].appendChild(tabfreq[ItemNb])
  1128.         tabfreq[ItemNb].appendChild(doc.createTextNode(str(comp.parameter['Frequency'].value)))
  1129.  
  1130.         tabphase.append(doc.createElement('phase'))
  1131.         item[ItemNb].appendChild(tabphase[ItemNb])
  1132.         tabphase[ItemNb].appendChild(doc.createTextNode(str(comp.parameter['Phase'].value)))
  1133.  
  1134.     else:
  1135.         tabamp.append([])
  1136.         tabfreq.append([])
  1137.         tabphase.append([])
  1138.  
  1139.  
  1140.     if (comp.className == 'GenPulse'):
  1141.         tabpolarity.append(doc.createElement('polarity'))
  1142.         item[ItemNb].appendChild(tabpolarity[ItemNb])
  1143.         tabpolarity[ItemNb].appendChild(doc.createTextNode(str(comp.parameter['Polarity'].value)))
  1144.  
  1145.         tabpulseWidth.append(doc.createElement('pulse_width'))
  1146.         item[ItemNb].appendChild(tabpulseWidth[ItemNb])
  1147.         tabpulseWidth[ItemNb].appendChild(doc.createTextNode(str(comp.parameter['Pulse Width'].value)))
  1148.     else:
  1149.         tabpolarity.append([])
  1150.         tabpulseWidth.append([])
  1151.  
  1152.     if (comp.className == 'GenRandInt'):
  1153.         tabUpRand.append(doc.createElement('upper_random'))
  1154.         item[ItemNb].appendChild(tabUpRand[ItemNb])
  1155.         tabUpRand[ItemNb].appendChild(doc.createTextNode(str(comp.parameter['Upper limit'].value)))
  1156.  
  1157.         tabLowRand.append(doc.createElement('lower_random'))
  1158.         item[ItemNb].appendChild(tabLowRand[ItemNb])
  1159.         tabLowRand[ItemNb].appendChild(doc.createTextNode(str(comp.parameter['Lower limit'].value)))
  1160.     else:
  1161.         tabLowRand.append([])
  1162.         tabUpRand.append([])
  1163.  
  1164.  
  1165. def convertXML(diagram):
  1166.     ItemNb = 0
  1167.     NetNb = 0
  1168.     ConstantNb = 0
  1169.  
  1170.     item = []
  1171.     name = []
  1172.     ref = []
  1173.     gainval = []
  1174.     offs = []
  1175.     slope = []
  1176.     constValue = []
  1177.     amp = []
  1178.     freq = []
  1179.     phase = []
  1180.     polarity = []
  1181.     pulseWidth = []
  1182.     upperRand = []
  1183.     lowerRand = []
  1184.  
  1185.  
  1186.     terminal = []  # terminal[Itemnb][TerminalNb]
  1187.     Ttype = []
  1188.     TDataType = []
  1189.  
  1190.     net = []
  1191.     netName = []
  1192.     netStart = []
  1193.     netEnd = []
  1194.     netDelay = []
  1195.     netSrcTerm = []
  1196.     netSnkTerm = []
  1197.     netNameCheck = []
  1198.     netActorSrc = []
  1199.     netActorSnk = []
  1200.  
  1201.     constant = []
  1202.     constantRef = []
  1203.     constantValue = []
  1204.  
  1205.     doc = minidom.Document()
  1206.     doc.appendChild(doc.createComment("Diagram to XML Exporter"))
  1207.  
  1208.     root = doc.createElement('root')
  1209.     doc.appendChild(root)
  1210.  
  1211.     for Component in diagram.diagram.componentList:
  1212.  
  1213.         if Component.className != 'Constant':
  1214.             item.append(doc.createElement('component'))
  1215.             root.appendChild(item[ItemNb])
  1216.  
  1217.             name.append(doc.createElement('name'))
  1218.             item[ItemNb].appendChild(name[ItemNb])
  1219.             name[ItemNb].appendChild(doc.createTextNode(Component.className))
  1220.  
  1221.             ref.append(doc.createElement('ref'))
  1222.             item[ItemNb].appendChild(ref[ItemNb])
  1223.             ref[ItemNb].appendChild(doc.createTextNode(Component.parameter['Ref'].value))
  1224.  
  1225.             constantValuesXML(Component, gainval, offs, item, ItemNb, doc, slope, constValue, amp, freq, phase,
  1226.                              polarity, pulseWidth, upperRand, lowerRand)
  1227.  
  1228.             TerminalNb = 0
  1229.             terminal.append([])
  1230.             Ttype.append([])
  1231.             TDataType.append([])
  1232.  
  1233.             for key in Component.terminal.keys():
  1234.                 terminal[ItemNb].append(doc.createElement('terminal'))
  1235.                 item[ItemNb].appendChild(terminal[ItemNb][TerminalNb])
  1236.  
  1237.                 Ttype[ItemNb].append(doc.createElement('type'))
  1238.                 terminal[ItemNb][TerminalNb].appendChild(Ttype[ItemNb][TerminalNb])
  1239.  
  1240.                 if Component.terminal[key].termType == 1:
  1241.                     Ttype[ItemNb][TerminalNb].appendChild(doc.createTextNode('CONN'))
  1242.  
  1243.                 elif Component.terminal[key].termType == 2:
  1244.                     Ttype[ItemNb][TerminalNb].appendChild(doc.createTextNode('IN'))
  1245.  
  1246.                 elif Component.terminal[key].termType == 4:
  1247.                     Ttype[ItemNb][TerminalNb].appendChild(doc.createTextNode('OUT'))
  1248.  
  1249.                 elif Component.terminal[key].termType == 8:
  1250.                     Ttype[ItemNb][TerminalNb].appendChild(doc.createTextNode('INOUT'))
  1251.  
  1252.                 TDataType[ItemNb].append(doc.createElement('data_type'))
  1253.                 terminal[ItemNb][TerminalNb].appendChild(TDataType[ItemNb][TerminalNb])
  1254.                 if str(type(Component.terminal[key].value)) == "<class 'float'>":
  1255.                     TDataType[ItemNb][TerminalNb].appendChild(doc.createTextNode('float'))
  1256.                 TerminalNb += 1
  1257.  
  1258.             ItemNb += 1
  1259.  
  1260.     for Component in diagram.diagram.componentList:
  1261.  
  1262.         if Component.className == 'Constant':
  1263.             constant.append(doc.createElement('constant'))
  1264.             root.appendChild(constant[ConstantNb])
  1265.  
  1266.             constantRef.append(doc.createElement('name'))
  1267.             constant[ConstantNb].appendChild(constantRef[ConstantNb])
  1268.             constantRef[ConstantNb].appendChild(doc.createTextNode(Component.parameter['Ref'].value))
  1269.  
  1270.             for key in Component.terminal.keys():
  1271.                 constantValue.append(doc.createElement('value'))
  1272.                 constant[ConstantNb].appendChild(constantValue[ConstantNb])
  1273.                 constantValue[ConstantNb].appendChild(doc.createTextNode(str(Component.terminal[key].value)))
  1274.  
  1275.             ConstantNb += 1
  1276.  
  1277.     if diagram.simEngine is None:
  1278.         diagram.simEngine = Action(diagram.diagram)
  1279.  
  1280.     netInfos = diagram.simEngine.checkNetwork()
  1281.  
  1282.     for key in netInfos.keys():
  1283.  
  1284.         if key not in netNameCheck:
  1285.             netNameCheck.append(key)
  1286.  
  1287.             net.append(doc.createElement('edge'))
  1288.             root.appendChild(net[NetNb])
  1289.  
  1290.             netName.append(doc.createElement('name'))
  1291.             net[NetNb].appendChild(netName[NetNb])
  1292.             netName[NetNb].appendChild(doc.createTextNode(key))
  1293.  
  1294.             netDelay.append(doc.createElement('delay'))
  1295.             net[NetNb].appendChild(netDelay[NetNb])
  1296.             netDelay[NetNb].appendChild(doc.createTextNode(str(netInfos[key][4])))
  1297.  
  1298.             netStart.append(doc.createElement('source'))
  1299.             net[NetNb].appendChild(netStart[NetNb])
  1300.  
  1301.             netActorSrc.append(doc.createElement('actor'))
  1302.             netStart[NetNb].appendChild(netActorSrc[NetNb])
  1303.             netActorSrc[NetNb].appendChild(doc.createTextNode(netInfos[key][0]))
  1304.  
  1305.             netSrcTerm.append(doc.createElement('port'))
  1306.             netStart[NetNb].appendChild(netSrcTerm[NetNb])
  1307.             netSrcTerm[NetNb].appendChild(doc.createTextNode(str(netInfos[key][1])))
  1308.  
  1309.             netEnd.append(doc.createElement('dest'))
  1310.             net[NetNb].appendChild(netEnd[NetNb])
  1311.  
  1312.             netActorSnk.append(doc.createElement('actor'))
  1313.             netEnd[NetNb].appendChild(netActorSnk[NetNb])
  1314.             netActorSnk[NetNb].appendChild(doc.createTextNode(netInfos[key][2]))
  1315.  
  1316.             netSnkTerm.append(doc.createElement('port'))
  1317.             netEnd[NetNb].appendChild(netSnkTerm[NetNb])
  1318.             netSnkTerm[NetNb].appendChild(doc.createTextNode(str(netInfos[key][3])))
  1319.  
  1320.             NetNb += 1
  1321.  
  1322.     xml_file = doc.toprettyxml(indent='   ')
  1323.     return xml_file
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement