mtdUtils.py 26.67 KiB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
# Various python tools for geospatial data manipulations
import csv
import datetime
import math
import os
import random
import string
import subprocess
import sys
import uuid
import time

import gdal
import numpy as np
import ogr
import osr

NP2GDAL = {
    "uint8": 1,
    "int8": 1,
    "uint16": 2,
    "int16": 3,
    "uint32": 4,
    "int32": 5,
    "float32": 6,
    "float64": 6
}

def periodic_date_generator(filename, start_date, end_date, step):
    start_date = start_date.split('-')
    start_date = datetime.datetime(int(start_date[0]),int(start_date[1]),int(start_date[2]))
    end_date = end_date.split('-')
    end_date = datetime.datetime(int(end_date[0]),int(end_date[1]),int(end_date[2]))
    d = start_date
    step = datetime.timedelta(days=step)
    with open(filename, 'w') as f:
        while d < end_date :
            f.write(d.strftime('%Y%m%d')+'\n')
            d += step

def dateYMDtoYJ(date):
    dt = datetime.datetime.strptime(date, '%Y%m%d')
    tt = dt.timetuple()
    return '%d%03d' % (tt.tm_year, tt.tm_yday)


def getShapefileExtent_WGS84(inShp):
    """ getShapefileExtent_WGS84(inShp)
    Returns shapefile extent in WGS84 geographic coordinates
    (useful for quering data from various providers based on lon/lat extents)

    INPUT	: 	inShp	-	a shapefile

    OUTPUT	: 	[lonmin, latmin, lonmax, latmax]
    """
    driver = ogr.GetDriverByName('ESRI Shapefile')
    dataset = driver.Open(inShp)
    extent = dataset.GetLayer().GetExtent()
    inRef = dataset.GetLayer().GetSpatialRef()
    outRef = osr.SpatialReference()
    outRef.ImportFromEPSG(4326)
    ct = osr.CoordinateTransformation(inRef, outRef)

    points = [0, 0, 0, 0]
    point = ogr.Geometry(ogr.wkbPoint)
    point.AddPoint(extent[0], extent[2])
    point.Transform(ct)
    points[0], points[1] = point.GetX(), point.GetY()
    point.AddPoint(extent[1], extent[3])
    point.Transform(ct)
    points[2], points[3] = point.GetX(), point.GetY()

    return points


def createOverlappingTIFF(fn, ref, bands=None, type=None):
    """ createOverlappingTIFF(fn, bands, type, ref)
    Create a GTIFF  raster dataset via GDAL replicating
    the extent and resolution of a reference dataset.

    INPUT	:	fn 		-	the file name for the output dataset
                ref		-	reference GDALDataset object
                bands 	-	number of bands for the output dataset
                type	-	data type  for the output dataset

    OUTPUT	: 	the overlapping GDALDataset object
    """
    GeoT = ref.GetGeoTransform()
    Proj = ref.GetProjection()
    dr = gdal.GetDriverByName("GTiff")
    if bands is None:
        bands = ref.RasterCount
    if type is None:
        type = ref.GetRasterBand(1).DataType
    out = dr.Create(fn, ref.RasterXSize, ref.RasterYSize, bands, type)
    out.SetGeoTransform(GeoT)
    out.SetProjection(Proj)

    return out


def bandToArray(band, subset=None):
    """ bandToArray(band)
    Extracts data from a band of a raster GDALDataset
    (issued by gdal.GetRasterBand) into a 2-D numpy array.

    INPUT	:	band 	-	the GDAL band object
                subset	-	optional, read from a subset [row_start, row_size, col_start, col_size]

    OUTPUT	: 	a numpy array (float by default)
    """
    if subset is None:
        ss = [0, 0, band.XSize, band.YSize]
    else:
        ss = [subset[1], subset[0], subset[3], subset[2]]
    """
    pack_types = ['x','B','H','h','I','i','f','d'];
    typ = pack_types[band.DataType]
    scan = band.ReadRaster(ss[0],ss[1],ss[2],ss[3])
    out = np.array(struct.unpack(typ * ss[2] * ss[3],scan))
    out = np.reshape(out,[ss[3],ss[2]])
    scan = None
    """
    out = band.ReadAsArray(ss[0], ss[1], ss[2], ss[3])

    return out


