def sampleColorsFromRasterLayer(enquire_layer_name,raster_layer_name, fieldnames = [], blur = 0):
    """
    Gets the colors at the geometry vertices from layer 'raster_layer' with corresponding CRS.:param layer: The layer on which the polygons reside
    :type layer: QgsVectorLayer
    :param geometry: Geometry to find the containers of
    :type geometry: QgsGeometry
    :param crs: Coordinate Reference System for the given geometry
    :type crs: QgsCoordinateReferenceSystem
    :return: Found Containers
    :rtype: list
    """
    result = True
    enquire_layer = legend.nodeByName(enquire_layer_name)[0].layer()
    enquire_provider = enquire_layer.dataProvider()
    raster_layer = legend.nodeByName(raster_layer_name)[0].layer()
    testenquire = enquire_layer.getFeatures().next()
    field_keys = sampleColor(raster_layer, testenquire.geometry()).keys()
    if bool(fieldnames):
        field_keys = fieldnames[0:len(field_keys)]
    for nam in field_keys:
        if not str(nam) in [a.name() for a in enquire_layer.fields()]:
            enquire_provider.addAttributes([QgsField(str(nam), QVariant.String)])
    enquire_layer.updateFields()
    enquire_layer.startEditing()
    for enquirer in enquire_layer.getFeatures():
        color = sampleColor(raster_layer, enquirer.geometry(), enquire_layer.crs(), fieldnames = field_keys, blur = blur)
        result = result & all(co != NULL for co in color.values())
        for i in color.keys():
            enquirer[str(i)] = color[str(i)]
            enquire_layer.updateFeature(enquirer)
    enquire_layer.commitChanges()
def sampleDataFromVectorLayerByFeature(feature, data_layer_name, field_list=[] , feature_crs = None):
    """
        Gets data form surrounding Polygons on Data Layer for the geometries found on Enquire Layer.
        :param feature: Enquiring feature
        :type feature: QgsFeature
        :param data_layer_name: Name of the Data Layer shown QGIS Legend
        :type data_layer_name: string
        :param field_list: List of fields to get from surrounding polygons found on Data Layer
        :type field_list: list of strings
        :param feature_crs: Coordinate Reference System of the feature
        :type feature_crs: QgsCoordinateReferenceSystem
        :return: True/False depending on found data
        :rtype: boolean
        """
    result = True
    enquire_layer = legend.nodeByName(enquire_layer_name)[0].layer()
    enquire_provider = enquire_layer.dataProvider()
    data_layer = legend.nodeByName(data_layer_name)[0].layer()
    fieldnames = [j.name() for j in data_layer.pendingFields()]
    fieldnames =filter(lambda nam: nam in field_list, fieldnames)
    for nam in fieldnames:
        if not nam in [a.name() for a in enquire_layer.fields()]:
            enquire_provider.addAttributes([QgsField(nam, QVariant.String)])
    enquire_layer.updateFields()
    enquire_layer.startEditing()
    containers = sampleContainers(data_layer, feature.geometry(), feature_crs)
    result = None
    if bool(containers):
        container = containers[0]
        result =[]
        for nam in fieldnames:
            #print nam
            result.append({str(nam):container[str(nam)]})
    return result
def sampleDataFromVectorLayer(enquire_layer_name, data_layer_name, field_list=[]):
    """
        Gets data form surrounding Polygons on Data Layer for the geometries found on Enquire Layer.
        :param enquire_layer_name: Name of the Layer shown QGIS Legend on which the enquiring geometries reside
        :type enquire_layer_name: string
        :param data_layer_name: Name of the Data Layer shown QGIS Legend
        :type data_layer_name: string
        :param field_list: List of fields to get from surrounding polygons found on Data Layer
        :type field_list: list of strings
        :return: True/False depending on found data
        :rtype: boolean
        """
    result = True
    enquire_layer = legend.nodeByName(enquire_layer_name)[0].layer()
    enquire_provider = enquire_layer.dataProvider()
    data_layer = legend.nodeByName(data_layer_name)[0].layer()
    fieldnames = [j.name() for j in data_layer.pendingFields()]
    fieldnames =filter(lambda nam: nam in field_list, fieldnames)
    for nam in fieldnames:
        if not nam in [a.name() for a in enquire_layer.fields()]:
            enquire_provider.addAttributes([QgsField(nam, QVariant.String)])
    enquire_layer.updateFields()
    enquire_layer.startEditing()
    for enquirer in enquire_layer.getFeatures():
        containers = sampleContainers(data_layer, enquirer.geometry(), enquire_layer.crs())
        result = result & bool(containers)
        if bool(containers):
            container = containers[0]
            for nam in fieldnames:
                #print nam
                enquirer[str(nam)] = container[str(nam)]
                enquire_layer.updateFeature(enquirer)

    enquire_layer.commitChanges()
    return result
