Exemplo n.º 1
0
    def populate_grid_by_model_object(self):
        if not isinstance(self.model_object, ModelBox):
            sPrint("ModelDetails.model_object needs to by type ModelBox")
            return

        model_as_json = engineAccessors.getModelById(self.model_object.ID)

        if not isinstance(model_as_json, dict):
            sPrint("ModelDetailsCtrl.populate_grid_by_model_object.model_as_json needs to be type dictionary")
            return

        if "params" in model_as_json:
            if "path" in model_as_json["params"]:
                self._data = models.parse_json(model_as_json["params"]["path"])
                self.grid.add_data(self._data)
                return

        elif "attrib" in model_as_json:
            if "mdl" in model_as_json["attrib"]:
                self._data = models.parse_json(model_as_json["attrib"]["mdl"])
                self.grid.add_data(self._data)
                return

        self.grid.add_section("General")
        for key, value in model_as_json.iteritems():
            if isinstance(value, dict):
                self.grid.add_dictionary(value, key)
            else:
                self.grid.add_data_to_section(0, key, value)
        return
Exemplo n.º 2
0
    def populate_grid_by_model_object(self):
        if not isinstance(self.model_object, ModelBox):
            sPrint("ModelDetails.model_object needs to by type ModelBox")
            return

        model_as_json = engineAccessors.getModelById(self.model_object.ID)

        if not isinstance(model_as_json, dict):
            sPrint(
                "ModelDetailsCtrl.populate_grid_by_model_object.model_as_json needs to be type dictionary"
            )
            return

        if "params" in model_as_json:
            if "path" in model_as_json["params"]:
                self._data = models.parse_json(model_as_json["params"]["path"])
                self.grid.add_data(self._data)
                return

        elif "attrib" in model_as_json:
            if "mdl" in model_as_json["attrib"]:
                self._data = models.parse_json(model_as_json["attrib"]["mdl"])
                self.grid.add_data(self._data)
                return

        self.grid.add_section("General")
        for key, value in model_as_json.iteritems():
            if isinstance(value, dict):
                self.grid.add_dictionary(value, key)
            else:
                self.grid.add_data_to_section(0, key, value)
        return
Exemplo n.º 3
0
    def test_basic_conversion(self):

        # add models to engine
        mdl1 = '../../app_data/models/randomizer/randomizer.mdl'
        params = parse_json(mdl1)
        params.update({'id': 'm1', 'mdl': mdl1, 'model_type': 'mdl'})
        m1 = self.engine.add_model(**params)

        mdl2 = '../../app_data/models/multiplier/multiplier.mdl'
        params = parse_json(mdl2)
        params.update({'id': 'm2', 'mdl': mdl2, 'model_type': 'mdl'})
        m2 = self.engine.add_model(**params)

        self.assertTrue(m1)
        self.assertTrue(m2)
        self.assertTrue(len(self.engine.Models()) == 2)

        mi1 = m1.instance()
        mi2 = m2.instance()

        # run the model mi1
        mi1.run(inputs={})

        # get the oei and iei that will be mapped
        oei = mi1.outputs()['random POINT 1-10']
        outvals = numpy.array(oei.getValues2())
        iei = mi2.inputs()['some_value']


        converted_vals = units.convert_units(oei=oei, iei=iei, vals=outvals)


        print  'done'
Exemplo n.º 4
0
    def load_simulation(self, simfile):

        params = model_utils.parse_json(simfile)

        models = params['models'] if 'models' in params else []
        links = params['links'] if 'links' in params else []
        datamodels = params['datamodels'] if 'datamodels' in params else []

        self.failed_models = 0
        total = len(models) + len(datamodels) + len(
            self.models) + self.failed_models

        # start thread that will load links when once all models have been loaded
        waitingThread = threading.Thread(target=self.wait_for_model_loading,
                                         args=(total, links),
                                         name="load_links")
        self.logicCanvasThreads[waitingThread.name] = waitingThread
        waitingThread.start()

        # loop through all of the models and load each one individually
        for model in models:
            if self.is_model_netcdf(model):
                self.add_netcdf_model(model["params"]["ncpath"],
                                      model["params"]["tdim"],
                                      model["params"]["xdim"],
                                      model["params"]["ydim"],
                                      model["params"]["tunit"],
                                      model["params"]["starttime"])
                continue

            mdl = model['path']
            args = model_utils.parse_json(mdl)
            inputs = model.pop('model_inputs')
            args.update(model)
            args.update(inputs)

            # save these coordinates for drawing once the model is loaded
            self.set_model_coordinate(model['id'],
                                      x=float(model['xcoordinate']),
                                      y=float(model['ycoordinate']))

            # load the model in the engine
            engine.addModel(**args)

            # draw the model
            wx.CallAfter(self.FloatCanvas.Draw)