def arrayToBand(band, arr, start=None):
    """ arrayToBand(band,arr)
    Copies data from a 2-D numpy array to a band
    of a raster GDALDataset (issued by gdal.GetRasterBand)
    automatically converting array data to the band datatype.

    INPUT	:	band 	-	the destination GDAL band object
                arr		-	the numpy array to copy
                subset	-	optional, write onto a subset starting at [row_start, col_start]

    OUTPUT	: 	0
    """
    """
    if start is None:
        ss = [0,0,band.XSize,band.YSize]
    else:
        ss = [start[1], start[0], arr.shape[1], arr.shape[0]]
    pack_types = [None, np.uint8, np.uint16, np.int16, np.uint32, np.int32, np.float32, np.float64];
    typ = pack_types[band.DataType]
    band.WriteRaster(ss[0],ss[1],ss[2],ss[3],arr.astype(typ).tostring())
    """
    if start is None:
        ss = [0, 0]
    else:
        ss = [start[1], start[0]]
    types = [None, np.uint8, np.uint16, np.int16, np.uint32, np.int32, np.float32, np.float64];
    typ = types[band.DataType]
    band.WriteArray(arr.astype(typ), ss[0], ss[1])
    return 0


def multiBandToArray(ds, subset=None):
    """ multiBandToArray(ds)
    Extracts data from all bands of a GDALDataset
    into a (generally 3-D) numpy array.

    INPUT	:	ds 		-	the source GDAL raster dataset
                subset	-	optional, read from a subset [row_start, col_start, row_size, col_size]

    OUTPUT	: 	a numpy array (float by default)
    """
    if subset is None:
        sz = [ds.RasterYSize, ds.RasterXSize]
    else:
        sz = [subset[2], subset[3]]
    out = np.empty((ds.RasterCount, sz[0], sz[1]))
    for k in range(ds.RasterCount):
        out[k] = bandToArray(ds.GetRasterBand(k + 1), subset)
    return out


def multiArrayToBands(ds, arr, subset=None):
    """ multiArrayToBands(ds,arr)
    Copies data from a generally 3-D numpy array to
    all bands of a raster GDALDataset automatically converting
    array data to the bands datatype.

    INPUT	:	ds 		-	the destination raster GDAL dataset
                arr		-	the numpy array to copy
                subset	-	optional, write onto a subset starting at [row_start, col_start]

    OUTPUT	: 	0
    """
    for k in range(ds.RasterCount):
        arrayToBand(ds.GetRasterBand(k + 1), arr[k], subset)
    ds.FlushCache()
    return 0


def setNoDataValue(fn, val=0):
    """ setNoDataValue(fn,val = 0)
    Sets a value for nodata pixels in a raster GDAL dataset.

    INPUT	:	fn 		-	GDAL dataset file
                val		-	nodata value (def. 0)

    OUTPUT	: 	None
    """
    ds = gdal.Open(fn, gdal.GA_Update)
    for i in range(0, ds.RasterCount):
        band = ds.GetRasterBand(i + 1)
        if val is None:
            band.DeleteNoDataValue()
        else:
            band.SetNoDataValue(val)
        band = None
    ds.FlushCache()
    ds = None

def getNoDataValue(fn):
    """ getNoDataValue(fn,val = 0)
    Gets current value for nodata pixels in a raster GDAL dataset.

    INPUT	:	fn 		-	GDAL dataset file

    OUTPUT	: 	No-data value
    """
    ds = gdal.Open(fn, gdal.GA_ReadOnly)
    ndv = ds.GetRasterBand(1).GetNoDataValue()
    ds = None
    return ndv

def getRasterInfo(fn):

    ds = gdal.Open(fn)
    size = [ds.RasterXSize, ds.RasterYSize]
    bands = ds.RasterCount

    return bands, size