Exemple #4
0
def write_building_reports(bld_ids=[], reporttemplate=None):
    from mole.qgisinteraction import legend
    from mole.project import config
    from mole import oeq_global
    import os
    database = legend.nodeByName(config.data_layer_name)
    if not database:
        return None
    database = database[0]
    if not reporttemplate:
        reporttemplate = config.building_report_tpl
    tpl_path = os.path.join(oeq_global.OeQ_project_path(),
                            config.report_template_dir, reporttemplate)
    rep_path = os.path.join(oeq_global.OeQ_project_path(),
                            config.building_report_dir)
    th = open(tpl_path, 'r')
    template = th.read()
    th.close()
    building_list = database.layer().selectedFeatures()
    if not building_list:
        building_list = database.layer().getFeatures()
    output = []
    for building in building_list:
        if (not bld_ids) | (building[config.building_id_key] in bld_ids):
            tpl = template
            for field in [i.name() for i in database.layer().fields()]:
                tpl.replace('!!!' + field + '!!!', str(building[field]))
            rh = open(
                os.path.join(
                    rep_path,
                    "BLD_" + building[config.building_id_key] + '.html'), 'w')
            rh.write(tpl)
            rh.close()
            output.append(tpl)
    return output
def write_building_reports(bld_ids=[],reporttemplate=None):
    from mole.qgisinteraction import legend
    from mole.project import config
    from mole import oeq_global
    import os
    database=legend.nodeByName(config.data_layer_name)
    if not database:
        return None
    database = database[0]
    if not reporttemplate:
        reporttemplate=config.building_report_tpl
    tpl_path=os.path.join(oeq_global.OeQ_project_path(),config.report_template_dir,reporttemplate)
    rep_path=os.path.join(oeq_global.OeQ_project_path(),config.building_report_dir)
    th = open(tpl_path, 'r')
    template = th.read()
    th.close()
    building_list = database.layer().selectedFeatures()
    if not building_list:
        building_list = database.layer().getFeatures()
    output = []
    for building in building_list:
        if (not bld_ids) | (building[config.building_id_key] in bld_ids):
            tpl =template
            for field in [i.name() for i in database.layer().fields()]:
                tpl.replace('!!!'+field+'!!!',str(building[field]))
            rh=open(os.path.join(rep_path,"BLD_"+building[config.building_id_key]+'.html'),'w')
            rh.write(tpl)
            rh.close()
            output.append(tpl)
    return output
 def set_input_layer(self, layer_name):
     layernode = legend.nodeByName(layer_name, 'layer')
     if len(layernode) == 0:
         return None
     in_layer = self.pst_dialog.inSample
     #print in_layer
     index = in_layer.findText(layer_name)
     in_layer.setCurrentIndex(index)
 def set_input_layer(self, layer_name):
     layernode = legend.nodeByName(layer_name,'layer')
     if len(layernode) == 0:
         return None
     in_layer = self.pst_dialog.inSample
     #print in_layer
     index = in_layer.findText(layer_name)
     in_layer.setCurrentIndex(index)
def createCentroidLayer(polygon_layer_name, centroid_layer_name, forced=False):
    '''
    Create Polygon centroids that are reliably inside
    :param polygon_layer_name: Name of the polygon layer
    :type: string
    :param centroid_layer_name: Name of the new centroid layer
    :type: string
    :param forced: Force regeneration of centroids
    :type: boolean
    :return: Centroid Layer or None
    :rtype: QgsVectorLayer

    '''
    import os
    from mole import oeq_global
    from mole.project import config
    from mole.qgisinteraction import plugin_interaction,legend,layer_interaction
    # check if centroid layer exists
    if legend.nodeExists(centroid_layer_name):
        #force rebuild?
        if forced:
            #remove centroid layer
            legend.nodeRemove(centroid_layer_name,True)
        else:
            return legend.nodeByName(centroid_layer_name)[0].layer()
    # init plugin communication
    rci = plugin_interaction.RealCentroidInteraction(config.real_centroid_plugin_name)
    output = os.path.join(oeq_global.OeQ_project_path(), centroid_layer_name + '.shp')
    centroid_layer = rci.create_centroids(polygon_layer_name, output)
    if centroid_layer.isValid():
        layer_interaction.add_layer_to_registry(centroid_layer)
        polygon_layer = legend.nodeByName(polygon_layer_name)
        #if not failed
        if bool(polygon_layer):
            polygon_layer = polygon_layer[0].layer()
            rci.calculate_accuracy(polygon_layer, centroid_layer)
            layer_interaction.add_style_to_layer(config.valid_centroids_style, centroid_layer)
            legend.nodeByName(centroid_layer.name())[0].setExpanded(False)
            #source_section = self.progress_items_model.section_views[1]
            #section_model = source_section.model()
            #project_item = section_model.findItems("Load building coordinates")[0]
            #project_item.setCheckState(2)
            #time.sleep(0.1)
            #self.handle_load_raster_maps()
            return centroid_layer
    return None