Exemplo n.º 5
0
    def populate_grid_by_path(self):
        if not os.path.exists(self.data_path):
            sPrint("ModelDetailsCtrl.data_path does not exist or has not been set")
            return

        self._data = models.parse_json(self.data_path)

        if self.data_path[-4:] == ".sim":
            self._load_simulation()
        else:
            self.grid.add_data(self._data)
Exemplo n.º 6
0
    def load_json_file(self, cat, fullpath):
        data = models.parse_json(fullpath)
        txt = data["general"][0]["name"]

        child = self.tree.AppendItem(cat, txt)
        self.filepath[txt] = fullpath
        self.items[child] = fullpath

        child.__setattr__("path", fullpath)
        self.tree.SetItemImage(child, self.modelicon, which=wx.TreeItemIcon_Expanded)
        self.tree.SetItemImage(child, self.modelicon, which=wx.TreeItemIcon_Normal)
Exemplo n.º 7
0
    def populate_grid_by_path(self):
        if not os.path.exists(self.data_path):
            sPrint(
                "ModelDetailsCtrl.data_path does not exist or has not been set"
            )
            return

        self._data = models.parse_json(self.data_path)

        if self.data_path[-4:] == ".sim":
            self._load_simulation()
        else:
            self.grid.add_data(self._data)
Exemplo n.º 8
0
    def load_simulation(self, simfile):

        params = model_utils.parse_json(simfile)

        models = params['models'] if 'models' in params else []
        links = params['links'] if 'links' in params else []
        datamodels = params['datamodels'] if 'datamodels' in params else []

        self.failed_models = 0
        total = len(models) + len(datamodels) + len(self.models) + self.failed_models

        # start thread that will load links when once all models have been loaded
        waitingThread = threading.Thread(target=self.wait_for_model_loading, args=(total, links), name="load_links")
        self.logicCanvasThreads[waitingThread.name] = waitingThread
        waitingThread.start()

        # loop through all of the models and load each one individually
        for model in models:
            if self.is_model_netcdf(model):
                self.add_netcdf_model(model["params"]["ncpath"], model["params"]["tdim"],
                                      model["params"]["xdim"], model["params"]["ydim"],
                                      model["params"]["tunit"], model["params"]["starttime"])
                continue

            mdl = model['path']
            args = model_utils.parse_json(mdl)
            inputs = model.pop('model_inputs')
            args.update(model)
            args.update(inputs)

            # save these coordinates for drawing once the model is loaded
            self.set_model_coordinate(model['id'], x=float(model['xcoordinate']), y=float(model['ycoordinate']))

            # load the model in the engine
            engine.addModel(**args)

            # draw the model
            wx.CallAfter(self.FloatCanvas.Draw)
Exemplo n.º 9
0
    def load_json_file(self, cat, fullpath):
        data = models.parse_json(fullpath)
        txt = data["general"][0]["name"]

        child = self.tree.AppendItem(cat, txt)
        self.filepath[txt] = fullpath
        self.items[child] = fullpath

        child.__setattr__("path", fullpath)
        self.tree.SetItemImage(child,
                               self.modelicon,
                               which=wx.TreeItemIcon_Expanded)
        self.tree.SetItemImage(child,
                               self.modelicon,
                               which=wx.TreeItemIcon_Normal)
