예제 #1
0
    def importXMLFromFile(self):
        ''' NO DOCUMENTATION '''
        # print "importXMLFromFile"
        # First, prompt the user for the filename to read in
        start_dir = paths.get_project_configs_path()
        configDialog = QFileDialog()
        filter_str = QString("*.xml")
        fd = configDialog.getOpenFileName(
            self.manager.base_widget, "Please select an XML file to import...",
            start_dir, filter_str)
        # Check for cancel
        if len(fd) == 0:
            return
        fileName = QString(fd)

        # Pass that in to create a new XMLConfiguration
        try:
            options = ''
            xml_tree = load_xml_file(str(fileName))
            xml_node = xml_tree.getroot()

            options = ' or another node in the tree view'
            self.import_from_node(xml_node)
        except Exception, e:
            MessageBox.error(mainwindow=self.view,
                             text='Cannot insert XML file.',
                             detailed_text='XML insert failed.  '
                             '%s.  '
                             'Please select another XML file%s.' %
                             (e, options))
            return
    def execToolConfig(self):
        '''
        Show the dialog box for executing a "tool config"
        A tool config is has a pointer to an existing tool (a "tool hook") but
        can provide an alternative configuration.
        '''
        assert self.has_selected_item()

        # First we need to get the hooked node that we want to run
        node = self.selected_item().node
        hooked_tool_name = node.find('tool_hook').text
        hooked_tool_node = get_tool_node_by_name(self.project,
                                                 hooked_tool_name)
        if hooked_tool_node is None:
            MessageBox.error(
                mainwindow=self.view,
                text='Invalid tool hook',
                detailed_text=(
                    'This tool config points to a tool named "%s" '
                    'but there is no tool with that name in this project.' %
                    hooked_tool_name))
            return

        # Open up a GUI element and populate with variable's
        tool_lib_node = get_tool_library_node(self.project)
        params = {'tool_path': get_path_to_tool_modules(self.project)}
        window = ExecuteToolGui(parent_widget=self.manager.base_widget,
                                tool_node=hooked_tool_node,
                                tool_config=node,
                                tool_library_node=tool_lib_node,
                                params=params)
        window.setModal(True)
        window.show()
    def execToolFile(self):
        '''
        Show a dialog box that lets the user configure and execute a
        tool.
        '''
        assert self.has_selected_item()

        tool_lib_node = get_tool_library_node(self.project)
        params = {'tool_path': get_path_to_tool_modules(self.project)}

        tool_node = self.selected_item().node

        try:
            module_name = tool_node.find('class_module').text
            import_path = params['tool_path'] + '.' + module_name
            importString = "from %s import opusRun" % (import_path)
            exec(importString)
        except Exception, e:
            print e
            MessageBox.error(
                mainwindow=self.view,
                text='Invalid module name',
                detailed_text=
                ('This tool points to a module named "%s" '
                 'but there is no module with that name, or module returned import error.'
                 % import_path))
            return
예제 #4
0
 def _checkImportNodeMsg(self):
     try:
         return self._checkImportNode()
     except Exception, e:
         MessageBox.error(self, 'This is not a valid XML structure.', \
                          '''%s.\n\n%s''' % (e, self.ATTENTION))
         return None
    def addParam(self):
        assert self.has_selected_item()

        item = self.selected_item()
        node = item.node
        window = addParamGui(self.manager.base_widget, None)
        window.setModal(True)
        window.show()

        if window.exec_() == window.Accepted:
            name = str(window.nameEdit.text())
            typ = str(window.typeComboBox.currentText())
            default = str(window.defaultEdit.text())
            required = str(window.requiredComboBox.currentText())

            attributes = {
                'name': name,
                'param_type': typ,
                'required': required
            }
            node = Element('param', attributes)
            node.text = default
            if self.model.insertRow(0, self.selected_index(), node) == False:
                MessageBox.error(
                    mainwindow=self.view,
                    text='Parameter Name Exists',
                    detailed_text=(
                        'The parameter name to add is "%s" '
                        'but there is already a parameter with that name.' %
                        name))
                return

            self.view.expand(self.selected_index())
