예제 #1
0
 def get_area_km2(self, to_sr, geom):
     if isinstance(geom, Point):
         ret = None
     else:
         geom = CreateGeometryFromWkb(geom.wkb)
         geom.AssignSpatialReference(self.sr)
         geom.TransformTo(to_sr)
         ret = geom.GetArea() * 1e-6
     return (ret)
예제 #2
0
    def project(self, projection):
        to_sr = projection.sr
        from_sr = self.spatial.projection.sr
        se = self.spatial.geom
        len_se = len(se)
        loads = wkb.loads

        for idx in range(len_se):
            geom = CreateGeometryFromWkb(se[idx].wkb)
            geom.AssignSpatialReference(from_sr)
            geom.TransformTo(to_sr)
            se[idx] = loads(geom.ExportToWkb())

        self.spatial.projection = projection
예제 #3
0
 def get_projected(self,to_sr):
     from_sr = self.sr
     se = self.selection_geometry
     len_se = len(se)
     loads = wkb.loads
     
     ret = [None]*len_se
     for idx in range(len_se):
         gc = deepcopy(se[idx])
         geom = CreateGeometryFromWkb(gc['geom'].wkb)
         geom.AssignSpatialReference(from_sr)
         geom.TransformTo(to_sr)
         gc['geom'] = loads(geom.ExportToWkb())
         ret[idx] = gc
     
     return(SelectionGeometry(ret,sr=to_sr))
예제 #4
0
    def ogr(self):
        if self._ogr is None:
            if self._wkb is None and self._wkt is not None:
                self._ogr = CreateGeometryFromWkt(self._wkt)
            else:
                # WKB is the fastest, so convert to WKB and then to OGR.
                self._ogr = CreateGeometryFromWkb(self.wkb)

        if self._ogr is None:
            raise GeometryNotValid("Invalid geometry WKB/WKT value!")

        return self._ogr
예제 #5
0
파일: dataset.py 프로젝트: imclab/ocgis
    def project(self,projection):
        ## projection is only valid if the geometry has not been loaded. this is
        ## to limit the number of spatial operations. this is primary to ensure
        ## any masks created during a subset are not destroyed in the geometry
        ## resetting process.
#        if self.spatial.vector._geom is not None:
#            raise(NotImplementedError('project is only valid before geometries have been loaded.'))
        
        if self.spatial.grid.is_bounded:
            raise(NotImplementedError)
        
        ## project the rows and columns
        row = self.spatial.grid.row.value
        new_row = np.empty_like(row)
        col = self.spatial.grid.column.value
        new_col = np.empty_like(col)
        sr = self.spatial.projection.sr
        to_sr = projection.sr
        for row_idx in range(row.shape[0]):
            row_value = row[row_idx]
            for col_idx in range(col.shape[0]):
                col_value = col[col_idx]
                pt = Point(col_value,row_value)
                geom = CreateGeometryFromWkb(pt.wkb)
                geom.AssignSpatialReference(sr)
                geom.TransformTo(to_sr)
                new_col[col_idx] = geom.GetX()
            new_row[row_idx] = geom.GetY()
            
        ## update the rows and columns
        self.spatial.grid.row.value = new_row
        self.spatial.grid.column.value = new_col
        ## update the projection
        self.spatial.projection = projection
        self.spatial.vector._geom = None
예제 #6
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()
예제 #7
0
    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()
예제 #8
0
    def write(self,geom_dict,path,sr=None):
        """Write a list of geometry dictionaries (similar to that returned by :func:`~ocgis.ShpCabinet.get_geoms`) to disk.
        
        :param geom_dict: The list of geometry dictionaries.
        :type geom_dict: list of dict
        :param path: The absolute path to the output file.
        :type path: str
        :param sr: The spatial reference for the output. Defaults to WGS84.
        :type sr: :class:`osgeo.osr.SpatialReference`
        :rtype: str path to output file.
        """
        
        from ocgis.conv.csv_ import OcgDialect