def getRasterExtent(ras_ds):
    """ getRasterExtent(ras_ds)
    Gets the extent of a raster GDAL dataset.

    INPUT	:	ras_ds	-	input GDAL dataset object

    OUTPUT	: 	[lonmin, lonmax, latmin, latmax]
    """
    gt = ras_ds.GetGeoTransform()
    cols, rows = ras_ds.RasterXSize, ras_ds.RasterYSize
    ext = [gt[0], gt[0] + gt[1] * cols, gt[3], gt[3] + gt[5] * rows]
    return ext


def getRasterExtentAsGeometry(ras_ds):
    """ getRasterExtentAsGeometry(ras_ds)
    Gets the extent of a raster GDAL dataset as polygon (ogr.Geometry).

    INPUT	:	ras_ds	-	input GDAL dataset object

    OUTPUT	: 	ogr.Geometry object
    """
    extent = getRasterExtent(ras_ds)
    ring = ogr.Geometry(ogr.wkbLinearRing)
    ring.AddPoint(extent[0], extent[2])
    ring.AddPoint(extent[1], extent[2])
    ring.AddPoint(extent[1], extent[3])
    ring.AddPoint(extent[0], extent[3])
    ring.AddPoint(extent[0], extent[2])
    poly = ogr.Geometry(ogr.wkbPolygon)
    poly.AddGeometry(ring)
    return poly


def getRasterExtentAsShapefile(ras, shp):
    """ getRasterExtentAsShapefile(ras,shp)
    Gets the extent of a raster image as shapefile.

    INPUT	:	ras_ds	-	input raster file

    OUTPUT	: 	output shapefile (same CSR than input)
    """
    ras_ds = gdal.Open(ras)
    shp_drv = ogr.GetDriverByName('ESRI Shapefile')
    shp_ds = shp_drv.CreateDataSource(shp)
    crs = osr.SpatialReference()
    crs.ImportFromWkt(ras_ds.GetProjection())
    shp_ly = shp_ds.CreateLayer(os.path.splitext(os.path.basename(shp))[0], crs, ogr.wkbPolygon)
    shp_ly_id = ogr.FieldDefn('id', ogr.OFTInteger)
    shp_ly.CreateField(shp_ly_id)
    # Create the feature and set values
    shp_feat_def = shp_ly.GetLayerDefn()
    shp_feat = ogr.Feature(shp_feat_def)
    shp_feat.SetGeometry(getRasterExtentAsGeometry(ras_ds))
    shp_feat.SetField('id', 1)
    shp_ly.CreateFeature(shp_feat)
    return 0

def cloneVectorDataStructure(ds_in, fname, ly = 0, epsg = None):
    ds_in_ly = ds_in.GetLayer(ly)

    if epsg is None:
        srs = ds_in_ly.GetSpatialRef()
    else:
        srs = osr.SpatialReference()
        srs.ImportFromEPSG(epsg)

    drv = ogr.GetDriverByName('ESRI Shapefile')
    ds_out = drv.CreateDataSource(fname)
    ds_out_ly = ds_out.CreateLayer(os.path.splitext(os.path.basename(fname))[0],
                                   srs=srs,
                                   geom_type=ds_in_ly.GetLayerDefn().GetGeomType())
    f = ds_in_ly[0]
    [ds_out_ly.CreateField(f.GetFieldDefnRef(i)) for i in range(f.GetFieldCount())]
    ds_in_ly.ResetReading()

    return ds_out

def getRasterCoverage(shp, ras, shp_out):
    ras_ds = gdal.Open(ras)
    ras_geom = getRasterExtentAsGeometry(ras_ds)
    shp_ds = ogr.Open(shp)
    shp_ly = shp_ds.GetLayer(0)

    out_ds = cloneVectorDataStructure(shp_ds, shp_out)
    out_ly = out_ds.GetLayer(0)
    for f in shp_ly:
        of = f.Clone()
        g = of.GetGeometryRef()
        intsec = g.Intersection(ras_geom)
        if intsec.GetArea() > 0:
            of.SetGeometryDirectly(intsec)
            out_ly.CreateFeature(of)

    ras_ds = None
    shp_ds = None
    out_ds = None