예제 #6
0
    def __init__(self, parent_widget):
        QDialog.__init__(self, parent_widget)
        self.setupUi(self)

        settings_directory = os.path.join(os.environ['OPUS_HOME'], 'settings')
        self._config_filename = os.path.join(settings_directory, 'database_server_configurations.xml')
        try:
            root = ElementTree(file=self._config_filename).getroot()
            view = XmlView(self)
            model = XmlModel(root)
            delegate = XmlItemDelegate(view)
            view.setModel(model)
            # Turns out that Qt Garbage collects the model (and delegate) if we don't explicitly
            # bind it to a Python object in addition to using the PyQt .setModel() method.
            view._model = model
            view._delegate = delegate
            view.setItemDelegate(delegate)
            view.openDefaultItems()

            self.gridlayout.addWidget(view)

            self.tree_view = view
            self.xml_root = root
            return

        except IOError, ex:
            MessageBox.error(mainwindow = self,
                          text = 'Could not initialize Database Settings',
                          detailed_text = str(ex))
            self.xml_root = None
            self._config_filename = ''
            self.configFile = None
    def execBatch(self):
        ''' Present a dialog to execute a set of tool configurations '''
        assert self.has_selected_item()
        # Node representing the set to execute
        tool_set_node = self.selected_item().node

        # map tool config nodes in set -> name of the hooked node
        tool_config_to_tool_name = {}
        tool_config_nodes = tool_set_node[:]
        for tool_config_node in tool_config_nodes:
            hook_node = tool_config_node.find('tool_hook')
            hooked_tool_name = str(hook_node.text or '').strip()
            hooked_tool_node = get_tool_node_by_name(self.project,
                                                     hooked_tool_name)
            module_name = hooked_tool_node.find('class_module').text

            try:
                module_name = hooked_tool_node.find('class_module').text
                tool_path = get_path_to_tool_modules(self.project)
                import_path = tool_path + '.' + module_name
                importString = "from %s import opusRun" % (import_path)
                exec(importString)
                tool_config_to_tool_name[tool_config_node] = import_path
            except Exception, e:
                MessageBox.error(
                    mainwindow=self.view,
                    text='Invalid module name',
                    detailed_text=
                    ('This tool points to a module named "%s" '
                     'but there is no module with that name, or module returned import error.'
                     % import_path))
                return
