コード例 #1
0
    def attach_variant(self, variant_id, *args, **kwargs):
        a = 1
        for layer in self.iface.legendInterface().selectedLayers():
            if any([
                    a.name() == 'begroeiingsvariant_id'
                    for a in layer.pendingFields()
            ]):
                # if not layer.isEditable():
                #     messagebar_message('Fout', 'Laag is niet bewerkbaar', QgsMessageBar.WARNING, 15)
                #     return

                features = layer.selectedFeatures()
                layer.startEditing()
                count = 0
                for feature in features:
                    feature['begroeiingsvariant_id'] = variant_id
                    count += 1
                    layer.updateFeature(feature)

                layer.commitChanges()

                messagebar_message(
                    'Gelukt',
                    '{0} features op begroeiingsvariant gezet.'.format(count),
                    QgsMessageBar.INFO, 15)

                if self.iface.mapCanvas().isCachingEnabled():
                    layer.setCacheImage(None)
                else:
                    self.iface.mapCanvas().refresh()

            else:
                pass
                # todo: select editable layer with link to begroeiingsVariant
                messagebar_message(
                    'Fout', 'Laag bevat geen link naar begroeiingsVariant',
                    QgsMessageBar.WARNING, 15)
                return
コード例 #2
0
    def set_next_endpoint(self):
        """
        select the next endpoint in a traject with no selected variant
        called by the next_endpoint_button

        returns: -
        """
        sp = self.legger_model.sp
        if sp is None:
            messagebar_message('Fout',
                               'Selecteer eerst een startpunt (kolom sp)',
                               level=1,  # Warning
                               duration=15)
            return

        missing_values, endpoint = self.legger_model.find_endpoint_traject_without_legger_profile(sp)
        if not missing_values or endpoint is None:
            messagebar_message('Eindpunt selectie',
                               'Geen traject gevonden met ontbrekende legger',
                               duration=15)
        else:
            self.legger_model.open_till_endpoint(endpoint, close_other=True)
            self.legger_model.setDataItemKey(endpoint, 'ep', True)
コード例 #3
0
    def create_spatialite_database(self):
        # todo:
        #  feedback if input is incorrect.

        settings = QSettings('leggertool', 'filepaths')
        try:
            init_path = settings.value('last_used_legger_spatialite_path',
                                       type=str)
        except:
            init_path = os.path.expanduser(
                "~")  # get path to respectively "user" folder

        database = QFileDialog.getSaveFileName(
            self, 'Selecteer bestandslocatie voor nieuwe leggerdatabase',
            init_path, 'Spatialite (*.sqlite)')

        if not database:
            return

        self.var_text_leggerdatabase.setText(database)

        settings.setValue('last_used_legger_spatialite_path',
                          os.path.dirname(database))

        database_path = self.var_text_leggerdatabase.text()
        filepath_DAMO = self.var_text_DAMO.text()
        filepath_HDB = self.var_text_HDB.text()

        if not os.path.exists(filepath_DAMO):
            messagebar_message('Aanmaken leggerdatabase mislukt',
                               'Opgegeven DAMO database bestaat niet',
                               level=2,
                               duration=10)

            raise Exception('Geselecteerde DAMO database mist')

        legger_class = CreateLeggerSpatialite(
            filepath_DAMO,
            filepath_HDB,
            database_path,
        )

        legger_class.full_import_ogr2ogr()

        # set root_tool as last, because this triggers other actions
        self.root_tool.polder_datasource = database

        # create views
        con_legger = dbapi.connect(self.root_tool.polder_datasource)
        create_legger_views(con_legger)

        con_legger.execute("""
            WITH 
                max_diepte as (Select pr.hydro_id as hydro_id, min(pp.iws_hoogte) as bodemhoogte, ho.streefpeil - min(pp.iws_hoogte)  as diepte, "meting" as bron
                from profielpunten pp, profielen pr, hydroobject ho
                where pp.pro_pro_id = pr.pro_id AND ho.id = pr.hydro_id AND osmomsch="Z1"
                group by pr.hydro_id)
    
            UPDATE kenmerken
            SET (bodemhoogte, diepte, bron_diepte) = (SELECT bodemhoogte, diepte, bron FROM max_diepte WHERE kenmerken.hydro_id = max_diepte.hydro_id)
            WHERE kenmerken.hydro_id in (SELECT hydro_id FROM max_diepte)    
            """)
        con_legger.execute("""
            INSERT INTO begroeiingsvariant(id, naam, is_default, friction_manning, friction_begroeiing, begroeiingsdeel) 
            VALUES 
                (1, 'basis', 1, 27.2, 80, 0.1),
                (2, 'half vol', 0, 27.2, 80, 0.5),
                (3, 'volledig begroeid', 0, 27.2, 80, 0.9)
            """)
        con_legger.execute("""
                    INSERT INTO categorie(categorie, naam, variant_diepte_max, default_talud) 
                    VALUES 
                        (1, 'primair', 4, 2),
                        (2, 'secundair', 2, 27.2, 2),
                        (3, 'tertiare', 1.5, 27.2, 2)
                    """)
        con_legger.commit()

        messagebar_message('Aanmaken leggerdatabase',
                           'Aanmaken leggerdatabase is gelukt',
                           level=3,
                           duration=10)