def buffer(infile, outfile, buffdist):
    """ buffer(infile,outfile,buffdist)
    Creates a shapefile which is the buffered version of the input.

    INPUT	:	infile		-	input OGR dataset object
                outfile		-	output buffered OGR dataset object
                buffdist	-	buffer size

    OUTPUT	: 	True if ok
    """
    try:
        ds_in = ogr.Open(infile)
        lyr_in = ds_in.GetLayer(0)
        drv = ds_in.GetDriver()
        if os.path.exists(outfile):
            drv.DeleteDataSource(outfile)
        ds_out = drv.CreateDataSource(outfile)

        layer = ds_out.CreateLayer(lyr_in.GetLayerDefn().GetName(), \
                                   lyr_in.GetSpatialRef(), ogr.wkbPolygon)
        n_fields = lyr_in.GetLayerDefn().GetFieldCount()
        for i in xrange(lyr_in.GetLayerDefn().GetFieldCount()):
            field_in = lyr_in.GetLayerDefn().GetFieldDefn(i)
            fielddef = ogr.FieldDefn(field_in.GetName(), field_in.GetType())
            layer.CreateField(fielddef)

        for feat in lyr_in:
            geom = feat.GetGeometryRef()
            feature = feat.Clone()
            feature.SetGeometry(geom.Buffer(float(buffdist)))
            layer.CreateFeature(feature)
            del geom
        ds_out = None
    except:
        return False
    return True


def strq(str):
    """ strq(str)
    Puts quotes around a string.
    Ex. Pippo --> "Pippo"
    """
    return "\"%s\"" % str


def rasterizeOnReference(shp, fld, ras, out, bglabel=0, inner=False, scale_factor=1.0):
    """ rasterizeOnReference(shp,fld,ras,out,bglabel=0,inner=False)
    Cool function to rasterize any vector dataset over the grid
    of a reference raster dataset.

    INPUT	:	shp				-	shapefile to rasterize
                fld				-	shapefile field to burn into raster
                ras				-	reference raster file
                out 			-	output raster file
                bglabel			-	label for raster background (def. 0)
                inner			-	if True, only pixels entirely inside the
                                    polygons will be set (def. False)
                scale_factor	-	scales resolution using this factor (def. 1)
                                    > 1 ==> higher resolution

    OUTPUT	: 	True if ok
    """
    ras_ds = gdal.Open(ras)
    ext = getRasterExtent(ras_ds)
    xmin, ymin, xmax, ymax = min(ext[0], ext[1]), min(ext[2], ext[3]), max(ext[0], ext[1]), max(ext[2], ext[3])
    gt = ras_ds.GetGeoTransform()
    xres, yres = math.fabs(gt[1]) / scale_factor, math.fabs(gt[5]) / scale_factor
    rad_ds = None

    if not inner:
        tmp_shp = shp
    else:
        r = math.sqrt(2 * max(xres, yres) * max(xres, yres)) / 2
        tmp_shp = os.environ['TEMP'] + '\\' + str(uuid.uuid1()) + '.shp'
        buffer(shp, tmp_shp, -r)

    shp_ds = ogr.Open(tmp_shp)
    shp_ly = shp_ds.GetLayer(0)
    shp_ly_name = shp_ly.GetName()
    shp_ds = None
    shp_ly = None

    toRun = ['gdal_rasterize', '-init', str(bglabel), '-a', fld, '-l', shp_ly_name, '-te', str(xmin), str(ymin),
             str(xmax), str(ymax), '-tr', str(xres), str(yres), '-ot', 'Int32', '-q', tmp_shp, out]
    res = subprocess.call(toRun)

    if inner:
        os.remove(os.path.splitext(tmp_shp)[0] + '.shp')
        os.remove(os.path.splitext(tmp_shp)[0] + '.shx')
        os.remove(os.path.splitext(tmp_shp)[0] + '.prj')
        os.remove(os.path.splitext(tmp_shp)[0] + '.dbf')

    return res