Exemplo n.º 10
0
    def __init__(self, parent, path):
        wx.Frame.__init__(self, parent, style=wx.DEFAULT_FRAME_STYLE | wx.FRAME_FLOAT_ON_PARENT)

        # Create panels
        panel = wx.Panel(self)
        scroll_panel = wx.lib.scrolledpanel.ScrolledPanel(panel)
        scroll_panel.SetupScrolling(scroll_x=False)  # Disable scrolling horizontally
        bottom_panel = wx.Panel(panel)

        self.params = models.parse_json(path)
        self.params.update({'path':path,
                            'model_type':path[-3:]})

        self.valid_params = 1
        self.has_inputs = 1 if 'model_inputs' in self.params else 0

        # if a sim file is being loaded return, else proceed
        if not self.has_inputs:
            return
        if self.params['model_type'] == 'sim':
            return
        elif self.params['model_type'] == 'mdl':
            if not models.validate_json_model(self.params):
                sPrint('Encountered and error when validating parameters: %s' %path)
                self.valid_params = 0  # set the param validation as False
                return

        # validate the model inputs fields
        model_inputs = self.params["model_inputs"]
        required_inputs = ['name', 'help', 'input', 'variable', 'required']
        for item in model_inputs:
            for req in required_inputs:
                if req not in item.keys():
                    sPrint('Cannot load model. Missing required parameter in '
                           '"model inputs" section of mdl: {%s}' % req,
                           MessageType.ERROR)
                    self.valid_params = 0 # set the param validation as False
                    return

        title = "Input for " + self.params["model"][0]["code"]
        self.SetTitle(title)

        count = 0  # Keeps track of how many input items there are
        self.static_texts = []
        self.text_ctrls = []
        self.help_texts = []
        self.inputs = []
        self.variable_names = []
        self.variable_types = []
        self.required = []

        # Add components dynamically
        for item in model_inputs:
            static_text = wx.StaticText(scroll_panel, id=count, label=item["name"] + ":")
            help_text = wx.StaticText(scroll_panel, id=count, label=item["help"])
            text_ctrl = wx.TextCtrl(scroll_panel, id=count)

            file_explorer_button = None
            if item["input"] == "file":
                file_explorer_button = wx.Button(scroll_panel, id=count, label="Browse", style=wx.BU_EXACTFIT)

            font = wx.Font(pointSize=8, family=wx.DEFAULT, style=wx.NORMAL, weight=wx.NORMAL)
            help_text.SetFont(font)

            # set default values
            if 'default' in item:
                text_ctrl.Value = str(item['default'])

            # save variable types
            if 'datatype' in item:
                self.variable_types.append(item['datatype'])
            else:
                self.variable_types.append('str')

            # Keep track of all the components in the lists
            self.static_texts.append(static_text)
            self.text_ctrls.append(text_ctrl)
            self.inputs.append(file_explorer_button)
            self.help_texts.append(help_text)
            self.variable_names.append(item['variable'])
            self.required.append(bool(item['required']) if 'required' in item else False)
            count += 1

        break_line = wx.StaticLine(panel)
        self.cancel_button = wx.Button(bottom_panel, label="Cancel", style=wx.BU_EXACTFIT)
        self.submit_button = wx.Button(bottom_panel, label="Load Model", style=wx.BU_EXACTFIT)

        # Create sizers
        frame_sizer = wx.BoxSizer(wx.VERTICAL)
        scroll_panel_sizer = wx.BoxSizer(wx.VERTICAL)
        flex_grid_sizer = wx.FlexGridSizer(rows=count * 3, cols=1, vgap=1, hgap=5)

        button_sizer = wx.BoxSizer(wx.HORIZONTAL)

        # Add components to sizer
        for i in range(count):
            # Used to act as if there were two columns. Allows the text ctrl to overflow into the second column
            sizer = wx.BoxSizer(wx.HORIZONTAL)
            word_wrap_sizer = wx.BoxSizer(wx.HORIZONTAL)  # For wrapping the help text

            flex_grid_sizer.Add(self.static_texts[i])

            sizer.Add(self.text_ctrls[i], 1, wx.EXPAND)
            if self.inputs[i]:
                sizer.Add(self.inputs[i], 0, wx.EXPAND)

            flex_grid_sizer.Add(sizer, 1, wx.EXPAND)
            word_wrap_sizer.Add(self.help_texts[i], 1, wx.EXPAND)
            flex_grid_sizer.Add(word_wrap_sizer, 1, wx.EXPAND | wx.BOTTOM, 15)
            flex_grid_sizer.AddGrowableRow(((i + 1) * 3) - 1, 1)

        flex_grid_sizer.AddGrowableCol(0, 1)  # Set the first column to expand and fill space

        # Adding the flex grid sizer to scroll panel sizer to give margin to the side of the scroll bar
        scroll_panel_sizer.Add(flex_grid_sizer, 1, wx.ALL | wx.EXPAND, 20)
        scroll_panel.SetSizer(scroll_panel_sizer)
        scroll_panel_sizer.Fit(scroll_panel)

        ###################################
        # ADD HELP IF MARKDOWN HELP EXIST
        ###################################
        if "help_markdown" in self.params:
            self.help_button = wx.Button(bottom_panel, label="Help", style=wx.BU_EXACTFIT)
            button_sizer.Add(self.help_button, 0, wx.ALL | wx.ALIGN_LEFT, 5)

        button_sizer.AddSpacer((0, 0), 1, wx.EXPAND, 5)
        button_sizer.Add(self.cancel_button, 0, wx.ALL | wx.ALIGN_RIGHT, 5)
        button_sizer.Add(self.submit_button, 0, wx.EXPAND | wx.ALL, 5)
        bottom_panel.SetSizer(button_sizer)

        frame_sizer.Add(scroll_panel, proportion=1, flag=wx.LEFT | wx.EXPAND, border=-10)
        frame_sizer.Add(break_line, 0, wx.EXPAND, 5)
        frame_sizer.Add(bottom_panel, 0, wx.ALL | wx.EXPAND, 3)

        panel.SetSizer(frame_sizer)
        frame_sizer.Fit(self)
        self.SetSize((-1, 400))

        self.Show()