コード例 #4
0
    def __init__(self, parent=None, iface=None, path_legger_db=None):
        """Constructor."""
        super(LeggerWidget, self).__init__(parent)

        # store arguments
        self.iface = iface
        self.path_legger_db = path_legger_db

        # init parameters
        self.measured_model = ProfileModel()
        self.variant_model = ProfileModel()
        self.legger_model = LeggerTreeModel()
        self.area_model = AreaTreeModel()

        if not path_legger_db:
            messagebar_message("Database selectie", "Selecteer eerst een legger database", level=1)
            raise Exception("Selecteer eerst een legger database")

        # create session (before setup_ui)
        db = LeggerDatabase(
            {'db_path': path_legger_db},
            'spatialite'
        )
        db.create_and_check_fields()
        self.session = db.get_session()
        # todo: request something to test connection and through error message otherwise
        hydro_object_count = self.session.query(HydroObject).count()

        if hydro_object_count == 0:
            messagebar_message("Database selectie", "Database bevat geen hydrovakken", level=1)
            raise Exception("Database bevat geen hydrovakken")

        # initial values
        self.selected_hydrovak = None
        self.active_begroeiings_variant = SHOW_ALL
        self.active_begroeiings_variant_strategy = None

        # setup ui
        self.setup_ui(self)

        self.legger_model.setTreeWidget(self.legger_tree_widget)
        self.area_model.setTreeWidget(self.startpoint_tree_widget)

        self.category_combo.insertItems(0, ['4', '3', '2', '1'])
        self.category_combo.setCurrentIndex(0)
        self.category_filter = 4

        self.begroeiings_varianten = OrderedDict(
            [(SHOW_ALL, 'all'), (PRE_SELECTED, 'pre_selected'), ] +
            [(v.naam, v) for v in self.session.query(BegroeiingsVariant)]
        )

        self.begroeiings_combo.insertItems(
            0, self.begroeiings_varianten.keys())

        self.begroeiings_variant_strategies = OrderedDict((
            ('alleen dit hydrovak', 'only_this_hydrovak'),
            ('alle bovenstroomse hydrovakken', 'all_upstream'),
        ))

        self.begroeiings_strategy_combo.insertItems(0, self.begroeiings_variant_strategies.keys())
        self.begroeiings_strategy_combo.setCurrentIndex(0)

        self.child_selection_strategies = OrderedDict((
            ('gekozen traject tot waarde', 'selected_branch_till_value'),
            ('gekozen traject tot eind', 'selected_branch_till_end'),
            ('alleen dit hydrovak', 'selected_hydrovak'),
            ('bovenstrooms (met zijtakken) tot waarde ', 'upstream_till_value'),
            ('bovenstrooms (met zijtakken) tot eind', 'upstream_till_end'),
        ))

        self.child_selection_strategy_combo.insertItems(0, self.child_selection_strategies.keys())
        self.child_selection_strategy_combo.setCurrentIndex(0)

        # create line layer and add to map
        self.layer_manager = LeggerMapManager(self.iface, self.path_legger_db)

        self.line_layer = self.layer_manager.get_line_layer(add_to_map=True)
        self.vl_tree_layer = self.layer_manager.get_virtual_tree_layer(add_to_map=True)
        self.vl_endpoint_layer = self.layer_manager.get_endpoint_layer(add_to_map=True)
        self.vl_track_layer = self.layer_manager.get_track_layer(add_to_map=True)
        self.vl_hover_layer = self.layer_manager.get_hover_layer(add_to_map=True)
        self.vl_selected_layer = self.layer_manager.get_selected_layer(add_to_map=True)
        self.vl_startpoint_hover_layer = self.layer_manager.get_hover_startpoint_layer(add_to_map=True)

        self.map_visualisation = LeggerMapVisualisation(
            self.iface, self.line_layer.crs())

        # init network
        line_direct = self.layer_manager.get_line_layer(geometry_col='line')
        field_nr = line_direct.fieldNameIndex('direction')
        director = QgsLineVectorLayerDirector(
            line_direct, field_nr, '2', '1', '3', 3)

        self.network = NewNetwork(
            line_direct, self.line_layer, director, None, self.vl_tree_layer, self.vl_endpoint_layer
        )

        # add listeners
        self.category_combo.currentIndexChanged.connect(self.category_change)
        self.variant_model.dataChanged.connect(self.data_changed_variant)
        self.legger_model.dataChanged.connect(self.data_changed_legger_tree)
        self.area_model.dataChanged.connect(self.data_changed_area_model)
        self.show_manual_input_button.clicked.connect(
            self.show_manual_input_window)
        self.next_endpoint_button.clicked.connect(
            self.set_next_endpoint)
        self.begroeiings_combo.currentIndexChanged.connect(self.onSelectBegroeiingsVariant)

        # self.begroeiings_strategy_combo.currentIndexChanged.connect(self.onSelectBegroeiingsVariantStrategy)

        # create and init startpoint (AreaTree) model
        def loop_over(parent, data):
            for child in data['children']:
                area = area_class(child)
                item = AreaTreeItem(area, parent)
                parent.appendChild(item)
                loop_over(item, child)

        # get startingpoints and select first
        sp_tree = self.network.get_start_arc_tree()

        root = AreaTreeItem(None, None)
        loop_over(root, sp_tree)
        self.area_model.setNewTree(root.childs)

        # initial, select first area
        first_area = root.child(0)
        self.area_model.setDataItemKey(first_area, 'selected', True)
