Ejemplo n.º 1
0
def makeJS(filename):
    """
	"""

    from Container import Diagram
    from Join import makeDEVSConf, makeJoin

    a = Diagram()
    if a.LoadFile(filename):
        sys.stdout.write(_("\nFile loaded\n"))
        #		master = Diagram.makeDEVSInstance(a)

        addInner = []
        liaison = []
        model = {}
        labelEnCours = str(os.path.basename(a.last_name_saved).split('.')[0])

        # path = os.path.join(os.getcwd(),os.path.basename(a.last_name_saved).split('.')[0] + ".js") # genere le fichier js dans le dossier de devsimpy
        # path = filename.split('.')[0] + ".js" # genere le fichier js dans le dossier du dsp charg�.

        #Position initial du 1er modele
        x = [40]
        y = [40]
        bool = True

        model, liaison, addInner = makeJoin(a, addInner, liaison, model, bool,
                                            x, y, labelEnCours)
        makeDEVSConf(model, liaison, addInner, "%s.js" % labelEnCours)
    else:
        return False
Ejemplo n.º 2
0
    def __init__ (self, filename):
        """
        """
        from Container import Diagram

        self.filename = filename
        self.modelname = os.path.basename(self.filename)

        self.report   = {'model_name' : self.modelname}

        self.json_obj = None

        # Create diagram object
        self.diagram  = Diagram()
        try :
            self.filename_is_valid = self.diagram.LoadFile(self.filename)
            if self.filename_is_valid != True :
                self.report['success'] = False
                self.report['info'] = 'YAML file load failed'
                print(json.dumps(self.report))
        except:
            self.report['success'] = False
            self.report['info'] = traceback.format_exc()
            print(json.dumps(self.report))
            raise
Ejemplo n.º 3
0
    def Load(filename, label, canvas):
        """ Load component from filename
		"""
        from Container import Diagram
        #assert(filename.endswith('.dsp'))

        # its possible to use the original copy of the droped diagram
        dial = wx.MessageDialog(
            canvas,
            _('Do you want to open the original diagram in a new tab?'), label,
            wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)

        new_tab = dial.ShowModal() == wx.ID_YES

        # load diagram in a new page
        if new_tab:
            diagram = Diagram()
        else:
            diagram = canvas.GetDiagram()

        ### if diagram is instanciated
        if diagram:
            load_file_result = diagram.LoadFile(filename)

            ### if diagram is loaded
            if not isinstance(load_file_result, Exception):

                mainW = canvas.GetTopLevelParent()
                nb2 = mainW.GetDiagramNotebook()

                ### if new tab
                if new_tab:
                    nb2.AddEditPage(label, diagram)
                else:
                    selection = nb2.GetSelection()
                    nb2.SetPageText(selection, label)

                # Add as new recent file
                if filename not in mainW.openFileList:
                    mainW.openFileList.insert(0, filename)
                    del mainW.openFileList[-1]
                    mainW.cfg.Write("openFileList",
                                    str(eval("mainW.openFileList")))
                    mainW.cfg.Flush()

                return True
            else:
                info = _(
                    'Error opening file \n file : %s \n object : %s \n error : %s '
                ) % (filename, load_file_result[1], load_file_result[0])
                wx.MessageBox(info, _('Error'), wx.OK | wx.ICON_ERROR)
                return False
Ejemplo n.º 4
0
def getYAMLModels(filename):
    from Container import Diagram, Block

    ### load diagram from yaml and update args
    dia = Diagram()

    if dia.LoadFile(filename):
        shape_list = dia.GetShapeList()
        block_list = filter(lambda c: isinstance(c, Block), shape_list)

        ### write new yaml file
        print dict(map(lambda a: (str(a.id), str(a.label)), block_list))

        return True

    else:
        return False
Ejemplo n.º 5
0
def makeYAMLUpdate(json_str):
    import json
    from Container import Diagram

    ### data = "{ 'a':'A', 'b':(2, 4), 'c':3.0 }"
    ### data_string = json.dumps(json_str)

    obj = eval(json.loads(repr(json_str)))

    ### new args
    new_args = obj['args']
    label = obj['model']
    filename = obj['filename']

    ### load diagram from yaml and update args
    a = Diagram()

    if a.LoadFile(filename):
        model = a.GetShapeByLabel(label)
        #print "avant", model.args, new_args
        for arg in model.args:
            new_val = new_args[arg]
            old_val = model.args[arg]
            if old_val != new_val:
                ### adapt types for python code (float, int and bool)
                if new_val in ('true', 'True'):
                    new_val = True
                elif new_val in ('false', 'False'):
                    new_val = False
                elif new_val.replace('.', '').replace('-', '').isdigit():
                    new_val = eval(new_val)

                model.args[arg] = new_val


#		print "apres", model.args

### write new yaml file
        return a.SaveFile(a.last_name_saved)

    else:
        return False