예제 #8
0
 def _checkImportNodeMsg(self):
     try:
         return self._checkImportNode()
     except Exception, e:
         MessageBox.error(self, 'This is not a valid XML structure.', \
                          '''%s.\n\n%s''' % (e, self.ATTENTION))
         return None
    def execBatch(self):
        ''' Present a dialog to execute a set of tool configurations '''
        assert self.has_selected_item()
        # Node representing the set to execute
        tool_set_node = self.selected_item().node

        # map tool config nodes in set -> name of the hooked node
        tool_config_to_tool_name = {}
        tool_config_nodes = tool_set_node[:]
        for tool_config_node in tool_config_nodes:
            hook_node = tool_config_node.find('tool_hook')
            hooked_tool_name = str(hook_node.text or '').strip()
            hooked_tool_node = get_tool_node_by_name(self.project, hooked_tool_name)
            module_name = hooked_tool_node.find('class_module').text
            
            try:
                module_name = hooked_tool_node.find('class_module').text
                tool_path = get_path_to_tool_modules(self.project)
                import_path = tool_path + '.' + module_name
                importString = "from %s import opusRun" % (import_path)
                exec(importString)
                tool_config_to_tool_name[tool_config_node] = import_path
            except Exception, e:
                MessageBox.error(mainwindow = self.view,
                    text = 'Invalid module name',
                    detailed_text = ('This tool points to a module named "%s", ' % import_path + \
                                     'but there is no module with that name, or module returned import error: %s. ' \
                                     % formatExceptionInfo() 
                                     ))
                return
    def addParam(self):
        assert self.has_selected_item()

        item = self.selected_item()
        node = item.node
        window = addParamGui(self.manager.base_widget, None)
        window.setModal(True)
        window.show()

        if window.exec_() == window.Accepted:
            name = str(window.nameEdit.text())
            typ = str(window.typeComboBox.currentText())
            default = str(window.defaultEdit.text())
            required = str(window.requiredComboBox.currentText())

            attributes = {'name': name, 'param_type': typ, 'required': required}
            node = Element('param', attributes)
            node.text = default
            if self.model.insertRow(0, self.selected_index(), node) == False:
                MessageBox.error(mainwindow = self.view,
                    text = 'Parameter Name Exists',
                    detailed_text = ('The parameter name to add is "%s" '
                    'but there is already a parameter with that name.' %
                    name))
                return

            self.view.expand(self.selected_index())
    def execToolConfig(self):
        '''
        Show the dialog box for executing a "tool config"
        A tool config is has a pointer to an existing tool (a "tool hook") but
        can provide an alternative configuration.
        '''
        assert self.has_selected_item()

        # First we need to get the hooked node that we want to run
        node = self.selected_item().node
        hooked_tool_name = node.find('tool_hook').text
        hooked_tool_node = get_tool_node_by_name(self.project, hooked_tool_name)
        if hooked_tool_node is None:
            MessageBox.error(mainwindow = self.view,
                text = 'Invalid tool hook',
                detailed_text = ('This tool config points to a tool named "%s" '
                    'but there is no tool with that name in this project.' %
                    hooked_tool_name))
            return

        # Open up a GUI element and populate with variable's
        tool_lib_node = get_tool_library_node(self.project)
        params = {'tool_path': get_path_to_tool_modules(self.project)}
        window = ExecuteToolGui(parent_widget = self.manager.base_widget,
                                tool_node = hooked_tool_node,
                                tool_config = node,
                                tool_library_node = tool_lib_node,
                                params=params,
                                model=self.model)
        window.setModal(True)
        window.show()
    def execToolFile(self):
        '''
        Show a dialog box that lets the user configure and execute a
        tool.
        '''
        assert self.has_selected_item()

        tool_lib_node = get_tool_library_node(self.project)
        params = {'tool_path': get_path_to_tool_modules(self.project)}

        tool_node = self.selected_item().node

        try:
            module_name = tool_node.find('class_module').text
            import_path = params['tool_path'] + '.' + module_name
            importString = "from %s import opusRun" % (import_path)
            exec(importString)
        except Exception, e:
            print e
            MessageBox.error(mainwindow = self.view,
                text = 'Invalid module name',
                detailed_text = ('This tool points to a module named "%s", ' % import_path + \
                                 'but there is no module with that name, or module returned import error: %s. ' \
                                 % formatExceptionInfo() 
                                 ))
            return
    def execToolFile(self):
        """
        Show a dialog box that lets the user configure and execute a
        tool.
        """
        assert self.has_selected_item()

        tool_lib_node = get_tool_library_node(self.project)
        params = {"tool_path": get_path_to_tool_modules(self.project)}

        tool_node = self.selected_item().node

        try:
            module_name = tool_node.find("class_module").text
            import_path = params["tool_path"] + "." + module_name
            importString = "from %s import opusRun" % (import_path)
            exec (importString)
        except Exception, e:
            print e
            MessageBox.error(
                mainwindow=self.view,
                text="Invalid module name",
                detailed_text=(
                    'This tool points to a module named "%s" '
                    "but there is no module with that name, or module returned import error." % import_path
                ),
            )
            return
    def _get_viz_spec(self):
        viz_type = self.cboVizType.currentText()
        translation = self._get_output_types(viz_type)
        dataset_name = self.dataset_name
        output_type = QString(translation[str(self.cboOutputType.currentText())])
        indicators = QString(str(self._get_column_values(column = 0)))

        vals = {
                'indicators': indicators,
                'output_type': output_type,
                'dataset_name': dataset_name,
                'visualization_type': QString(self._get_type_mapper()[str(viz_type)])
        }

        if output_type == 'mapnik_map' or output_type == 'mapnik_animated_map':
            vals['mapnik_bucket_labels'] = self.mapnik_options['mapnik_bucket_labels']
            vals['mapnik_bucket_colors'] = self.mapnik_options['mapnik_bucket_colors']
            vals['mapnik_bucket_ranges'] = self.mapnik_options['mapnik_bucket_ranges']
            vals['mapnik_resolution'] = self.mapnik_options['mapnik_resolution']
            vals['mapnik_page_dims'] = self.mapnik_options['mapnik_page_dims']
            vals['mapnik_map_lower_left'] = self.mapnik_options['mapnik_map_lower_left']
            vals['mapnik_map_upper_right'] = self.mapnik_options['mapnik_map_upper_right']
            vals['mapnik_legend_lower_left'] = self.mapnik_options['mapnik_legend_lower_left']
            vals['mapnik_legend_upper_right'] = self.mapnik_options['mapnik_legend_upper_right']


        elif output_type == 'fixed_field':
            try:
                fixed_field_params = QString(str(self._get_column_values(column = 1)))
            except:
                errorInfo = formatExceptionInfo()
                logger.log_error(errorInfo)
                MessageBox.error(mainwindow = self,
                                text = 'Could not get fixed field parameters for all columns',
                                detailed_text = '')
                return None

            vals['fixed_field_specification'] = fixed_field_params
            vals['id_format'] = self.leOption1.text()
        elif output_type == 'sql':
            vals['database_name'] = self.leOption1.text()
        elif output_type == 'esri':
            vals['storage_location'] = self.leOption1.text()
        elif output_type in ('tab', 'xls'):
            if self.rbSingleTable.isChecked():
                output_style = Table.ALL
            elif self.rbTablePerIndicator.isChecked():
                output_style = Table.PER_ATTRIBUTE
            elif self.rbTablePerYear.isChecked():
                output_style = Table.PER_YEAR
            vals['output_style'] = QString(str(output_style))
            if self.appendTypeCheckBox.isChecked():
                vals['append_col_type'] = True
            else:
                vals['append_col_type'] = False
            if output_type == 'xls':
                vals['storage_location'] = self.leOption1.text()

        return vals
예제 #15
0
 def on_buttonBox_accepted(self):
     try:
         ElementTree(self.xml_root).write(self._config_filename)
     except IOError, ex:
         MessageBox.error(self,
                       text = 'A disk error occured when saving the ' +
                       'settings.',
                       detailed_text = str(ex))