def write_project_definitions_report():
    from qgis.core import QgsCoordinateReferenceSystem,QgsCoordinateTransform
    from mole.qgisinteraction import legend
    from mole.project import config
    from mole import oeq_global
    import os
    import webbrowser
    from cgi import escape
    from urllib import pathname2url
    tpl_path=os.path.join(oeq_global.OeQ_plugin_path(),config.report_template_dir,config.project_definitions_tpl)
    rep_path=os.path.join(oeq_global.OeQ_project_path(),config.report_dir,config.project_definitions_tpl)
    th = open(tpl_path, 'r')
    template = str(th.read())
    th.close()
    extend_node=legend.nodeByName(config.investigation_shape_layer_name)
    if not extend_node:
        return None
    extent=extend_node[0].layer().extent()
    #crsSrc=QgsCoordinateReferenceSystem(int(config.default_extent_crs.split(':')[-1]), QgsCoordinateReferenceSystem.EpsgCrsId)
        #crsDest=QgsCoordinateReferenceSystem(int(self.source_crs.split(':')[-1]), QgsCoordinateReferenceSystem.EpsgCrsId)
        ##transform extent
        #coord_transformer = QgsCoordinateTransform(crsSrc, crsDest)
        #extent = coord_transformer.transform(extent)
    p_info = oeq_global.OeQ_project_info
    project_info = {'PRJ_NAME':p_info['project_name'],
             'PRJ_DESCR':p_info['description'],
             'IAC_CTY':p_info['location_city'],
             'IAC_COD':p_info['location_postal'],
             'IAC_LON1':p_info['location_lon'],
             'IAC_LAT1':p_info['location_lat'],
             'IA_LONMIN':str(extent.xMinimum()),
             'IA_LONMAX':str(extent.xMaximum()),
             'IA_LATMIN':str(extent.yMinimum()),
             'IA_LATMAX':str(extent.xMaximum()),
             'IA_CRS':p_info['location_crs'],
             'PRJ_YOC':p_info['average_construction_year'],
             'PRJ_PDENS':p_info['population_density'],
             'PRJ_HDD':p_info['heating_degree_days']}
    for field in project_info.keys():
            print field
            print escape(project_info[field])
            template=template.replace('!!!'+field+'!!!',escape(project_info[field]))
    if not os.path.exists(os.path.join(oeq_global.OeQ_project_path(),config.report_dir)):
        os.makedirs(os.path.join(oeq_global.OeQ_project_path(),config.report_dir))
    print rep_path
    rh=open(rep_path,'w')
    print rep_path
    template=template.encode('utf8', 'replace')
    rh.write('"""'+template+'"""')
    rh.close()
    #print escape(rep_path)
    print rep_path
    webbrowser.open('file://' + os.path.realpath(rep_path),new=2)
    return template
Exemple #10
0
def getBuildingLocationDataByBLD_ID(building_id, crs=None):
    # In: BLD_ID
    #     Target Coordinate Reference System as EPSG Code
    # Out: dict of all informations delivered by googlemaps
    from mole.qgisinteraction import legend
    from mole.project import config
    layer = legend.nodeByName(config.building_coordinate_layer_name)
    if not layer: return None
    layer = layer[0].layer()
    layerEPSG=int(layer.crs().authid()[5:])
    provider=layer.dataProvider()
    building=filter(lambda x: x.attribute(config.building_id_key)==str(building_id), provider.getFeatures())
    if len(building)==0: return None
    geom = building[0].geometry()
    result = getBuildingLocationDataByCoordinates(geom.asPoint().x(), geom.asPoint().y(), layerEPSG)
    for i in result:
        i.update({'crs':crs.authid()})
    return result