def compactLabeledArray(arr, cnt=1, nodata=0):
    """ compactLabeledArray(arr,cnt=1,nodata=0)
    Rewrites an label array on a compact integer range.

    INPUT	:	arr		-	input array
                cnt		-	start counter
                nodata	-	value to preserve (e.g. background)

    OUTPUT	: 	[compact array, association with original labels]
    """
    uni = np.unique(arr)
    toDel = np.where(uni == nodata)[0]
    lbl = np.delete(np.unique(arr), toDel)
    idx = np.arange(cnt, cnt + len(lbl))
    ass = {key: val for key, val in zip(lbl, idx)}
    out = convertLabels(arr, ass, nodata)
    ass = {val: key for key, val in ass.items()}
    return np.reshape(out, arr.shape), ass, cnt + len(lbl) - 1


def convertLabels(arr, ass, nodata=0):
    """ convertLabels(arr,ass,nodata=0)
    Apply a label converter to a label array.

    INPUT	:	arr		-	array to convert
                ass		-	association dictionary
                nodata	-	value to preserve (e.g. background)

    OUTPUT	: 	converted array
    """
    out = arr.flatten()
    q = np.where(out != nodata)[0]
    for i, x in zip(q, out[q]):
        out[i] = ass[x]
    return np.reshape(out, arr.shape)


def bufferedVectorDifference(fn1, fn2, fout, buf):
    """ bufferedVectorDifference(fn1,fn2,fout,buf)
    Provides the difference between a vector layer and
    the buffered version of a second vector layer.

    INPUT	:	fn1		-	first vector operand (file)
                fn2		-	intersecting vector operand (file)
                fout	-	output vector file
                buf 	-	buffer size

    OUTPUT	: 	None
    """
    if buf < 1:
        buf = 1

    outputFileName = fout

    driver = ogr.GetDriverByName("ESRI Shapefile")
    f1 = driver.Open(fn1, 0)

    if f1 is None:
        print "Could not open f1 file ", fn1
        sys.exit(1)

    f2 = driver.Open(fn2, 0)

    if f2 is None:
        print "Could not open f2 file ", fn2
        sys.exit(1)

    layer1 = f1.GetLayer()
    feature1 = layer1.GetNextFeature()
    layer2 = f2.GetLayer()

    ### Create output file ###
    if os.path.exists(outputFileName):
        os.remove(outputFileName)
    try:
        output = driver.CreateDataSource(outputFileName)
    except:
        print 'Could not create output datasource ', outputFileName
        sys.exit(1)

    newLayer = output.CreateLayer('SymmetricDifference', geom_type=ogr.wkbPolygon, srs=layer1.GetSpatialRef())

    if newLayer is None:
        print "Could not create output layer"
        sys.exit(1)

    newLayerDef = newLayer.GetLayerDefn()
    ##############################

    featureID = 0

    while feature1:

        layer2.ResetReading()
        geom1 = feature1.GetGeometryRef()
        feature2 = layer2.GetNextFeature()
        newgeom = geom1.Clone()

        while feature2:
            geom2 = feature2.GetGeometryRef().Buffer(buf)

            if geom2.IsValid() and newgeom.Intersects(geom2) == 1:
                newgeom = newgeom.Difference(geom2)

            feature2.Destroy()
            feature2 = layer2.GetNextFeature()

        newFeature = ogr.Feature(newLayerDef)
        newFeature.SetGeometry(newgeom)
        newFeature.SetFID(featureID)
        newLayer.CreateFeature(newFeature)
        featureID += 1
        newFeature.Destroy()

        feature1.Destroy()
        feature1 = layer1.GetNextFeature()

    f1.Destroy()
    f2.Destroy()


def randomword(length):
    """ randomword(length)
    Generates a random word (for temp files).

    INPUT	:	length	-	word length

    OUTPUT	:	random word (string)
    """
    return ''.join(random.choice(string.lowercase) for i in range(length))