예제 #16
0
 def on_buttonBox_accepted(self):
     try:
         ElementTree(self.xml_root).write(self._config_filename, pretty_print=True, with_tail=False)
     except IOError, ex:
         MessageBox.error(self,
                       text = 'A disk error occured when saving the ' +
                       'settings.',
                       detailed_text = str(ex))
예제 #17
0
    def on_buttonBox_accepted(self):
        path = str(self.lePath.text())
        if not os.path.exists(path):
            msg = 'Cannot import, %s does not exist' % path
            logger.log_warning(msg)
            MessageBox.warning(mainwindow=self, text=msg, detailed_text='')
        else:
            cache_directory = path
            years = []

            for dir in os.listdir(cache_directory):
                if len(dir) == 4 and dir.isdigit():
                    years.append(int(dir))
            if years == []:
                msg = 'Cannot import, %s has no run data' % path
                logger.log_warning(msg)
                MessageBox.warning(mainwindow=self, text=msg, detailed_text='')

            else:
                start_year = min(years)
                end_year = max(years)
                project_name = os.environ['OPUSPROJECTNAME']
                run_name = os.path.basename(path)

                server_config = ServicesDatabaseConfiguration()
                run_manager = RunManager(server_config)

                run_id = run_manager._get_new_run_id()
                resources = {
                    'cache_directory': cache_directory,
                    'description': '',
                    'years': (start_year, end_year),
                    'project_name': project_name
                }

                try:
                    run_manager.add_row_to_history(run_id=run_id,
                                                   resources=resources,
                                                   status='done',
                                                   run_name=run_name)
                    update_available_runs(self.project)
                    logger.log_status(
                        'Added run %s of project %s to run_activity table' %
                        (run_name, project_name))
                except:
                    errorInfo = formatExceptionInfo()
                    logger.log_error(errorInfo)
                    MessageBox.error(
                        mainwindow=self,
                        text=
                        'Could not add run %s of project %s to run_activity table'
                        % (run_name, project_name),
                        detailed_text=errorInfo)
        self.close()
    def on_buttonBox_accepted(self):
        path = str(self.lePath.text())
        if not os.path.exists(path):
            msg = 'Cannot import, %s does not exist' % path
            logger.log_warning(msg)
            MessageBox.warning(mainwindow = self,
                            text = msg,
                            detailed_text = '')
        else:
            cache_directory = path
            years = []

            for dir in os.listdir(cache_directory):
                if len(dir) == 4 and dir.isdigit():
                    years.append(int(dir))
            if years == []:
                msg = 'Cannot import, %s has no run data'%path
                logger.log_warning(msg)
                MessageBox.warning(mainwindow = self,
                                text = msg,
                                detailed_text = '')

            else:
                start_year = min(years)
                end_year = max(years)
                project_name = os.environ['OPUSPROJECTNAME']
                run_name = os.path.basename(path)

                server_config = ServicesDatabaseConfiguration()
                run_manager = RunManager(server_config)

                run_id = run_manager._get_new_run_id()
                resources = {
                     'cache_directory': cache_directory,
                     'description': '',
                     'years': (start_year, end_year),
                     'project_name': project_name
                }

                try:
                    run_manager.add_row_to_history(run_id = run_id,
                                                   resources = resources,
                                                   status = 'done',
                                                   run_name = run_name)
                    update_available_runs(self.project)
                    logger.log_status('Added run %s of project %s to run_activity table'%(run_name, project_name))
                except:
                    errorInfo = formatExceptionInfo()
                    logger.log_error(errorInfo)
                    MessageBox.error(mainwindow = self,
                                    text = 'Could not add run %s of project %s to run_activity table'%(run_name, project_name),
                                    detailed_text = errorInfo)
        self.close()
예제 #19
0
    def __init__(self, parent_widget):
        QDialog.__init__(self, parent_widget)
        self.setupUi(self)

        desc = '\n'.join((
            '%(PROTOCOL_TAG)s: Database protocol. Double-click and hold to see the available options.',
            '%(HOST_NAME_TAG)s: Host name (and database name for Postgres).',
            '    * Postgres: Use the format "host_name/database_name" (without quotes).',
            '          - Leave host_name empty to connect to localhost.',
            '          - Leave database_name empty (but retain the slash) to connect',
            '            to the default database for the database user.',
            '    * Other protocols: Enter the host name only.',
            '%(USER_NAME_TAG)s: Database user name',
            '%(PASSWORD_TAG)s: Database password', '',
            'To add a new database configuration, please edit',
            '%(conf_file_path)s'))
        desc = QtGui.QApplication.translate("DatabaseSettingsEditGui", desc,
                                            None,
                                            QtGui.QApplication.UnicodeUTF8)
        desc = unicode(desc) % dict(
            [(n, eval('DatabaseServerConfiguration.%s' % n))
             for n in dir(DatabaseServerConfiguration)
             if re.match('.*_TAG$', n)] +
            [('conf_file_path',
              DatabaseServerConfiguration.get_default_configuration_file_path(
              ))])
        desc = QtCore.QString(desc)

        self.description.setText(desc)

        self._config_filename = DatabaseServerConfiguration.get_default_configuration_file_path(
        )

        try:
            self.xml_root = ElementTree(file=self._config_filename).getroot()
            self.base_widget = self.variableBox
            self.xml_controller = XmlController_DatabaseConfig(self)
            # Turns out that Qt Garbage collects the model (and delegate) if we don't explicitly
            # bind it to a Python object in addition to using the PyQt .setModel() method.

            self.tree_view = self.xml_controller.view
            return

        except IOError, ex:
            MessageBox.error(mainwindow=self,
                             text='Could not initialize Database Settings',
                             detailed_text=str(ex))
            self.xml_root = None
            self._config_filename = ''
            self.configFile = None