Exemple #11
0
    def update_color_values(self):
        """
        Change the color-table view to display the color-map of the currently selected layer.
        :return:
        :rtype:
        """
        layer = self.layers_dropdown.currentText()
        color_map = {}
        if layer in self.color_entry_manager.layer_values_map:
            color_map = self.color_entry_manager.layer_values_map[layer]
            table_model = QColorTableModel(color_map, self.header, self)
        if not color_map:
            table_model = self.dummy_model
        self.color_table_view.setModel(table_model)
        self.recent_layer = layer

        try:
            wms_layer = legend.nodeByName(layer)[0].layer()
            url = wms_layer.legendUrl()
            self.legend_view.load(QtCore.QUrl(url))
        except (TypeError, AttributeError) as NoneTypeError:
            pass
Exemple #12
0
def save_wms_extent_as_image(wms_layer_name, max_res = 2064, geo_reference_output = True):

    export_wms_layer = legend.nodeByName(wms_layer_name)
    if not export_wms_layer: return None
    export_wms_layer = export_wms_layer[0].layer()
    iface = qgis.utils.iface
    canvas = iface.mapCanvas()

    current_crs = canvas.mapSettings().destinationCrs()
    current_extent = canvas.extent()
    export_extent = raster_layer_interaction.transform_wms_geo_data(export_wms_layer, current_extent, current_crs)

    #info_text = 'The current extent will now be clipped. This may take some time.'
    #QMessageBox.information(iface.mainWindow(), 'Info', info_text)
    if not geo_reference_output:
      export_wms_layer.setLayerName(export_wms_layer.name().replace("_RAW",""))

    filename = layer_interaction.save_layer_as_image(export_wms_layer, export_extent, OeQ_project_path(), max_res)

    if geo_reference_output:
         # wait until the file exists to add geo-references
        no_timeout = 30
        while not os.path.exists(filename) and no_timeout:
            time.sleep(0.1)
            no_timeout -= 1
        #dest_filename=os.path.splitext(filename)[0]
        dest_filename=filename.replace("_RAW","")
        #print filename
        #print dest_filename
        #dest_filename = os.path.splitext(filename)[0] + '_geo.tif'
        referencing = raster_layer_interaction.gdal_translate_layerfile(filename, dest_filename, current_crs.authid(), current_extent)

        if referencing != 0:
            print 'Error number {} occured, while referencing the output .tif'.format(referencing)
        else:
            #os.remove(filename)
            filename = dest_filename

    return filename
def write_project_definition_report(self,template):
    from mole.qgisinteraction import legend
    from mole.project import config
    from mole import oeq_global
    database=legend.nodeByName(config.data_layer_name)
    if not database:
        return None
    database = database[0]
    tpl_path=os.path.join(oeq_global.OeQ_project_path(),config.report_template_dir,config.building_report_tpl)
    th = open(tpl_path, 'r')
    template = th.read()
    th.close()
    building_list = database.layer().selectedFeatures()
    if not building_list:
        building_list = database.layer().getFeatures()
    output = []
    for building in building_list:
        tpl =template
        for field in [i.name() for i in database.layer().fields()]:
            tpl.replace('!!!'+field+'!!!',str(building[field]))
        output.append()
    return output
Exemple #14
0
def getBuildingLocationDataByBLD_ID(building_id, crs=None):
    # In: BLD_ID
    #     Target Coordinate Reference System as EPSG Code
    # Out: dict of all informations delivered by googlemaps
    from mole.qgisinteraction import legend
    from mole.project import config
    layer = legend.nodeByName(config.building_coordinate_layer_name)
    if not layer: return None
    layer = layer[0].layer()
    layerEPSG = int(layer.crs().authid()[5:])
    provider = layer.dataProvider()
    building = filter(
        lambda x: x.attribute(config.building_id_key) == str(building_id),
        provider.getFeatures())
    if len(building) == 0: return None
    geom = building[0].geometry()
    result = getBuildingLocationDataByCoordinates(geom.asPoint().x(),
                                                  geom.asPoint().y(),
                                                  layerEPSG)
    for i in result:
        i.update({'crs': crs.authid()})
    return result
def sampleColorFromRasterLayerByFeature(feature,raster_layer_name, fieldnames = [], feature_crs = None, blur = 0):
    """
    Gets the colors at the geometry vertices from layer 'raster_layer' with corresponding CRS.:param layer: The layer on which the polygons reside
    :type layer: QgsVectorLayer
    :param geometry: Geometry to find the containers of
    :type geometry: QgsGeometry
    :param crs: Coordinate Reference System for the given geometry
    :type crs: QgsCoordinateReferenceSystem
    :return: Found Containers
    :rtype: list
    """
    result = None
    raster_layer = legend.nodeByName(raster_layer_name)[0].layer()
    color = sampleColor(raster_layer, feature.geometry(), feature_crs)
    field_keys = [str(k) for k in range(1,len(color)+1)]
    #print field_keys
    if bool(fieldnames):
        field_keys = fieldnames[0:len(field_keys)]
        print
    color = sampleColor(raster_layer, feature.geometry(), feature_crs, fieldnames = field_keys, blur = blur)
    #print color
    return color
