Esempio n. 1
0
    def write(self, fpath, polygons, spatial_reference=None, driver_name=None):
        """ Convert SCHISM polygon YAML file to a shapefile

        Parameters
        ----------
        fpath: str
            output file name
        polygons: array of schism_polygon.SchismPolygon
            polygons to write
        spatial_reference: osgeo.osr.SpatialReference or proj4 string
            default: NAD83, UTM zone 10N, meter
        driver_name: osgeo.ogr Driver name
            default: ESRI Shapefile
        """
        if spatial_reference is None:
            # Not sure if this changed. it should be EPSG 26910 
            #spatial_reference = '+proj=utm +zone=10N +ellps=NAD83 +datum=NAD83 +units=m'
            spatial_reference= '+proj=utm +zone=10 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs'
        if isinstance(spatial_reference, str):
            spatial_reference_obj = SpatialReference()
            try:
                spatial_reference_obj.ImportFromProj4(spatial_reference)
            except:
                raise ValueError("spatial reference could not be created from string: {}".format(spatial_reference))
        elif isinstance(spatial_reference, SpatialReference):
            spatial_reference_obj = spatial_reference
        else:
            raise ValueError('Not support spatial_reference type')
        if driver_name is None:
            driver_name = 'ESRI Shapefile'
        driver = GetDriverByName(driver_name)
        if driver is None:
            print('%s is not available.' % driver_name)
            raise RuntimeError()
        datasource = driver.CreateDataSource(str(fpath))
        if datasource is None:
            raise RuntimeError("Cannot create a GIS file")
        layer = datasource.CreateLayer('layer',
                                       spatial_reference_obj,
                                       wkbPolygon)
        fields = ('name', 'type', 'attribute')
        for field in fields:
            layer.CreateField(FieldDefn(field))
        feature_defn = layer.GetLayerDefn()
        feature = Feature(feature_defn)
        for i, polygon in enumerate(polygons):
            feature.SetGeometry(CreateGeometryFromWkb(polygon.wkb))
            feature.SetField(0, polygon.name)
            feature.SetField(1, polygon.type)
            feature.SetField(2, polygon.attribute)
            layer.CreateFeature(feature)
        datasource.Destroy()
    def write(self,
              fpath,
              lines,
              spatial_reference=None,
              driver_name=None,
              **kwargs):
        """
            Parameters
            ----------
            fpath: str
                output file name
            lines: array of schism_linestring.LineString
                list of LineStrings
            spatial_reference: osgeo.osr.SpatialReference
            default: NAD83, UTM zone 10N, meter
        """
        # Boilerplate to create a SHP file
        if spatial_reference is None:
            spatial_reference = SpatialReference()
            spatial_reference.ImportFromProj4(
                '+proj=utm +zone=10N +ellps=NAD83 +datum=NAD83 +units=m')
        if driver_name is None:
            driver_name = 'ESRI Shapefile'
        driver = GetDriverByName(driver_name)
        if driver is None:
            print('%s is not available.' % driver_name)
            raise RuntimeError()
        datasource = driver.CreateDataSource(fpath)
        if datasource is None:
            raise RuntimeError("Cannot create a GIS file")
        layer = datasource.CreateLayer('layer', spatial_reference,
                                       wkbLineString)
        fields = []
        for l in lines:
            if l.prop is not None:
                for k in l.prop:
                    if k not in fields and k != 'coordinates':
                        fields.append(k)
        map(layer.CreateField, [FieldDefn(field) for field in fields])
        feature_defn = layer.GetLayerDefn()
        feature = Feature(feature_defn)

        for i, line in enumerate(lines):
            feature.SetGeometry(CreateGeometryFromWkb(line.wkb))
            for j, f in enumerate(fields):
                val = line.prop.get(f)
                if val is not None:
                    feature.SetField(j, val)
            layer.CreateFeature(feature)
        datasource.Destroy()