#        path = self.get_path()

        if sr is None:
            sr = osr.SpatialReference()
            sr.ImportFromEPSG(4326)
        
        dr = ogr.GetDriverByName('ESRI Shapefile')
        ds = dr.CreateDataSource(path)
        if ds is None:
            raise IOError('Could not create file on disk. Does it already exist?')
        
        arch = CreateGeometryFromWkb(geom_dict[0]['geom'].wkb)
        layer = ds.CreateLayer('lyr',srs=sr,geom_type=arch.GetGeometryType())
        headers = self.get_headers(geom_dict)
        
        build = True
        for dct,geom in self.get_converter_iterator(geom_dict):
            if build:
                csv_path = path.replace('.shp','.csv')
                csv_f = open(csv_path,'w')
                writer = csv.writer(csv_f,dialect=OcgDialect)
                writer.writerow(headers)
                
                ogr_fields = self._get_ogr_fields_(headers,dct)
                for of in ogr_fields:
                    layer.CreateField(of.ogr_field)
                    feature_def = layer.GetLayerDefn()
                build = False
            try:
                row = [dct[h.lower()] for h in headers]
            except KeyError:
                row = []
                for h in headers:
                    try:
                        x = dct[h]
                    except KeyError:
                        x = dct[h.lower()]
                    row.append(x)
            writer.writerow(row)
            feat = ogr.Feature(feature_def)
            for o in ogr_fields:
                args = [o.ogr_name,None]
                try:
                    args[1] = dct[o.ogr_name.lower()]
                except KeyError:
                    args[1] = dct[o.ogr_name]
#                args = [o.ogr_name,o.convert(dct[o.ogr_name.lower()])]
                try:
                    feat.SetField(*args)
                except NotImplementedError:
                    args[1] = str(args[1])
                    feat.SetField(*args)
            feat.SetGeometry(ogr.CreateGeometryFromWkb(geom.wkb))
            layer.CreateFeature(feat)
        
        ds = None
        csv_f.close()
        
        return(path)
예제 #9
0
파일: dataset.py 프로젝트: imclab/ocgis
 def get_iter_value(self,add_bounds=True,add_masked=True,value=None,
                    temporal_group=False):        
     ## check if the reference projection is different than the dataset
     if type(self.spatial.projection) != type(ocgis.env.REFERENCE_PROJECTION) and ocgis.env.WRITE_TO_REFERENCE_PROJECTION:
         project = True
         sr = self.spatial.projection.sr
         to_sr = ocgis.env.REFERENCE_PROJECTION.sr #@UndefinedVariable
     else:
         project = False
     
     ## if no external value to iterate over is passed, use the internal value
     if value is None:
         value = self.value
     
     ## reference the mask checker
     is_masked = np.ma.is_masked
     ## reference the value name
     _name_value = self._name_value
     ## reference the fill_value
     fill_value = constants.fill_value
     
     ## if iteration over the temporal groups is requested, reference the
     ## appropriate iterator.
     if temporal_group:
         time_iter = self.temporal.group.get_iter
     else:
         time_iter = self.temporal.get_iter
     
     if self.level is None:
         for (ridx,cidx),geom,gret in self.spatial.get_iter():
             if project:
                 geom = CreateGeometryFromWkb(geom.wkb)
                 geom.AssignSpatialReference(sr)
                 geom.TransformTo(to_sr)
                 geom = loads(geom.ExportToWkb())
             for tidx,tret in time_iter(add_bounds=add_bounds):
                 gret.update(tret)
                 gret['lid'] = None
                 gret['level'] = None
                 ref = value[tidx,0,ridx,cidx]
                 masked = is_masked(ref)
                 if add_masked and masked:
                     ref = fill_value
                 elif not add_masked and masked:
                     continue
                 gret[_name_value] = ref
                 yield(geom,gret)
     else:
         for (ridx,cidx),geom,gret in self.spatial.get_iter():
             if project:
                 geom = CreateGeometryFromWkb(geom.wkb)
                 geom.AssignSpatialReference(sr)
                 geom.TransformTo(to_sr)
                 geom = loads(geom.ExportToWkb())
             for lidx,lret in self.level.get_iter(add_bounds=add_bounds):
                 gret.update(lret)
                 for tidx,tret in time_iter(add_bounds=add_bounds):
                     gret.update(tret)
                     ref = value[tidx,lidx,ridx,cidx]
                     masked = is_masked(value)
                     if add_masked and masked:
                         ref = None
                     elif not add_masked and masked:
                         continue
                     gret[_name_value] = ref
                     yield(geom,gret)