コード例 #5
0
    def data_changed_variant(self, index):
        """
        changes during selection and hover of variant table

        index (QIndex): index of changed field
        """
        item = self.variant_model.rows[index.row()]
        if self.variant_model.columns[index.column()].name == 'active':
            if item.active.value:
                # only one selected at the time
                item.color.value = list(item.color.value)[:3] + [255]
                for row in self.variant_model.rows:
                    if row.active.value and row != item:
                        row.active.value = False

                depth = item.depth.value
                selected_variant_id = item.name.value
                traject = []

                if self.legger_model.ep:
                    traject = self.legger_model.ep.up(self.legger_model.selected)
                    traject.reverse()
                    if len(traject) > 0:
                        traject.pop(0)
                else:
                    messagebar_message(
                        'Traject nodig',
                        'Selecteer eerst een traject (sp en ep) voordat diepte kan worden doorgetrokken.',
                        1,
                        15)
                    return

                self.loop_tree(
                    self.legger_model.selected,
                    depth=depth,
                    initial=False,
                    variant_id=selected_variant_id,
                    begroeiingsvariant=self.get_begroeiings_variant(),
                    child_strategy=self.get_child_selection_strategy(),
                    begroeiings_strategy=self.get_begroeiings_strategy(),
                    traject_nodes=traject
                )
                self.session.commit()
                # trigger repaint of sideview
                self.sideview_widget.draw_selected_lines(self.sideview_widget._get_data())
            else:
                item.color.value = list(item.color.value)[:3] + [20]
                # trigger repaint of sideview
                self.sideview_widget.draw_selected_lines(self.sideview_widget._get_data())

        elif self.variant_model.columns[index.column()].name == 'hover':
            if item.hover.value:
                # only one selected at the time
                item.color.value = list(item.color.value)[:3] + [255]
                for row in self.variant_model.rows:
                    if row.hover.value and row != item:
                        row.hover.value = False

                depth = item.depth.value
                selected_variant_id = item.name.value
                traject = []
                self.legger_model.set_column_value('selected_depth_tmp', None)

                if self.legger_model.ep:
                    traject = self.legger_model.ep.up(self.legger_model.selected)
                    traject.reverse()
                    if len(traject) > 0:
                        traject.pop(0)

                else:
                    messagebar_message(
                        'Traject nodig',
                        'Selecteer eerst een traject (sp en ep) voordat diepte kan worden doorgetrokken.',
                        1,
                        15)
                    return

                hydrovakken = self.loop_tree(
                    self.legger_model.selected,
                    depth=depth,
                    initial=False,
                    hover=True,
                    variant_id=selected_variant_id,
                    begroeiingsvariant=self.get_begroeiings_variant(),
                    child_strategy=self.get_child_selection_strategy(),
                    begroeiings_strategy=self.get_begroeiings_strategy(),
                    traject_nodes=traject
                )

                # set map visualisation of selected hydrovakken
                self.network._virtual_tree_layer.setSubsetString(
                    '"hydro_id" in (\'{ids}\')'.format(
                        ids='\',\''.join([str(hydrovak.hydrovak['hydro_id']) for hydrovak in hydrovakken])))
                # trigger repaint of sideview
                self.sideview_widget.draw_selected_lines(self.sideview_widget._get_data())
            else:
                self.legger_model.set_column_value('selected_depth_tmp', None)
                # reset map visualisation
                self.network._virtual_tree_layer.setSubsetString('')
                # trigger repaint of sideview
                self.sideview_widget.draw_selected_lines(self.sideview_widget._get_data())