def rescaleImage(img, outmin=0, outmax=255, nodata=None, bw=False):
    """ rescaleImage(img,outmin=0,outmax=255,bw=False)
    Rescales values of an image (excluding nodata) between a min and a max.

    INPUT	:	img 			-	image array (float32)
                outmin, outmax 	-	minimum and maximum output values
                nodata			-	nodata value
                bw				-	if True, performs a band-wise rescaling (to equalize band dynamics)

    OUTPUT	:	rescaled image array
    """
    if nodata is not None:
        src = np.ma.array(img, mask=(img == nodata))
    else:
        src = img

    m = np.amin(src)
    M = np.amax(src)

    out = np.empty(src.shape)

    if len(src.shape) == 3:
        B = src.shape[0]
        for k in range(0, B):
            if bw:
                m = np.amin(src[k])
                M = np.amax(src[k])
            out[k] = (((src[k] - m) / (M - m)) * (outmax - outmin)) + outmin
    else:
        out = (((src - m) / (M - m)) * (outmax - outmin)) + outmin

    return out


def overlappingExtentCoords(ds, ref):
    """ overlappingExtentCoords(ds,ref)
    Get extent (in pixel coordinates) of a raster overlapping a reference raster
    at a different resolution (but SAME CRS/PROJECTION).

    INPUT	:	ds		-	dataset to clip
                ref		-	reference raster dataset

    OUTPUT	:	overlapping extent [row_start, col_start, row_size, col_size]
    """
    ds_geoT = ds.GetGeoTransform()
    ref_geoT = ref.GetGeoTransform()
    ref_origin_px_center = [ref_geoT[0] + ref_geoT[1] / 2, ref_geoT[3] + ref_geoT[5] / 2]
    ref_end_px_center = [ref_geoT[0] + ref_geoT[1] * ref.RasterXSize - ref_geoT[1] / 2, \
                         ref_geoT[3] + ref_geoT[5] * ref.RasterYSize - ref_geoT[5] / 2]
    ds_origin_px = [int(math.floor((ref_origin_px_center[1] - ds_geoT[3]) / ds_geoT[5])), \
                    int(math.floor((ref_origin_px_center[0] - ds_geoT[0]) / ds_geoT[1]))]
    ds_end_px = [int(math.floor((ref_end_px_center[1] - ds_geoT[3]) / ds_geoT[5])), \
                 int(math.floor((ref_end_px_center[0] - ds_geoT[0]) / ds_geoT[1]))]
    return [ds_origin_px[0], ds_origin_px[1], ds_end_px[0] - ds_origin_px[0] + 1, ds_end_px[1] - ds_origin_px[1] + 1]


def cropAsContainer(ras, ref, out_ras):
    """ cropAsContainer(ras,ref)
    Crops a raster using a reference raster (full-fit mode). The output raster extent will fully
    contain the reference extent (all reference pixels will be covered by at least one output pixel).

    INPUT	:	ras		-	rester to clip
                ref		-	reference raster

    OUTPUT	:	Writes output raster, returns True if OK
    """
    ras_ds = gdal.Open(ras)
    ref_ds = gdal.Open(ref)
    ext = overlappingExtentCoords(ras_ds, ref_ds)
    ref_geoT = ras_ds.GetGeoTransform()
    newOriginX = ref_geoT[0] + ext[1] * ref_geoT[1]
    newOriginY = ref_geoT[3] + ext[0] * ref_geoT[5]
    out_geoT = (newOriginX, ref_geoT[1], ref_geoT[2], newOriginY, ref_geoT[4], ref_geoT[5])
    drv = gdal.GetDriverByName('GTiff')
    out_ds = drv.Create(out_ras, ext[3], ext[2], ras_ds.RasterCount, ras_ds.GetRasterBand(1).DataType)
    out_ds.SetGeoTransform(out_geoT)
    out_ds.SetProjection(ras_ds.GetProjection())
    toWrite = multiBandToArray(ras_ds, ext)
    multiArrayToBands(out_ds, toWrite)
    out_ds.FlushCache()

    return (out_ds != None)