Ejemplo n.º 6
0
def makeSimulation(filename, T, json_trace=False):
    """
	"""

    from Container import Diagram

    if not json_trace:
        sys.stdout.write(
            _("\nSimulation in batch mode with %s\n") %
            __builtin__.__dict__['DEFAULT_DEVS_DIRNAME'])

    a = Diagram()

    if not json_trace:
        sys.stdout.write(
            _("\nLoading %s file...\n") % (os.path.basename(filename)))
    else:
        json = {'date': time.strftime("%c")}
    json['mode'] = 'no-gui'

    if a.LoadFile(filename):

        if not json_trace:
            sys.stdout.write(_("%s loaded!\n") % (os.path.basename(filename)))
        else:
            json['file'] = filename

        try:
            if not json_trace:
                sys.stdout.write(_("\nMaking DEVS instance...\n"))
            master = Diagram.makeDEVSInstance(a)
        except:
            if not json_trace:
                return False
            else:
                json['devs_instance'] = None
                json['success'] = False
                sys.stdout.write(str(json))
        else:
            if not json_trace:
                sys.stdout.write(_("DEVS instance created!\n"))
            else:
                json['devs_instance'] = str(master)

            if not json_trace:
                sys.stdout.write(_("\nPerforming DEVS simulation...\n"))

            sim = runSimulation(master, T)
            thread = sim.Run()

            first_time = time.time()
            while (thread.isAlive()):
                new_time = time.time()
                output = new_time - first_time
                if not json_trace: Printer(output)

            if not json_trace:
                sys.stdout.write(_("\nDEVS simulation completed!\n"))

        if json_trace:
            json['time'] = output
            json['output'] = []

        ### inform that data file has been generated
        for m in filter(lambda a: hasattr(a, 'fileName'), master.componentSet):
            for i in range(len(m.IPorts)):
                fn = '%s%s.dat' % (m.fileName, str(i))
                if os.path.exists(fn):
                    if not json_trace:
                        sys.stdout.write(
                            _("\nData file %s has been generated!\n") % (fn))
                    else:
                        json['output'].append({
                            'name': os.path.basename(fn),
                            'path': fn
                        })
    else:
        if json_trace:
            json['file'] = None
        json['success'] = True
        sys.stdout.write(str(json))
Ejemplo n.º 7
0
def makeJSON(filename, json=None, diagram=None):
    """ Make JSON file from D graph of the diagram
	"""
    from Container import Diagram, ConnectionShape, CodeBlock, ContainerBlock, iPort, oPort

    if not json:
        ### add filename in json
        json = {
            os.path.basename(filename): [{
                "cells": []
            }, {
                "description": ""
            }]
        }
    else:
        json = json

    if not diagram:
        dia = Diagram()

        if not dia.LoadFile(filename):
            json['success'] = False
            return json
    else:
        dia = diagram

    for c in dia.GetShapeList():

        ### if c is coupled model
        if isinstance(c, ContainerBlock):
            D = {
                "type": "devs.Coupled",
                "angle": 0,
                "id": c.label,
                "z": 1,
                "size": {
                    "width": c.w,
                    "height": c.h
                },
                "position": {
                    "x": c.x[0],
                    "y": c.y[0]
                },
                "inPorts": map(lambda i: "in%d" % i, range(c.input)),
                "outPorts": map(lambda i: "out%d" % i, range(c.output)),
                "attrs": {
                    "text": {
                        "text": c.label
                    }
                }
            }

            ### embeds key
            shapes = c.GetFlatBlockShapeList()
            D["embeds"] = [s.label for s in shapes]

            json[os.path.basename(filename)][0]['cells'].append(D)

            return makeJSON(filename, json, c)

        ### if c is connexion
        else:
            if isinstance(c, ConnectionShape):
                D = {
                    "type": "devs.Link",
                    "id": str(id(c)),
                    "z": 0,
                    "attrs": {},
                    'source': {
                        "selector": ".outPorts>g:nth-child(1)>circle"
                    },
                    'target': {
                        "selector": ".inPorts>g:nth-child(1)>circle"
                    }
                }
                model1, portNumber1 = c.input
                model2, portNumber2 = c.output

                D['source']['id'] = model1.label.encode("utf-8")
                D['target']['id'] = model2.label.encode("utf-8")

            ### if c is atomic model
            elif isinstance(c, CodeBlock):

                D = {
                    "type": "devs.Atomic",
                    "angle": 0,
                    "id": c.label,
                    "z": 1,
                    "size": {
                        "width": c.w,
                        "height": c.h
                    },
                    "position": {
                        "x": c.x[0],
                        "y": c.y[0]
                    },
                    "inPorts": map(lambda i: "in%d" % i, range(c.input)),
                    "outPorts": map(lambda i: "out%d" % i, range(c.output)),
                    "attrs": {
                        "text": {
                            "text": c.label
                        }
                    },
                    "prop": {
                        "data": c.args
                    }
                }

                for i in xrange(c.input):
                    D["attrs"].update({
                        ".inPorts>.port%d>.port-label" % i: {
                            "text": "in%d" % i
                        },
                        ".inPorts>.port%d>.port-body" % i: {
                            "port": {
                                "id": "in%d" % i,
                                "type": "in"
                            }
                        },
                        ".inPorts>.port%d" % i: {
                            "ref": ".body",
                            "ref-y": float(i + 1) / (c.input + 1)
                        }
                    })
                for j in xrange(c.output):
                    D["attrs"].update({
                        ".outPorts>.port%d>.port-label" % j: {
                            "text": "out%d" % j
                        },
                        ".outPorts>.port%d>.port-body" % j: {
                            "port": {
                                "id": "out%d" % j,
                                "type": "out"
                            }
                        },
                        ".outPorts>.port%d" % j: {
                            "ref": ".body",
                            "ref-y": float(j + 1) / (c.output + 1)
                        }
                    })

            json[os.path.basename(filename)][0]['cells'].append(D)

    return json