Exemple #16
0
    def update_color_values(self):
        """
        Change the color-table view to display the color-map of the currently selected layer.
        :return:
        :rtype:
        """
        layer = self.layers_dropdown.currentText()
        color_map = {}
        if layer in self.color_entry_manager.layer_values_map:
            color_map = self.color_entry_manager.layer_values_map[layer]
            table_model = QColorTableModel(color_map, self.header, self)
        if not color_map:
            table_model = self.dummy_model
        self.color_table_view.setModel(table_model)
        self.recent_layer = layer

        try:
            wms_layer = legend.nodeByName(layer)[0].layer()
            url = wms_layer.legendUrl()
            self.legend_view.load(QtCore.QUrl(url))
        except (TypeError, AttributeError) as NoneTypeError:
            pass
Exemple #17
0
def write_project_definition_report(self, template):
    from mole.qgisinteraction import legend
    from mole.project import config
    from mole import oeq_global
    database = legend.nodeByName(config.data_layer_name)
    if not database:
        return None
    database = database[0]
    tpl_path = os.path.join(oeq_global.OeQ_project_path(),
                            config.report_template_dir,
                            config.building_report_tpl)
    th = open(tpl_path, 'r')
    template = th.read()
    th.close()
    building_list = database.layer().selectedFeatures()
    if not building_list:
        building_list = database.layer().getFeatures()
    output = []
    for building in building_list:
        tpl = template
        for field in [i.name() for i in database.layer().fields()]:
            tpl.replace('!!!' + field + '!!!', str(building[field]))
        output.append()
    return output
Exemple #18
0
def write_project_definitions_report():
    from qgis.core import QgsCoordinateReferenceSystem, QgsCoordinateTransform
    from mole.qgisinteraction import legend
    from mole.project import config
    from mole import oeq_global
    import os
    import webbrowser
    from cgi import escape
    from urllib import pathname2url
    tpl_path = os.path.join(oeq_global.OeQ_plugin_path(),
                            config.report_template_dir,
                            config.project_definitions_tpl)
    rep_path = os.path.join(oeq_global.OeQ_project_path(), config.report_dir,
                            config.project_definitions_tpl)
    th = open(tpl_path, 'r')
    template = str(th.read())
    th.close()
    extend_node = legend.nodeByName(config.investigation_shape_layer_name)
    if not extend_node:
        return None
    extent = extend_node[0].layer().extent()
    #crsSrc=QgsCoordinateReferenceSystem(int(config.default_extent_crs.split(':')[-1]), QgsCoordinateReferenceSystem.EpsgCrsId)
    #crsDest=QgsCoordinateReferenceSystem(int(self.source_crs.split(':')[-1]), QgsCoordinateReferenceSystem.EpsgCrsId)
    ##transform extent
    #coord_transformer = QgsCoordinateTransform(crsSrc, crsDest)
    #extent = coord_transformer.transform(extent)
    p_info = oeq_global.OeQ_project_info
    project_info = {
        'PRJ_NAME': p_info['project_name'],
        'PRJ_DESCR': p_info['description'],
        'IAC_CTY': p_info['location_city'],
        'IAC_COD': p_info['location_postal'],
        'IAC_LON1': p_info['location_lon'],
        'IAC_LAT1': p_info['location_lat'],
        'IA_LONMIN': str(extent.xMinimum()),
        'IA_LONMAX': str(extent.xMaximum()),
        'IA_LATMIN': str(extent.yMinimum()),
        'IA_LATMAX': str(extent.xMaximum()),
        'IA_CRS': p_info['location_crs'],
        'PRJ_YOC': p_info['average_construction_year'],
        'PRJ_PDENS': p_info['population_density'],
        'PRJ_HDD': p_info['heating_degree_days']
    }
    for field in project_info.keys():
        print field
        print escape(project_info[field])
        template = template.replace('!!!' + field + '!!!',
                                    escape(project_info[field]))
    if not os.path.exists(
            os.path.join(oeq_global.OeQ_project_path(), config.report_dir)):
        os.makedirs(
            os.path.join(oeq_global.OeQ_project_path(), config.report_dir))
    print rep_path
    rh = open(rep_path, 'w')
    print rep_path
    template = template.encode('utf8', 'replace')
    rh.write('"""' + template + '"""')
    rh.close()
    #print escape(rep_path)
    print rep_path
    webbrowser.open('file://' + os.path.realpath(rep_path), new=2)
    return template