def generateRandomGCPs(img, out, N=80):
    ds = gdal.Open(img)
    X, Y = ds.RasterXSize, ds.RasterYSize
    G = ds.GetGeoTransform()

    inRef = osr.SpatialReference(wkt=ds.GetProjection())
    outRef = osr.SpatialReference()
    outRef.ImportFromEPSG(4326)
    ct = osr.CoordinateTransformation(inRef, outRef)

    f = open(out, 'w')
    f.write('#col row lon lat\n')

    for i in range(N):
        xp, yp = math.floor(random.uniform(0, X)), math.floor(random.uniform(0, Y))
        pg = ct.TransformPoint(G[0] + (xp + 0.5) * G[1], G[3] + (yp + 0.5) * G[5])
        f.write('%d\t%d\t%f\t%f\n' % (xp, yp, pg[0], pg[1]))

    f.close()
    return 0


def fieldToArray(shp, fld, nodata=0):
    ds = ogr.Open(shp)
    ly = ds.GetLayer(0)
    out = np.empty(ly.GetFeatureCount())
    i = 0
    for f in ly:
        x = f.GetField(fld)
        if x is None:
            out[i] = nodata
        else:
            out[i] = x
        i += 1
    ds = None
    return out

def fieldsToArray(shp, flds, nodata=np.nan):
    ds = ogr.Open(shp)
    ly = ds.GetLayer(0)
    N = ly.GetFeatureCount()
    out = np.empty((int(N), len(flds)))
    print str(N) + ' features to read...'
    i = 0
    for f in ly:
        j = 0
        for fld in flds:
            x = f.GetField(fld)
            if x is None:
                out[i,j] = nodata
            else:
                out[i,j] = x
            j += 1
        i += 1
        if i%100 == 0:
            print str(i) + ' features read...'
    print 'Finished!'
    ds = None
    return out


def homoGeo2Pixel(pnts, ref, out, sample_rate=None):
    ds = gdal.Open(ref)
    geoT = ds.GetGeoTransform()
    fin = open(pnts, 'r')
    fout = open(out, 'w')
    count = 0
    for line in fin:
        if sample_rate is None or (sample_rate is not None and random.random() < sample_rate):
            if line[0] != '#':
                var = line.split('\t')
                gpnt = [float(var[0]), float(var[1])]
                # ppnt = [int((gpnt[0] - geoT[0])/geoT[1]),int((gpnt[1] - geoT[3])/geoT[5])]
                ppnt = [(gpnt[0] - geoT[0]) / geoT[1], (gpnt[1] - geoT[3]) / geoT[5]]
                fout.write(str(ppnt[0]) + '\t' + str(ppnt[1]) + '\t' + var[2] + '\t' + var[3])
                count += 1
    fin.close()
    fout.close()
    return count


def arrayToGeoTiff(arr, fn, ref=None):
    nb = 1 if len(arr.shape) == 2 else arr.shape[0]
    if ref is not None:
        ds_ref = gdal.Open(ref)
        ds = createOverlappingTIFF(fn, ds_ref, nb, NP2GDAL[arr.dtype.name])
    else:
        dr = gdal.GetDriverByName('GTiff')
        if len(arr.shape) == 2:
            sX, sY = arr.shape[1], arr.shape[0]
        else:
            sX, sY = arr.shape[2], arr.shape[1]
        ds = dr.Create(fn, sX, sY, nb, NP2GDAL[arr.dtype.name])

    if nb == 1:
        arrayToBand(ds.GetRasterBand(1), arr)
    else:
        multiArrayToBands(ds, arr)
    return nb


def shapefileToCsv(fn, out, fields, points=True):
    ds = ogr.Open(fn)
    ly = ds.GetLayer(0)

    inRef = ly.GetSpatialRef()
    outRef = osr.SpatialReference()
    outRef.ImportFromEPSG(4326)
    ct = osr.CoordinateTransformation(inRef, outRef)

    with open(out, 'wb') as csvout:

        if points and ly.GetGeomType() == ogr.wkbPoint:
            row = fields + ['XCOORD', 'YCOORD']
        else:
            row = fields

        wrt = csv.writer(csvout, delimiter=',')
        wrt.writerow(row)

        k = 0
        for f in ly:
            row = [f[fields[i]] for i in range(len(fields))]
            if points and ly.GetGeomType() == ogr.wkbPoint:
                g = f.GetGeometryRef()
                g.Transform(ct)
                row = row + [str(g.GetX()), g.GetY()]
            wrt.writerow(row)
            k += 1

    csvout = None
    ds = None

    return k