예제 #20
0
    def __init__(self, parent_widget):
        QDialog.__init__(self, parent_widget)
        self.setupUi(self)

        desc = "\n".join(
            (
                "%(PROTOCOL_TAG)s: Database protocol. Double-click and hold to see the available options.",
                "%(HOST_NAME_TAG)s: Host name (and database name for Postgres).",
                '    * Postgres: Use the format "host_name/database_name" (without quotes).',
                "          - Leave host_name empty to connect to localhost.",
                "          - Leave database_name empty (but retain the slash) to connect",
                "            to the default database for the database user.",
                "    * Other protocols: Enter the host name only.",
                "%(USER_NAME_TAG)s: Database user name",
                "%(PASSWORD_TAG)s: Database password",
                "",
                "To add a new database configuration, please edit",
                "%(conf_file_path)s",
            )
        )
        desc = QtGui.QApplication.translate("DatabaseSettingsEditGui", desc, None, QtGui.QApplication.UnicodeUTF8)
        desc = unicode(desc) % dict(
            [
                (n, eval("DatabaseServerConfiguration.%s" % n))
                for n in dir(DatabaseServerConfiguration)
                if re.match(".*_TAG$", n)
            ]
            + [("conf_file_path", DatabaseServerConfiguration.get_default_configuration_file_path())]
        )
        desc = QtCore.QString(desc)

        self.description.setText(desc)

        self._config_filename = DatabaseServerConfiguration.get_default_configuration_file_path()

        try:
            self.xml_root = ElementTree(file=self._config_filename).getroot()
            self.base_widget = self.variableBox
            self.xml_controller = XmlController_DatabaseConfig(self)
            # Turns out that Qt Garbage collects the model (and delegate) if we don't explicitly
            # bind it to a Python object in addition to using the PyQt .setModel() method.

            self.tree_view = self.xml_controller.view
            return

        except IOError, ex:
            MessageBox.error(mainwindow=self, text="Could not initialize Database Settings", detailed_text=str(ex))
            self.xml_root = None
            self._config_filename = ""
            self.configFile = None
 def update_model_nested_structure(self, node = None):
     '''
     Create an XML representation to use for the argument "nested_structure" used by Nested Logit
     Models (NLM). The argument is used in the NLMs init() method.
     @param node submodel node to construct a nested structure from (default self.submodel_node)
     @raise RuntimeError: If the model node could not be updated
     @return the created nested_structure node (useful for tests)
     '''
     node = self.submodel_node if node is None else node
     if node.find('nest') is None: # can't create a nested structure if there are no nests
         return None
     counter = {'current count': 1} # pass object ref to keep increments down the recursive chain
     try:
         new_nested_structure_node = self._create_nested_structure_xml(node, counter)
     except ValueError, ex:
         MessageBox.error(self, 'Not all nests have equations assigned to them.', str(ex))
         return None
예제 #22
0
 def _update_variable_from_fields(self):
     ''' update the variable with values from the gui widgets '''
     self.variable['name'] = str(self.leVarName.text())
     self.variable['source'] = str(self.cboVarType.currentText())
     self.variable['definition'] = str(
         self.le_var_def.document().toPlainText())
     try:
         v = VariableName(self.variable['definition'])
         dataset_name = v.get_dataset_name()
         interaction_set_names = v.get_interaction_set_names()
     except (SyntaxError, ValueError):
         MessageBox.error(
             mainwindow=self,
             text='parse error for variable',
             detailed_text=
             'setting dataset name for this variable to <unknown>')
         dataset_name = '<unknown>'
         interaction_set_names = None
     if dataset_name is None and interaction_set_names is not None:
         # It's an interaction set.  Look up possible names in available_datasets
         names = get_available_dataset_names(self.validator.project)
         n1 = interaction_set_names[0] + '_x_' + interaction_set_names[1]
         if n1 in names:
             dataset_name = n1
         else:
             n2 = interaction_set_names[1] + '_x_' + interaction_set_names[0]
             if n2 in names:
                 dataset_name = n2
             else:
                 MessageBox.error(
                     mainwindow=self,
                     text=
                     'unable to find an interaction set in available_datasets for this variable',
                     detailed_text=
                     "tried %s and %s \nbut couldn't find either name in available_datasets \nsetting dataset_name to <unknown>"
                     % (n1, n2))
                 dataset_name = '<unknown>'
     self.variable['dataset'] = dataset_name
     if self.rbUseModel.isChecked():
         self.variable['use'] = 'model variable'
     elif self.rbUseIndicator.isChecked():
         self.variable['use'] = 'indicator'
     else:
         self.variable['use'] = 'both'
