Esempio 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
Esempio 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
Esempio 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
Esempio 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
Esempio 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
Esempio n. 6
0
    def getDevsInstance(self):
        """ Returns the DEVS instance built from YAML file
        """
        from Container import Diagram

        if self.filename_is_valid != True: return False

        try :
            return Diagram.makeDEVSInstance(self.diagram)
        except:
            self.report['devs_instance'] = None
            self.report['success'] = False
            self.report['info'] = traceback.format_exc()
            print(json.dumps(self.report))
            return False
Esempio n. 7
0
class YAMLHandler:
    """ class providing methods for YAML file handling
    """
    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


    def getYAMLBlockModelsList(self):
        """ Writes to standard output
            the labels of the blocks (= Atomic Models)
            composing the model described in the file
        """

        if self.filename_is_valid != True: return False

        block_list = self.diagram.GetFlatCodeBlockShapeList()
        return map(lambda a: str(a.label), block_list)


    def getYAMLBlockModelArgs(self, label):
        """ Returns the parameters (name and value) of the block identified by the label
            composing the model described in the file
        """

        if self.filename_is_valid != True: return False

        block = self.diagram.GetShapeByLabel(label)
        return block.args


    def setYAMLBlockModelArgs(self, label, new_args):
        """ Saves in YAML file the new values of the parameters
            of the block identified by the label
            Returns the updated block parameters
        """

        if self.filename_is_valid != True: return False

        block = self.diagram.GetShapeByLabel(label)

        for arg in block.args:
            block.args[arg] = to_Python(new_args[arg])

        success = self.diagram.SaveFile(self.diagram.last_name_saved)

        return {'success' : success, 'args' : self.getYAMLBlockModelArgs(label)}

    def getJSON(self, diagram=None):
        """ Make JSON representation of the model from YAML file
        """
        from Container import ConnectionShape, CodeBlock, ContainerBlock

        if self.filename_is_valid != True: return False

        # Initialize JSON object if it does not exist (makeJSON is called recursively)
        if not diagram:
            self.json_obj = {"cells":[],"description": "No description"}
            diagram = self.diagram
        
        for c in diagram.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]

                self.json_obj['cells'].append(D)

                # add JSON description of coupled model components
                self.getJSON(c)

            else:
                ### if c is a connection
                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 an 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)}
                                                                   })

                else: #Input or Output port
                    D = None
                    
                if (D!= None):
                     self.json_obj['cells'].append(D)

        return self.json_obj


    def getDevsInstance(self):
        """ Returns the DEVS instance built from YAML file
        """
        from Container import Diagram

        if self.filename_is_valid != True: return False

        try :
            return Diagram.makeDEVSInstance(self.diagram)
        except:
            self.report['devs_instance'] = None
            self.report['success'] = False
            self.report['info'] = traceback.format_exc()
            print(json.dumps(self.report))
            return False

    def getJS(self):
        """
        """

        from Join import makeDEVSConf, makeJoin

        if self.filename_is_valid != True : return False

        addInner = []
        liaison = []
        model = {}
        labelEnCours = str(os.path.basename(self.diagram.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 charge.

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

        model, liaison, addInner = makeJoin(self.diagram, addInner, liaison, model, bool, x, y, labelEnCours)
        makeDEVSConf(model, liaison, addInner, "%s.js"%labelEnCours)
Esempio n. 8
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))
	def __set_properties(self):
		# begin wxGlade: ActivityReport.__set_properties

		self.SetTitle(self._title)

		data = []

		### get user configuration ofr static or dynamic execution
		diagram = self.parent.master.getBlockModel()

		if hasattr(diagram, 'activity_flags'):
			self.static_user_flag, self.dynamic_user_flag = diagram.activity_flags
		else:
			self.static_user_flag = self.dynamic_user_flag = True

		### after simulation, we can display the static and dynamic activity informations
		if self._master and self.dynamic_user_flag:

			L = GetFlatDEVSList(self._master, [])

			### if model have texec attribute, then its selected in the properties panel
			model_list = filter(lambda a: hasattr(a, 'texec'), L)

			### if at least one model has been selected in Activity configuration dialogue
			if len(model_list) != 0:

				d = ActivityData(model_list)

				### A=(Aint+Aext)/H
				H=self._master.timeLast if self._master.timeLast <= self._master.FINAL_TIME else self._master.FINAL_TIME

				Ddata, DrowLabels, DcolLabels = d.getDynamicData(H)

				if self.static_user_flag:
					Sdata, SrowLabels, ScolLabels = d.getStaticData()

					### update data ([1:] to delete the label of the model in case of dynamic data with static data)
					ScolLabels.extend(DcolLabels[1:])

					for i in range(len(Sdata)):
						### ([1:] to delete the label of the model in case of dynamic data with static data)
						Sdata[i].extend(Ddata[i][1:])

					###
					data = Sdata
					colLabels = ScolLabels
				else:
					data = Ddata
					colLabels = DcolLabels

				rowLabels = map(lambda a: str(a), range(len(map(lambda b: b[0], data))))

				d.EndProgressBar()

			### no models are selected from activity plug-in properties panel
			else:
				self.ReportGrid.Show(False)
				wx.MessageBox(_('Please select at least one model in activity configuration panel.'), _('Info'), wx.OK|wx.ICON_INFORMATION)

		### static data
		elif self.static_user_flag:

			### get DEVS model form diagram
			diagram.Clean()
			self._master = Diagram.makeDEVSInstance(diagram)

			### for static infrmations, all model are considered
			L = GetFlatDEVSList(self._master, [])

			model_list = filter(lambda a: hasattr(a.getBlockModel(), 'activity'), L)

			if len(model_list) != 0:
				d = ActivityData(model_list)
				data, rowLabels, colLabels = d.getStaticData()
				d.EndProgressBar()
			else:
				self.ReportGrid.Show(False)
				wx.MessageBox(_('Please select at least one model in activity configuration panel.'), _('Info'), wx.OK|wx.ICON_INFORMATION)

		### populate the grid from data
		if len(data) != 0:

			tableBase = GenericTable(data, rowLabels, colLabels)

			self.ReportGrid.CreateGrid(10, len(colLabels))
			for i in range(len(colLabels)):
				self.ReportGrid.SetColLabelValue(i, colLabels[i])

			self.ReportGrid.SetTable(tableBase)
			self.ReportGrid.EnableEditing(0)
			self.ReportGrid.SetColLabelSize(60)
			self.ReportGrid.SetLabelTextColour('#0000ff') # Blue
			self.ReportGrid.AutoSize()
Esempio n. 10
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
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))