def checkSRS(fn):

    ds = gdal.Open(fn)
    srs = osr.SpatialReference()

    srs.ImportFromWkt(ds.GetProjection())

    cod = srs.GetAttrValue('AUTHORITY',0) + ':' + srs.GetAttrValue('AUTHORITY',1)

    return cod

def compareImageGeometries(im1,im2):

    ds1 = gdal.Open(im1)
    ds2 = gdal.Open(im2)
    gt1 = ds1.GetGeoTransform()
    gt2 = ds2.GetGeoTransform()
    ds1 = None
    ds2 = None

    return gt1 == gt2

def getFieldNames(shp):

    ds = ogr.Open(shp)
    ly = ds.GetLayer(0)
    schema = []
    ldefn = ly.GetLayerDefn()
    for n in range(ldefn.GetFieldCount()):
        fdefn = ldefn.GetFieldDefn(n)
        schema.append(fdefn.name)

    return schema

def keepFields(src_shp,out_shp,except_list):

    shpd = ogr.GetDriverByName('ESRI Shapefile')
    dst = shpd.CreateDataSource(out_shp)
    src_ds = ogr.Open(src_shp,0)
    ly = src_ds.GetLayer()
    dst_ly = dst.CreateLayer(os.path.splitext(os.path.basename(out_shp))[0],
                             srs=ly.GetSpatialRef(),
                             geom_type=ly.GetLayerDefn().GetGeomType())
    ldef = ly.GetLayerDefn()
    toAdd = []
    for i in range(ldef.GetFieldCount()):
        if ldef.GetFieldDefn(i).name in except_list:
            toAdd.append(i)
            dst_ly.CreateField(ldef.GetFieldDefn(i))

    for f in ly:
        dstf = ogr.Feature(dst_ly.GetLayerDefn())
        dstf.SetGeometry(f.GetGeometryRef())
        for i in range(len(toAdd)):
            dstf.SetField(i,f.GetField(toAdd[i]))
        dst_ly.CreateFeature(dstf)

    src_ds = None
    dst = None

def queuedProcess(cmd_list,N_processes=4,shell=False,delay=0):

    cmd_queue = cmd_list
    prc_queue = []

    for t in range(N_processes):
        if len(cmd_queue) > 0:
            prc_queue.append(subprocess.Popen(cmd_queue.pop(0), shell=shell))
            time.sleep(delay)

    while len(prc_queue) > 0:
        for i in range(len(prc_queue)):
            if prc_queue[i].poll() is not None:
                prc_queue.pop(i)
                if len(cmd_queue) > 0:
                    prc_queue.append(subprocess.Popen(cmd_queue.pop(0), shell=shell))
                    time.sleep(delay)
                break

def arrayToField(shp,fld,arr,type='float'):
    ds = ogr.Open(shp,1)
    ly = ds.GetLayer(0)
    lydef = ly.GetLayerDefn()
    in_type = ogr.OFTReal
    in_type_np = np.float
    if type == 'int':
        in_type = ogr.OFTInteger
        in_type_np = np.int
    nf = ogr.FieldDefn(fld,in_type)
    ly.CreateField(nf)
    ly.ResetReading()
    i = 0
    for f in ly:
        f.SetField(fld,arr[i].astype(in_type_np))
        ly.SetFeature(f)
        i += 1
    ds = None

def mergeShapefiles(shp_list,out_file):
    ds = ogr.Open(shp_list[0])
    ds_out = cloneVectorDataStructure(ds,out_file)
    ds_out_ly = ds_out.GetLayer(0)
    ds = None

    for fn in shp_list:
        ds = ogr.Open(fn)
        for f in ds.GetLayer(0):
            ds_out_ly.CreateFeature(f)
        ds = None

    ds_out = None