예제 #23
0
 def okToCloseProject(self):
     '''
     Called before an operation that causes this project to close.
     If the project contains changes; ask if the user wants to save them,
     discard them or cancel the operation.
     @return: True if the user wishes to proceed with the closing operation.
     '''
     if not self.project.dirty: return True
     question = 'Do you want to save your changes before closing the project?'
     user_answer = common_dialogs.save_before_close(question)
     if user_answer == common_dialogs.YES:
         ok_flag, msg = self.project.save() # cancels on failed save
         if not ok_flag:
             MessageBox.error(self, "Could not save project", str(msg))
             return False
         return True
     elif user_answer == common_dialogs.NO:
         self.project.dirty = False
         return True
     else:
         return False
 def _update_variable_from_fields(self):
     ''' update the variable with values from the gui widgets '''
     self.variable['name'] = str(self.leVarName.text())
     self.variable['source'] = str(self.cboVarType.currentText())
     self.variable['definition'] = str(self.le_var_def.document().toPlainText())
     try:
         v = VariableName(self.variable['definition'])
         dataset_name = v.get_dataset_name()
         interaction_set_names = v.get_interaction_set_names()
     except (SyntaxError, ValueError):
         MessageBox.error(mainwindow = self,
             text = 'parse error for variable',
             detailed_text = 'setting dataset name for this variable to <unknown>')
         dataset_name = '<unknown>'
         interaction_set_names = None
     if dataset_name is None and interaction_set_names is not None:
         # It's an interaction set.  Look up possible names in available_datasets
         names = get_available_dataset_names(self.validator.project)
         n1 = interaction_set_names[0] + '_x_' + interaction_set_names[1]
         if n1 in names:
             dataset_name = n1
         else:
             n2 = interaction_set_names[1] + '_x_' + interaction_set_names[0]
             if n2 in names:
                 dataset_name = n2
             else:
                 MessageBox.error(mainwindow = self,
                     text = 'unable to find an interaction set in available_datasets for this variable',
                     detailed_text = "tried %s and %s \nbut couldn't find either name in available_datasets \nsetting dataset_name to <unknown>" % (n1,n2) )
                 dataset_name = '<unknown>'
     self.variable['dataset'] = dataset_name
     if self.rbUseModel.isChecked():
         self.variable['use'] = 'model variable'
     elif self.rbUseIndicator.isChecked():
         self.variable['use'] = 'indicator'
     else:
         self.variable['use'] = 'both'
예제 #25
0
 def update_model_nested_structure(self, node=None):
     '''
     Create an XML representation to use for the argument "nested_structure" used by Nested Logit
     Models (NLM). The argument is used in the NLMs init() method.
     @param node submodel node to construct a nested structure from (default self.submodel_node)
     @raise RuntimeError: If the model node could not be updated
     @return the created nested_structure node (useful for tests)
     '''
     node = self.submodel_node if node is None else node
     if node.find(
             'nest'
     ) is None:  # can't create a nested structure if there are no nests
         return None
     counter = {
         'current count': 1
     }  # pass object ref to keep increments down the recursive chain
     try:
         new_nested_structure_node = self._create_nested_structure_xml(
             node, counter)
     except ValueError, ex:
         MessageBox.error(self,
                          'Not all nests have equations assigned to them.',
                          str(ex))
         return None
 def _run_error(self,errorMessage):
     text = 'Error in computing or displaying indicator'
     MessageBox.error(mainwindow = self, text = text, detailed_text = errorMessage)