def write_foglio(foglio,
                 destination,
                 point_borders=False,
                 format_name='ESRI Shapefile'):

    cassini_soldener = ''
    #Imposto alcune variabile a seconda del codice_comune:
    #ATTENZIONE: Prima di modificare qui lo SRID controllare che su Postgres le tavole siano impostate adeguatamente nella tavola geometry_columns!!!
    #ATTENZIONE: se nella definizione della cassini_soldener si inseriscono dei valori fissi di x_0 e y_0 ricordarsi di definire successivamente la local_cassini_soldener in maniera adeguata, cioe' togliendo il riferimento al vettore shift_cassini prima definito. In pratica aggiungere il codice_comune nell'array del primo "if" (verso rigo 103...)
    if foglio['CODICE COMUNE'] == 'G087':
        cassini_soldener = '+proj=cass +lat_0=45.007336 +lon_0=7.53725 +x_0=%f +y_0=%f +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'B305':
        cassini_soldener = '+proj=cass +lat_0=45.067618 +lon_0=7.436827 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'I785':
        cassini_soldener = '+proj=cass +lat_0=37.267029 +lon_0=14.692473 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'G535':
        cassini_soldener = '+proj=cass +lat_0=44.759075 +lon_0=9.917936 +x_0=-15.5 +y_0=10.5 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'G476':
        cassini_soldener = '+proj=cass +lat_0=40.535328 +lon_0=15.324016 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'L380':
        cassini_soldener = '+proj=tmerc +lat_0=0 +lon_0=9 +k=0.9996 +x_0=1500000 +y_0=0 +ellps=intl +towgs84=-104.1,-49.1,-9.9,0.971,-2.917,0.714,-11.68 +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'I258':
        cassini_soldener = '+proj=cass +lat_0=45.099116 +lon_0=7.356182 +x_0=-1.5 +y_0=0.5 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'C261':
        cassini_soldener = '+proj=cass +lat_0=45.31413 +lon_0=9.502994 +x_0=1 +y_0=1 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'C722':
        cassini_soldener = "+proj=cass +lat_0=45.235812 +lon_0=7.602194 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs +wktext"
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'A484':
        cassini_soldener = '+proj=cass +lat_0=40.535328 +lon_0=15.324016 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'G793':
        cassini_soldener = '+proj=cass +lat_0=40.535328 +lon_0=15.324016 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'I089':
        cassini_soldener = '+proj=cass +lat_0=40.535328 +lon_0=15.324016 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'I143':
        cassini_soldener = '+proj=cass +lat_0=40.535328 +lon_0=15.324016 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'I307':
        cassini_soldener = '+proj=cass +lat_0=40.535328 +lon_0=15.324016 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'G226':
        cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'B266':
        cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'B868':
        cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'F618':
        cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'F625':
        cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'H683':
        cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'I410':
        cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'I451':
        cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'C370':
        cassini_soldener = '+proj=cass +lat_0=45.558239 +lon_0=10.76357 +x_0=+0.45 +y_0=-1.90 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'D292':
        cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs'
    target_srs = SpatialReference()
    try:
        target_srs.ImportFromEPSG(int(t_srs))
    except TypeError:
        raise
        target_srs.ImportFromProj4(t_srs)

    shifts = ((0., 0.), (0., 0.))
    shifts = comuni_shift.get(foglio['CODICE COMUNE'], shifts)
    shifts = comuni_shift.get(
        (foglio['CODICE COMUNE'], foglio['NUMERO FOGLIO']), shifts)

    shift_cassini, shift_gauss_boaga = shifts
    ##### Parte eventualmente da MODIFICARE:
    if foglio['CODICE COMUNE'] in [
            'G535', 'I258', 'L380', 'G476', 'C261', 'A484', 'B266', 'B868',
            'F618', 'F625', 'G226', 'G793', 'I307', 'I410', 'I451', 'D292',
            'I143', 'I089', 'H683', 'C722', 'B305', 'I785', 'C370'
    ]:
        local_cassini_soldener = cassini_soldener
    else:
        local_cassini_soldener = cassini_soldener % (-shift_cassini[0],
                                                     -shift_cassini[1])

    source_srs = SpatialReference()
    source_srs.ImportFromProj4(local_cassini_soldener)

    trasformation = CoordinateTransformation(source_srs, target_srs)

    f_comune = FieldDefn('COMUNE', OFTString)
    f_comune.SetWidth(4)
    f_foglio = FieldDefn('FOGLIO', OFTString)
    f_foglio.SetWidth(11)
    f_tipo = FieldDefn('tipo', OFTString)
    f_tipo.SetWidth(11)
    f_part = FieldDefn('PARTICELLA', OFTString)
    f_part.SetWidth(8)
    f_numero = FieldDefn('NUMERO', OFTString)
    f_part.SetWidth(8)
    f_dimensione = FieldDefn('DIMENSIONE', OFTInteger)
    f_area = FieldDefn('AREA', OFTInteger)
    f_angolo = FieldDefn('ANGOLO', OFTReal)
    f_pos_x = FieldDefn('POSIZIONEX', OFTReal)
    f_pos_y = FieldDefn('POSIZIONEY', OFTReal)
    f_interno_x = FieldDefn('P_INTERNOX', OFTReal)
    f_interno_y = FieldDefn('P_INTERNOY', OFTReal)
    f_simbolo = FieldDefn('SIMBOLO', OFTInteger)
    f_etichetta = FieldDefn('etichetta', OFTString)
    f_etichetta.SetWidth(32)
    f_testo = FieldDefn('TESTO', OFTString)
    f_testo.SetWidth(256)

    create_options = []
    if format_name == 'PostgreSQL':
        #Per passare i parametri del driver nella forma "parametro=valore". Sfortunatamente NON POSSO PASSARE "-APPEND"!!!!
        #vedi anche: http://www.gdal.org/gdal_tutorial.html
        papszOptions = ['OVERWRITE=yes']
    elif format_name == 'SQLite':  #IN SVILUPPO!
        #per maggiori info vedere: http://www.gdal.org/drv_sqlite.html
        create_options = [
            'SPATIALITE=YES', 'INIT_WITH_EPSG=YES',
            'OGR_SQLITE_SYNCHRONOUS=OFF', 'OVERWRITE=yes'
        ]
        #l'opzione Overwrite sul DB non funziona: ho messo una IF oltre
        papszOptions = ['FORMAT=SPATIALITE', 'OVERWRITE=yes']  #default
    else:
        papszOptions = []

    if (format_name == 'SQLite') and (os.path.exists(destination)):
        ds = GetDriverByName(format_name).Open(destination, update=1)
    #Pensavo in questo modo di ovviare all'errore che mi restituisce lo script nel caso di DB:
    #ERROR 1: PostgreSQL driver doesn't currently support database creation. Please create database with the `createdb' command.
    #ma non ho risolto niente... Invece aggiungendo "PG:" il plugin genera le tabelle!
    elif (format_name == 'PostgreSQL'):
        #    ds = GetDriverByName(format_name).Open(destination)
        #destination = "PG:%s" % (destination)
        ds = GetDriverByName(format_name).CreateDataSource(
            destination, options=create_options)
    else:
        ds = GetDriverByName(format_name).CreateDataSource(
            destination, options=create_options)
    #per evitare sovrascritture aggiungo anche l'allegato
    pedice = "%s_%s_%s_%s" % (foglio['CODICE COMUNE'], foglio['NUMERO FOGLIO'],
                              foglio['CODICE ALLEGATO'],
                              foglio['CODICE SVILUPPO'])

    #PLUGIN QGIS:
    #Decodifico alcuni campi in modo tale che vengano riconosciuti corretti anche dalle librerie interne di QGis:
    comune_decode = remove_accents(foglio['CODICE COMUNE'])
    #oppure potrebbe essere:
    #comune_decode = foglio['CODICE COMUNE'].encode('utf-8')
    codice_foglioXX = foglio['CODICE FOGLIO'][5:
                                              9]  #cosi' dovrebbe essere "0036"
    foglio_intero = int(codice_foglioXX.lstrip('0'))

    # tipo BORDO
    #bordi = ds.CreateLayer('CATASTO_BORDI', target_srs, wkbPolygon)
    nome_layer_not_utf = "CATASTO_BORDI_%s" % (pedice)
    nome_layer = nome_layer_not_utf.encode('utf-8')  #serve per plugin QGis
    bordi = ds.CreateLayer(nome_layer, target_srs, wkbPolygon25D, papszOptions)

    bordi.CreateField(f_comune)
    bordi.CreateField(f_foglio)
    bordi.CreateField(f_tipo)
    bordi.CreateField(f_part)
    bordi.CreateField(f_dimensione)
    bordi.CreateField(f_angolo)
    bordi.CreateField(f_pos_x)
    bordi.CreateField(f_pos_y)
    bordi.CreateField(f_interno_x)
    bordi.CreateField(f_interno_y)
    bordi.CreateField(f_area)
    bordi.CreateField(f_etichetta)

    for oggetto in foglio['oggetti']['BORDO']:
        poly = Geometry(wkbPolygon)
        tabisole = map(int, oggetto['TABISOLE'])

        # contorno esterno
        vertici_contorno = int(oggetto['NUMEROVERTICI']) - sum(tabisole)
        ring = Geometry(wkbLinearRing)
        for vertice in range(vertici_contorno):
            x, y = map(float, oggetto['VERTICI'][vertice])
            if True:
                x, y = trasformation.TransformPoint(x, y)[:2]
            ring.AddPoint(x + shift_gauss_boaga[0], y + shift_gauss_boaga[1])
        ring.CloseRings()
        poly.AddGeometry(ring)

        # isole
        for isola in range(int(oggetto['NUMEROISOLE'])):
            ring = Geometry(wkbLinearRing)
            for vertice in range(vertice + 1, vertice + 1 + tabisole[isola]):
                x, y = map(float, oggetto['VERTICI'][vertice])
                if True:
                    x, y = trasformation.TransformPoint(x, y)[:2]
                ring.AddPoint(x + shift_gauss_boaga[0],
                              y + shift_gauss_boaga[1])
            ring.CloseRings()
            poly.AddGeometry(ring)

        etichetta = oggetto['CODICE IDENTIFICATIVO']
        if oggetto['CODICE IDENTIFICATIVO'][-1] == '+':
            etichetta = ''

        feat = Feature(bordi.GetLayerDefn())
        feat.SetField('COMUNE',
                      comune_decode)  #plugin in QGis necessita di decodifica
        #codice_foglioXX = foglio['CODICE FOGLIO'][5:9] #cosi' dovrebbe essere "0036"
        #feat.SetField('FOGLIO', codice_foglioXX.lstrip('0'))
        feat.SetField('FOGLIO',
                      foglio_intero)  #plugin in QGis necessita di decodifica
        feat.SetField('tipo', oggetto['tipo'])
        #feat.SetField('PARTICELLA', oggetto['CODICE IDENTIFICATIVO']) #voglio togliere il "+"
        feat.SetField('PARTICELLA',
                      oggetto['CODICE IDENTIFICATIVO'].rstrip('+'))
        feat.SetField('DIMENSIONE', int(oggetto['DIMENSIONE']))
        feat.SetField('ANGOLO', float(oggetto['ANGOLO']))
        pos_x, pos_y = map(float,
                           (oggetto['POSIZIONEX'], oggetto['POSIZIONEY']))
        interno_x, interno_y = map(
            float, (oggetto['PUNTOINTERNOX'], oggetto['PUNTOINTERNOY']))
        if True:
            pos_x, pos_y = trasformation.TransformPoint(pos_x, pos_y)[:2]
            interno_x, interno_y = trasformation.TransformPoint(
                interno_x, interno_y)[:2]
        feat.SetField('POSIZIONEX', pos_x + shift_gauss_boaga[0])
        feat.SetField('POSIZIONEY', pos_y + shift_gauss_boaga[1])
        feat.SetField('P_INTERNOX', interno_x + shift_gauss_boaga[0])
        feat.SetField('P_INTERNOY', interno_y + shift_gauss_boaga[1])
        feat.SetField('AREA', oggetto.get('AREA', -1))
        feat.SetField('etichetta', etichetta.encode('utf-8'))
        feat.SetGeometry(poly)
        bordi.CreateFeature(feat)
        feat.Destroy()

    if point_borders:
        # tipo BORDO_PUNTO
        #bordi = ds.CreateLayer('CATASTO_PARTICELLE', target_srs, wkbPoint)
        #nome_layer = "CATASTO_PARTICELLE_%s" % (pedice)
        nome_layer_not_utf = "CATASTO_PARTICELLE_%s" % (pedice)
        nome_layer = nome_layer_not_utf.encode('utf-8')  #serve per plugin QGis
        bordi = ds.CreateLayer(nome_layer, target_srs, wkbPoint, papszOptions)

        bordi.CreateField(f_comune)
        bordi.CreateField(f_foglio)
        bordi.CreateField(f_tipo)
        bordi.CreateField(f_part)
        bordi.CreateField(f_dimensione)
        bordi.CreateField(f_angolo)
        bordi.CreateField(f_area)
        bordi.CreateField(f_etichetta)

        for oggetto in foglio['oggetti']['BORDO']:
            etichetta = oggetto['CODICE IDENTIFICATIVO']
            if oggetto['CODICE IDENTIFICATIVO'][-1] == '+':
                etichetta = ''

            feat = Feature(bordi.GetLayerDefn())
            #feat.SetField('COMUNE', foglio['CODICE COMUNE'])
            feat.SetField(
                'COMUNE',
                comune_decode)  #plugin in QGis necessita di decodifica
            #feat.SetField('FOGLIO', foglio['CODICE FOGLIO'])
            feat.SetField(
                'FOGLIO',
                foglio_intero)  #plugin in QGis necessita di decodifica
            feat.SetField('tipo', oggetto['tipo'])
            feat.SetField('PARTICELLA', oggetto['CODICE IDENTIFICATIVO'])
            feat.SetField('DIMENSIONE', int(oggetto['DIMENSIONE']))
            feat.SetField('ANGOLO', float(oggetto['ANGOLO']))
            pos_x, pos_y = map(
                float, (oggetto['PUNTOINTERNOX'], oggetto['PUNTOINTERNOY']))
            if True:
                pos_x, pos_y = trasformation.TransformPoint(pos_x, pos_y)[:2]
            feat.SetField('AREA', oggetto.get('AREA', -1))
            feat.SetField('etichetta', etichetta.encode('utf-8'))
            pt = Geometry(wkbPoint)
            pt.SetPoint_2D(0, pos_x + shift_gauss_boaga[0],
                           pos_y + shift_gauss_boaga[1])
            feat.SetGeometry(pt)
            bordi.CreateFeature(feat)
            feat.Destroy()

    # tipo TESTO
    #testi = ds.CreateLayer('CATASTO_TESTI', target_srs, wkbPoint)
    #nome_layer = "CATASTO_TESTI_%s" % (pedice)
    nome_layer_not_utf = "CATASTO_TESTI_%s" % (pedice)
    nome_layer = nome_layer_not_utf.encode('utf-8')  #serve per plugin QGis
    testi = ds.CreateLayer(nome_layer, target_srs, wkbPoint, papszOptions)

    testi.CreateField(f_comune)
    testi.CreateField(f_foglio)
    testi.CreateField(f_testo)
    testi.CreateField(f_dimensione)
    testi.CreateField(f_angolo)
    testi.CreateField(f_etichetta)

    for oggetto in foglio['oggetti']['TESTO']:
        x, y = map(float, (oggetto['POSIZIONEX'], oggetto['POSIZIONEY']))
        if True:
            x, y = trasformation.TransformPoint(x, y)[:2]
        # FIXME: many texts are useless, prun them from etichetta
        etichetta = remove_accents(oggetto['TESTO'])

        feat = Feature(testi.GetLayerDefn())
        #feat.SetField('COMUNE', foglio['CODICE COMUNE'])
        feat.SetField('COMUNE',
                      comune_decode)  #plugin in QGis necessita di decodifica
        #feat.SetField('FOGLIO', foglio['CODICE FOGLIO'])
        feat.SetField('FOGLIO',
                      foglio_intero)  #plugin in QGis necessita di decodifica
        #feat.SetField('TESTO', oggetto['TESTO'])
        feat.SetField('TESTO', etichetta)
        feat.SetField('DIMENSIONE', int(oggetto['DIMENSIONE']))
        feat.SetField('ANGOLO', float(oggetto['ANGOLO']))
        feat.SetField('etichetta', etichetta.encode('utf-8'))
        pt = Geometry(wkbPoint)
        pt.SetPoint_2D(0, x + shift_gauss_boaga[0], y + shift_gauss_boaga[1])
        feat.SetGeometry(pt)
        testi.CreateFeature(feat)

    # tipo SIMBOLO
    #simboli = ds.CreateLayer('CATASTO_SIMBOLI', target_srs, wkbPoint)
    #nome_layer = "CATASTO_SIMBOLI_%s" % (pedice)
    nome_layer_not_utf = "CATASTO_SIMBOLI_%s" % (pedice)
    nome_layer = nome_layer_not_utf.encode('utf-8')  #serve per plugin QGis
    simboli = ds.CreateLayer(nome_layer, target_srs, wkbPoint, papszOptions)

    simboli.CreateField(f_comune)
    simboli.CreateField(f_foglio)
    simboli.CreateField(f_simbolo)
    simboli.CreateField(f_angolo)

    for oggetto in foglio['oggetti']['SIMBOLO']:
        x, y = map(float, (oggetto['POSIZIONEX'], oggetto['POSIZIONEY']))
        if True:
            x, y = trasformation.TransformPoint(x, y)[:2]

        feat = Feature(simboli.GetLayerDefn())
        #feat.SetField('COMUNE', foglio['CODICE COMUNE'])
        feat.SetField('COMUNE',
                      comune_decode)  #plugin in QGis necessita di decodifica
        #feat.SetField('FOGLIO', foglio['CODICE FOGLIO'])
        feat.SetField('FOGLIO',
                      foglio_intero)  #plugin in QGis necessita di decodifica
        feat.SetField('SIMBOLO', oggetto['CODICE SIMBOLO'])
        feat.SetField('ANGOLO', float(oggetto['ANGOLO']))
        pt = Geometry(wkbPoint)
        pt.SetPoint_2D(0, x + shift_gauss_boaga[0], y + shift_gauss_boaga[1])
        feat.SetGeometry(pt)
        simboli.CreateFeature(feat)

    # tipo FIDUCIALE
    #fiduciali = ds.CreateLayer('CATASTO_FIDUCIALI', target_srs, wkbPoint)
    #nome_layer = "CATASTO_FIDUCIALI_%s" % (pedice)
    nome_layer_not_utf = "CATASTO_FIDUCIALI_%s" % (pedice)
    nome_layer = nome_layer_not_utf.encode('utf-8')  #serve per plugin QGis
    fiduciali = ds.CreateLayer(nome_layer, target_srs, wkbPoint, papszOptions)

    fiduciali.CreateField(f_comune)
    fiduciali.CreateField(f_foglio)
    fiduciali.CreateField(f_numero)
    fiduciali.CreateField(f_simbolo)
    fiduciali.CreateField(f_pos_x)
    fiduciali.CreateField(f_pos_y)
    fiduciali.CreateField(f_etichetta)

    print 'corrections', shift_cassini, shift_gauss_boaga
    for oggetto in foglio['oggetti']['FIDUCIALE']:
        x, y = map(float, (oggetto['POSIZIONEX'], oggetto['POSIZIONEY']))
        pos_x, pos_y = map(float, (oggetto['PUNTORAPPRESENTAZIONEX'],
                                   oggetto['PUNTORAPPRESENTAZIONEY']))
        if True:
            x, y = trasformation.TransformPoint(x, y)[:2]
            pos_x, pos_y = trasformation.TransformPoint(pos_x, pos_y)[:2]
        etichetta = 'PF%02d/%s%s/%s' % (int(oggetto['NUMERO IDENTIFICATIVO']),
                                        foglio['CODICE NUMERO FOGLIO'][1:],
                                        foglio['CODICE ALLEGATO'],
                                        foglio['CODICE COMUNE'])

        feat = Feature(fiduciali.GetLayerDefn())
        #feat.SetField('COMUNE', foglio['CODICE COMUNE'])
        feat.SetField('COMUNE',
                      comune_decode)  #plugin in QGis necessita di decodifica
        #feat.SetField('FOGLIO', foglio['CODICE FOGLIO'])
        feat.SetField('FOGLIO',
                      foglio_intero)  #plugin in QGis necessita di decodifica
        feat.SetField('NUMERO', oggetto['NUMERO IDENTIFICATIVO'])
        feat.SetField('SIMBOLO', oggetto['CODICE SIMBOLO'])
        feat.SetField('POSIZIONEX', pos_x + shift_gauss_boaga[0])
        feat.SetField('POSIZIONEY', pos_y + shift_gauss_boaga[1])
        feat.SetField('etichetta', etichetta.encode('utf-8'))
        pt = Geometry(wkbPoint)
        pt.SetPoint_2D(0, x + shift_gauss_boaga[0], y + shift_gauss_boaga[1])
        feat.SetGeometry(pt)
        fiduciali.CreateFeature(feat)

        print etichetta, oggetto['CODICE SIMBOLO'], \
            float(oggetto['POSIZIONEX']) + shift_cassini[0], float(oggetto['POSIZIONEY']) + shift_cassini[1], \
            x + shift_gauss_boaga[0], y + shift_gauss_boaga[1]

    # tipo LINEA
    #linee = ds.CreateLayer('CATASTO_LINEE', target_srs, wkbLineString)
    #nome_layer = "CATASTO_LINEE_%s" % (pedice)
    nome_layer_not_utf = "CATASTO_LINEE_%s" % (pedice)
    nome_layer = nome_layer_not_utf.encode('utf-8')  #serve per plugin QGis
    linee = ds.CreateLayer(nome_layer, target_srs, wkbLineString25D,
                           papszOptions)

    linee.CreateField(f_comune)
    linee.CreateField(f_foglio)
    linee.CreateField(f_simbolo)

    for oggetto in foglio['oggetti']['LINEA']:
        # contorno esterno
        vertici = int(oggetto['NUMEROVERTICI'])
        linea = Geometry(wkbLineString)
        for vertice in range(vertici):
            x, y = map(float, oggetto['VERTICI'][vertice])
            if True:
                x, y = trasformation.TransformPoint(x, y)[:2]
            linea.AddPoint(x + shift_gauss_boaga[0], y + shift_gauss_boaga[1])

        feat = Feature(linee.GetLayerDefn())
        #feat.SetField('COMUNE', foglio['CODICE COMUNE'])
        feat.SetField('COMUNE',
                      comune_decode)  #plugin in QGis necessita di decodifica
        #feat.SetField('FOGLIO', foglio['CODICE FOGLIO'])
        feat.SetField('FOGLIO',
                      foglio_intero)  #plugin in QGis necessita di decodifica
        feat.SetField('SIMBOLO', oggetto['CODICE TIPO DI TRATTO'])
        feat.SetGeometry(linea)
        linee.CreateFeature(feat)
        feat.Destroy()

    ds.Destroy()
