Duplication of layers and memory use

Duplication of layers and memory use#

One cool thing - and needed for this week’s assignment - is the use of the memory. The basic idea is to not create a physical file on your hard disc, as we showed in the chapter where we generated new vector files. Instead, we can use the RAM of our computer. In our opinion, this has two key advantages: (1) Read/write operations will be much faster, as the RAM is able to operate faster than the disc space; (2) Often, we want to create only temporary files, which we do not need later on in the process. Creating these types of files inside memory does not require us to clean-up after processing.

Below, you can find some basic code examples on how to work with vector files in memory. First, let’ call again the necessary libraries, and define the drivers. What I commonly do is to define both types of drivers, namely ESRI Shapefile and memory.

from osgeo import ogr, osr
drvMemV = ogr.GetDriverByName('memory')
drvV = ogr.GetDriverByName('ESRI Shapefile')

Now, if we want to create a file in memory, we use the same syntax as for the “real” vector file, but we provide an empty string "" as argument. We afterwards define spatial referenc, features, geometries etc. as in the general example

memDS = drvMemV.CreateDataSource('')
srs = osr.SpatialReference()
srs.ImportFromEPSG(4326)
0
memLYR = memDS.CreateLayer("", srs, geom_type=ogr.wkbPolygon) 
idField = ogr.FieldDefn("id", ogr.OFTInteger)
memLYR.CreateField(idField)
defn = memLYR.GetLayerDefn() # needed to create the new features in the next step
# Definition of a random starting coordinate
x = 13.356061147056309
y = 52.50885105569029
# Definition of a random step size
step = 0.05
# Build the geometry and the feature
polFeat = ogr.Feature(defn)
polFeat.SetField("id", 1)
ring = ogr.Geometry(ogr.wkbLinearRing)
ring.AddPoint(x, y)
ring.AddPoint(x+step, y)
ring.AddPoint(x+step, y-step)
ring.AddPoint(x, y-step)
ring.AddPoint(x, y)
poly = ogr.Geometry(ogr.wkbPolygon)
poly.AddGeometry(ring)
polFeat.SetGeometry(poly)
memLYR.CreateFeature(polFeat)
memLYR.GetFeatureCount()

And that is it. Pretty simple - yet very powerful! Now, what you can obviously think of, is to copy vector files from memory to disc and vice versa. Below you can find two functions on how to do it. Have a look at them and try to understand the logic behind them.

def SHP_memToDisc(shape, outpath):
    outSHP = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource(outpath)
    lyr = shape.GetLayer()
    outSHP.CopyLayer(lyr, 'lyr')
def SHP_discToMem(inpath):
    drvMemV = ogr.GetDriverByName('Memory')
    f_open = drvMemV.CopyDataSource(ogr.Open(inpath),'')
    return f_open