예제 #27
0
            return

        except IOError, ex:
            MessageBox.error(mainwindow=self, text="Could not initialize Database Settings", detailed_text=str(ex))
            self.xml_root = None
            self._config_filename = ""
            self.configFile = None

    def on_buttonBox_accepted(self):
        try:
            ElementTree(self.xml_root).write(self._config_filename, pretty_print=True, with_tail=False)
        except IOError, ex:
            MessageBox.error(self, text="A disk error occured when saving the " + "settings.", detailed_text=str(ex))
        except Exception, ex:
            MessageBox.error(
                mainwindow=self, text="An unknown error occured when saving " + "your changes.", detailed_text=str(ex)
            )
        finally:
            self.close()

    def on_buttonBox_rejected(self):
        # If there are any changes to the data, ask the user to save them
        if self.tree_view.model().dirty:
            question = "Do you want to save your changes before closing?"
            user_answer = common_dialogs.save_before_close(question)
            if user_answer == common_dialogs.YES:
                self.on_buttonBox_accepted()
            elif user_answer == common_dialogs.NO:
                pass
            else:
                return  # Cancel
    def importXMLFromFile(self):
        """ NO DOCUMENTATION """
        assert self.has_selected_item()
        # print "importXMLFromFile"
        # First, prompt the user for the filename to read in
        start_dir = ""
        opus_home = os.environ.get("OPUS_HOME")
        if opus_home:
            start_dir_test = os.path.join(opus_home, "project_configs")
            if start_dir_test:
                start_dir = start_dir_test
        configDialog = QFileDialog()
        filter_str = QString("*.xml")
        fd = configDialog.getOpenFileName(
            self.manager.base_widget, "Please select an xml file to import...", start_dir, filter_str
        )
        # Check for cancel
        if len(fd) == 0:
            return
        fileName = QString(fd)
        fileNameInfo = QFileInfo(QString(fd))
        fileNameInfoBaseName = fileNameInfo.completeBaseName()
        fileNameInfoName = fileNameInfo.fileName().trimmed()
        fileNameInfoPath = fileNameInfo.absolutePath().trimmed()

        # Pass that in to create a new XMLConfiguration
        xml_config = XMLConfiguration(str(fileNameInfoName), str(fileNameInfoPath))

        xml_node = xml_config.full_tree.getroot()
        if len(xml_node) == 0:
            raise ValueError("Loading node from XML file failed. " "No node definition found")
        xml_node = xml_node[0]

        parent_node = self.selected_item().node

        allowed_parent_tags = {
            "tool": ["tool_group"],
            "class_module": ["tool"],
            "path_to_tool_modules": ["tool_library"],
            "tool_library": ["data_manager"],
            "tool_group": ["tool_library"],
            "params": ["tool"],
            "param": ["params"],
            "tool_config": ["tool_set"],
            "tool_set": ["tool_sets"],
            "tool_sets": ["data_manager"],
        }
        if parent_node.tag not in allowed_parent_tags[xml_node.tag]:
            MessageBox.error(
                mainwindow=self.view,
                text="Invalid Xml insert",
                detailed_text=(
                    'Xml insert of node of type "%s" failed.  '
                    'Invalid type of parent node is "%s" - needs to be one of %s'
                    % (xml_node.tag, parent_node.tag, str(allowed_parent_tags[xml_node.tag]))
                ),
            )
            return

        # Insert it into the parent node from where the user clicked
        name = xml_node.get("name") if xml_node.get("name") is not None else ""
        if self.model.insertRow(0, self.selected_index(), xml_node) is False:
            MessageBox.error(
                mainwindow=self.view,
                text="Xml Insert Failed",
                detailed_text=(
                    'Xml insert of node with name "%s" failed - '
                    "most likely because there is already a node with that name." % name
                ),
            )
            return
예제 #29
0
 def _run_error(self, errorMessage):
     text = 'Error in computing or displaying indicator'
     MessageBox.error(mainwindow=self,
                      text=text,
                      detailed_text=errorMessage)
예제 #30
0
    def _get_viz_spec(self):
        viz_type = self.cboVizType.currentText()
        translation = self._get_output_types(viz_type)
        dataset_name = self.dataset_name
        output_type = QString(translation[str(
            self.cboOutputType.currentText())])
        indicators = QString(str(self._get_column_values(column=0)))

        vals = {
            'indicators': indicators,
            'output_type': output_type,
            'dataset_name': dataset_name,
            'visualization_type':
            QString(self._get_type_mapper()[str(viz_type)])
        }

        if output_type == 'mapnik_map' or output_type == 'mapnik_animated_map':
            vals['mapnik_bucket_labels'] = self.mapnik_options[
                'mapnik_bucket_labels']
            vals['mapnik_bucket_colors'] = self.mapnik_options[
                'mapnik_bucket_colors']
            vals['mapnik_bucket_ranges'] = self.mapnik_options[
                'mapnik_bucket_ranges']
            vals['mapnik_resolution'] = self.mapnik_options[
                'mapnik_resolution']
            vals['mapnik_page_dims'] = self.mapnik_options['mapnik_page_dims']
            vals['mapnik_map_lower_left'] = self.mapnik_options[
                'mapnik_map_lower_left']
            vals['mapnik_map_upper_right'] = self.mapnik_options[
                'mapnik_map_upper_right']
            vals['mapnik_legend_lower_left'] = self.mapnik_options[
                'mapnik_legend_lower_left']
            vals['mapnik_legend_upper_right'] = self.mapnik_options[
                'mapnik_legend_upper_right']

        elif output_type == 'fixed_field':
            try:
                fixed_field_params = QString(
                    str(self._get_column_values(column=1)))
            except:
                errorInfo = formatExceptionInfo()
                logger.log_error(errorInfo)
                MessageBox.error(
                    mainwindow=self,
                    text='Could not get fixed field parameters for all columns',
                    detailed_text='')
                return None

            vals['fixed_field_specification'] = fixed_field_params
            vals['id_format'] = self.leOption1.text()
        elif output_type == 'sql':
            vals['database_name'] = self.leOption1.text()
        elif output_type == 'esri':
            vals['storage_location'] = self.leOption1.text()
        elif output_type == 'tab':
            if self.rbSingleTable.isChecked():
                output_style = Table.ALL
            elif self.rbTablePerIndicator.isChecked():
                output_style = Table.PER_ATTRIBUTE
            elif self.rbTablePerYear.isChecked():
                output_style = Table.PER_YEAR

            vals['output_style'] = QString(str(output_style))

        return vals