Esempio n. 4
0
    def create_field(self,
                     field_name: str,
                     field_type: int = None,
                     field_def: ogr.FieldDefn = None):
        """Remove and then re-add a field to a feature class

        Args:
            field_name (str): Name of the attribute field to be created
            field_type (int, optional): ogr type to use. Defaults to None. OR
            field_def (ogr.FieldDefn, optional): [description]. Defaults to None.

        Raises:
            VectorBaseException: [description]
            VectorBaseException: [description]
            VectorBaseException: [description]

        Returns:
            [type]: [description]
        """
        if self.ogr_layer is None:
            raise VectorBaseException('No open layer to create fields on')

        # XOR (^) check to make sure only one of field_type or field_def are provided
        elif not (field_type is not None) ^ (field_def is not None):
            raise VectorBaseException(
                'create_field must have EITHER field_type or field_def as an input'
            )

        elif not field_name or len(field_name) < 1:
            raise VectorBaseException(
                'Attempting to create field with invalid field name "{}".'.
                format(field_name))

        elif self.driver_name == VectorBase.Drivers.Shapefile.value and len(
                field_name) > 10:
            raise VectorBaseException(
                'Field names in shapefiles cannot be greater than 10 characters. "{}" == {}.'
                .format(field_name, len(field_name)))

        elif self.driver_name == VectorBase.Drivers.Geopackage.value and len(
                field_name) > 31:
            raise VectorBaseException(
                'Field names in geopackages cannot be greater than 31 characters. "{}" == {}.'
                .format(field_name, len(field_name)))

        elif self.driver_name == VectorBase.Drivers.GeoDatabase.value:
            raise VectorBaseException('Cannot create fields in a Geodatabase')

        elif field_type is not None and field_type == ogr.OFTInteger64:
            self.log.error(
                'ERROR:: ogr.OFTInteger64 is not supported by ESRI!')

        if field_def is None:
            field_def = ogr.FieldDefn(field_name, field_type)

        # Delete output column from vector layer if it exists and then recreate it
        for fieldidx in range(0, self.ogr_layer_def.GetFieldCount()):
            old_def = self.ogr_layer_def.GetFieldDefn(fieldidx)
            if old_def.GetName() == field_def.GetName():
                if old_def.GetType() != field_def.GetType():
                    raise VectorBaseException(
                        "Field already exists but types do not match: NEW: {} vs. OLD: {}"
                        .format(old_def.GetTypeName(),
                                field_def.GetTypeName()))
                self.log.info('Field "{}" already exists.'.format(field_name))
                return old_def

        self.log.info(
            'Creating output field "{}" in layer.'.format(field_name))

        # Good precision convention for Real floating point values
        if field_type is not None and field_type == ogr.OFTReal:
            field_def.SetPrecision(10)
            field_def.SetWidth(18)

        self.ogr_layer.CreateField(field_def)
        return field_def