Exemplo n.º 11
0
    def __init__(self, parent, path):
        wx.Frame.__init__(self,
                          parent,
                          style=wx.DEFAULT_FRAME_STYLE
                          | wx.FRAME_FLOAT_ON_PARENT)

        # Create panels
        panel = wx.Panel(self)
        scroll_panel = wx.lib.scrolledpanel.ScrolledPanel(panel)
        scroll_panel.SetupScrolling(
            scroll_x=False)  # Disable scrolling horizontally
        bottom_panel = wx.Panel(panel)

        self.params = models.parse_json(path)
        self.params.update({'path': path, 'model_type': path[-3:]})

        self.valid_params = 1
        self.has_inputs = 1 if 'model_inputs' in self.params else 0

        # if a sim file is being loaded return, else proceed
        if not self.has_inputs:
            return
        if self.params['model_type'] == 'sim':
            return
        elif self.params['model_type'] == 'mdl':
            if not models.validate_json_model(self.params):
                sPrint('Encountered and error when validating parameters: %s' %
                       path)
                self.valid_params = 0  # set the param validation as False
                return

        # validate the model inputs fields
        model_inputs = self.params["model_inputs"]
        required_inputs = ['name', 'help', 'input', 'variable', 'required']
        for item in model_inputs:
            for req in required_inputs:
                if req not in item.keys():
                    sPrint(
                        'Cannot load model. Missing required parameter in '
                        '"model inputs" section of mdl: {%s}' % req,
                        MessageType.ERROR)
                    self.valid_params = 0  # set the param validation as False
                    return

        title = "Input for " + self.params["model"][0]["code"]
        self.SetTitle(title)

        count = 0  # Keeps track of how many input items there are
        self.static_texts = []
        self.text_ctrls = []
        self.help_texts = []
        self.inputs = []
        self.variable_names = []
        self.variable_types = []
        self.required = []

        # Add components dynamically
        for item in model_inputs:
            static_text = wx.StaticText(scroll_panel,
                                        id=count,
                                        label=item["name"] + ":")
            help_text = wx.StaticText(scroll_panel,
                                      id=count,
                                      label=item["help"])
            text_ctrl = wx.TextCtrl(scroll_panel, id=count)

            file_explorer_button = None
            if item["input"] == "file":
                file_explorer_button = wx.Button(scroll_panel,
                                                 id=count,
                                                 label="Browse",
                                                 style=wx.BU_EXACTFIT)

            font = wx.Font(pointSize=8,
                           family=wx.DEFAULT,
                           style=wx.NORMAL,
                           weight=wx.NORMAL)
            help_text.SetFont(font)

            # set default values
            if 'default' in item:
                text_ctrl.Value = str(item['default'])

            # save variable types
            if 'datatype' in item:
                self.variable_types.append(item['datatype'])
            else:
                self.variable_types.append('str')

            # Keep track of all the components in the lists
            self.static_texts.append(static_text)
            self.text_ctrls.append(text_ctrl)
            self.inputs.append(file_explorer_button)
            self.help_texts.append(help_text)
            self.variable_names.append(item['variable'])
            self.required.append(
                bool(item['required']) if 'required' in item else False)
            count += 1

        break_line = wx.StaticLine(panel)
        self.cancel_button = wx.Button(bottom_panel,
                                       label="Cancel",
                                       style=wx.BU_EXACTFIT)
        self.submit_button = wx.Button(bottom_panel,
                                       label="Load Model",
                                       style=wx.BU_EXACTFIT)

        # Create sizers
        frame_sizer = wx.BoxSizer(wx.VERTICAL)
        scroll_panel_sizer = wx.BoxSizer(wx.VERTICAL)
        flex_grid_sizer = wx.FlexGridSizer(rows=count * 3,
                                           cols=1,
                                           vgap=1,
                                           hgap=5)

        button_sizer = wx.BoxSizer(wx.HORIZONTAL)

        # Add components to sizer
        for i in range(count):
            # Used to act as if there were two columns. Allows the text ctrl to overflow into the second column
            sizer = wx.BoxSizer(wx.HORIZONTAL)
            word_wrap_sizer = wx.BoxSizer(
                wx.HORIZONTAL)  # For wrapping the help text

            flex_grid_sizer.Add(self.static_texts[i])

            sizer.Add(self.text_ctrls[i], 1, wx.EXPAND)
            if self.inputs[i]:
                sizer.Add(self.inputs[i], 0, wx.EXPAND)

            flex_grid_sizer.Add(sizer, 1, wx.EXPAND)
            word_wrap_sizer.Add(self.help_texts[i], 1, wx.EXPAND)
            flex_grid_sizer.Add(word_wrap_sizer, 1, wx.EXPAND | wx.BOTTOM, 15)
            flex_grid_sizer.AddGrowableRow(((i + 1) * 3) - 1, 1)

        flex_grid_sizer.AddGrowableCol(
            0, 1)  # Set the first column to expand and fill space

        # Adding the flex grid sizer to scroll panel sizer to give margin to the side of the scroll bar
        scroll_panel_sizer.Add(flex_grid_sizer, 1, wx.ALL | wx.EXPAND, 20)
        scroll_panel.SetSizer(scroll_panel_sizer)
        scroll_panel_sizer.Fit(scroll_panel)

        ###################################
        # ADD HELP IF MARKDOWN HELP EXIST
        ###################################
        if "help_markdown" in self.params:
            self.help_button = wx.Button(bottom_panel,
                                         label="Help",
                                         style=wx.BU_EXACTFIT)
            button_sizer.Add(self.help_button, 0, wx.ALL | wx.ALIGN_LEFT, 5)

        button_sizer.AddSpacer((0, 0), 1, wx.EXPAND, 5)
        button_sizer.Add(self.cancel_button, 0, wx.ALL | wx.ALIGN_RIGHT, 5)
        button_sizer.Add(self.submit_button, 0, wx.EXPAND | wx.ALL, 5)
        bottom_panel.SetSizer(button_sizer)

        frame_sizer.Add(scroll_panel,
                        proportion=1,
                        flag=wx.LEFT | wx.EXPAND,
                        border=-10)
        frame_sizer.Add(break_line, 0, wx.EXPAND, 5)
        frame_sizer.Add(bottom_panel, 0, wx.ALL | wx.EXPAND, 3)

        panel.SetSizer(frame_sizer)
        frame_sizer.Fit(self)
        self.SetSize((-1, 400))

        self.Show()