예제 #31
0
                          detailed_text = str(ex))
            self.xml_root = None
            self._config_filename = ''
            self.configFile = None

    def on_buttonBox_accepted(self):
        try:
            ElementTree(self.xml_root).write(self._config_filename)
        except IOError, ex:
            MessageBox.error(self,
                          text = 'A disk error occured when saving the ' +
                          'settings.',
                          detailed_text = str(ex))
        except Exception, ex:
            MessageBox.error(mainwindow = self,
                          text = 'An unknown error occured when saving ' +
                          'your changes.',
                          detailed_text = str(ex))
        finally:
            self.close()

    def on_buttonBox_rejected(self):
        # If there are any changes to the data, ask the user to save them
        if self.tree_view.model().dirty:
            question = 'Do you want to save your changes before closing?'
            user_answer = common_dialogs.save_before_close(question)
            if user_answer == common_dialogs.YES:
                self.on_buttonBox_accepted()
            elif user_answer == common_dialogs.NO:
                self.close()
            else:
                return # Cancel
    def importXMLFromFile(self):
        ''' NO DOCUMENTATION '''
        assert self.has_selected_item()
        # print "importXMLFromFile"
        # First, prompt the user for the filename to read in
        start_dir = ''
        opus_home = os.environ.get('OPUS_HOME')
        if opus_home:
            start_dir_test = os.path.join(opus_home, 'project_configs')
            if start_dir_test:
                start_dir = start_dir_test
        configDialog = QFileDialog()
        filter_str = QString("*.xml")
        fd = configDialog.getOpenFileName(
            self.manager.base_widget, "Please select an xml file to import...",
            start_dir, filter_str)
        # Check for cancel
        if len(fd) == 0:
            return
        fileName = QString(fd)
        fileNameInfo = QFileInfo(QString(fd))
        fileNameInfoBaseName = fileNameInfo.completeBaseName()
        fileNameInfoName = fileNameInfo.fileName().trimmed()
        fileNameInfoPath = fileNameInfo.absolutePath().trimmed()

        # Pass that in to create a new XMLConfiguration
        xml_config = XMLConfiguration(str(fileNameInfoName),
                                      str(fileNameInfoPath))

        xml_node = xml_config.full_tree.getroot()
        if len(xml_node) == 0:
            raise ValueError('Loading node from XML file failed. '
                             'No node definition found')
        xml_node = xml_node[0]

        parent_node = self.selected_item().node

        allowed_parent_tags = {"tool": ["tool_group"], \
                               "class_module": ["tool"], \
                                    "path_to_tool_modules": ["tool_library"], \
                               "tool_library": ["data_manager"], \
                               "tool_group": ["tool_library"], \
                               "params": ["tool"], \
                               "param": ["params"], \
                               "tool_config": ["tool_set"], \
                               "tool_set": ["tool_sets"], \
                               "tool_sets": ["data_manager"]}
        if parent_node.tag not in allowed_parent_tags[xml_node.tag]:
            MessageBox.error(
                mainwindow=self.view,
                text='Invalid Xml insert',
                detailed_text=
                ('Xml insert of node of type "%s" failed.  '
                 'Invalid type of parent node is "%s" - needs to be one of %s'
                 % (xml_node.tag, parent_node.tag,
                    str(allowed_parent_tags[xml_node.tag]))))
            return

        # Insert it into the parent node from where the user clicked
        name = xml_node.get('name') if xml_node.get('name') is not None else ''
        if self.model.insertRow(0, self.selected_index(), xml_node) is False:
            MessageBox.error(
                mainwindow=self.view,
                text='Xml Insert Failed',
                detailed_text=
                ('Xml insert of node with name "%s" failed - '
                 'most likely because there is already a node with that name.'
                 % name))
            return