Skip to content

Commit b3b4ec8

Browse files
committed
ffs
1 parent 6a1851c commit b3b4ec8

File tree

4 files changed

+56
-42
lines changed

4 files changed

+56
-42
lines changed

geospatial_learn/handyplots.py

+2-12
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,6 @@
11
# -*- coding: utf-8 -*-
22
"""
3-
Created on Wed May 6 14:21:38 2015
4-
@author: Ciaran Robb
5-
author: Ciaran Robb
6-
Research Associate in Earth Observation
7-
Centre for Landscape and Climate Research (CLCR)
8-
Department of Geography, University of Leicester, University Road, Leicester,
9-
LE1 7RH, UK
10-
11-
If you use code to publish work cite/acknowledge me and authors of libs as
12-
appropriate
13-
3+
The handy plots module - these plots may be/ may have been handy
144
155
166
"""
@@ -61,7 +51,7 @@ def plot_classif_report(trueVals, predVals, labels=None, target_names=None,
6151

6252
cbVl = dF.values
6353
mn = np.round(cbVl.min(), decimals=2)
64-
mx= np.round(cbVl.max(), decimals=2)
54+
mx = np.round(cbVl.max(), decimals=2)
6555
del cbVl
6656

6757

geospatial_learn/learning.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,7 @@ def objective(trial, X, y, cv, group, score=scr):
211211
param_grid = {
212212
#"device_type": trial.suggest_categorical("device_type", ['gpu']),
213213
#'metric': 'rmse',
214-
'random_state': 48,
214+
'random_state': 42,
215215
'n_estimators': 20000,
216216
'reg_alpha': trial.suggest_loguniform('reg_alpha', 1e-3, 10.0),
217217
'reg_lambda': trial.suggest_loguniform('reg_lambda', 1e-3, 10.0),

geospatial_learn/raster.py

+19-8
Original file line numberDiff line numberDiff line change
@@ -1523,7 +1523,7 @@ def combine_scene(scl, c_scn, blocksize = 256):
15231523
inDataset.FlushCache()
15241524
inDataset = None
15251525

1526-
def polygonize(inRas, outPoly, outField=None, mask = True, band = 1,
1526+
def polygonize(inRas, outPoly, outField=None, mask=True, band=1,
15271527
filetype="ESRI Shapefile"):
15281528

15291529
"""
@@ -1585,8 +1585,8 @@ def polygonize(inRas, outPoly, outField=None, mask = True, band = 1,
15851585

15861586
if outField is None:
15871587
dst_fieldname = 'DN'
1588-
fd = ogr.FieldDefn( dst_fieldname, ogr.OFTInteger )
1589-
dst_layer.CreateField( fd )
1588+
fd = ogr.FieldDefn(dst_fieldname, ogr.OFTInteger)
1589+
dst_layer.CreateField(fd)
15901590
dst_field = dst_layer.GetLayerDefn().GetFieldIndex(dst_fieldname)
15911591

15921592

@@ -1767,7 +1767,8 @@ def set_bandnames(inras, names):
17671767
rds.FlushCache()
17681768
rds = None
17691769

1770-
def rasterize(inShp, inRas, outRas, field=None, fmt="Gtiff"):
1770+
def rasterize(inShp, inRas, outRas, field=None, fmt="Gtiff",
1771+
dtype=gdal.GDT_Int32):
17711772

17721773
"""
17731774
Rasterize a polygon to the extent & geo transform of another raster
@@ -1787,6 +1788,10 @@ def rasterize(inShp, inRas, outRas, field=None, fmt="Gtiff"):
17871788
17881789
fmt: the gdal image format
17891790
1791+
dtype: int
1792+
gdal dtype for output raster - consider the dtytpe of the field
1793+
you are burning
1794+
17901795
"""
17911796

17921797

@@ -1796,7 +1801,7 @@ def rasterize(inShp, inRas, outRas, field=None, fmt="Gtiff"):
17961801
# the usual
17971802

17981803
outDataset = _copy_dataset_config(inDataset, FMT=fmt, outMap=outRas,
1799-
dtype = gdal.GDT_Int32, bands=1)
1804+
dtype=dtype, bands=1)
18001805

18011806

18021807
vds = ogr.Open(inShp)
@@ -1806,6 +1811,7 @@ def rasterize(inShp, inRas, outRas, field=None, fmt="Gtiff"):
18061811
if field == None:
18071812
gdal.RasterizeLayer(outDataset, [1], lyr, burn_values=[1])
18081813
else:
1814+
print('rasterizing', field)
18091815
gdal.RasterizeLayer(outDataset, [1], lyr, options=["ATTRIBUTE="+field])
18101816

18111817
outDataset.FlushCache()
@@ -2022,8 +2028,8 @@ def clip_raster(inRas, inShp, outRas, cutline=False, fmt='GTiff'):
20222028
rds1 = None
20232029

20242030

2025-
def fill_nodata(inRas, maxSearchDist=5, smoothingIterations=1,
2026-
bands=[1]):
2031+
def fill_nodata(inRas, maxSearchDist=3, smoothingIterations=0,
2032+
bands=[1], nodata=0):
20272033

20282034
"""
20292035
fill no data using gdal
@@ -2043,12 +2049,16 @@ def fill_nodata(inRas, maxSearchDist=5, smoothingIterations=1,
20432049
bands: list of ints
20442050
the bands to process
20452051
2052+
nodata: int/float
2053+
the nodata value (it may not be set)
2054+
20462055
"""
20472056

20482057
rds = gdal.Open(inRas, gdal.GA_Update)
20492058

20502059
for band in tqdm(bands):
20512060
bnd = rds.GetRasterBand(band)
2061+
bnd.SetNoDataValue(nodata)
20522062
gdal.FillNodata(targetBand=bnd, maskBand=None,
20532063
maxSearchDist=maxSearchDist,
20542064
smoothingIterations=smoothingIterations)
@@ -2525,7 +2535,8 @@ def _copy_dataset_config(inDataset, FMT = 'Gtiff', outMap = 'copy',
25252535
x_pixels,
25262536
y_pixels,
25272537
bands,
2528-
dtype)
2538+
dtype,
2539+
options=['COMPRESS=LZW'])
25292540

25302541
outDataset.SetGeoTransform((
25312542
x_min, # 0

geospatial_learn/shape.py

+34-21
Original file line numberDiff line numberDiff line change
@@ -1025,8 +1025,7 @@ def zonal_stats(inShp, inRas, band, bandname, layer=None, stat = 'mean',
10251025
elif stat == 'min':
10261026
feature_stats = float(masked.min())
10271027
elif stat == 'mean':
1028-
feature_stats = float(masked.mean())
1029-
1028+
feature_stats = float(masked.mean())
10301029
elif stat == 'max':
10311030
feature_stats = float(masked.max())
10321031
elif stat == 'median':
@@ -1038,9 +1037,20 @@ def zonal_stats(inShp, inRas, band, bandname, layer=None, stat = 'mean',
10381037
elif stat == 'count':
10391038
feature_stats = int(masked.count())
10401039
elif stat == 'perc':
1041-
total = masked.shape[0]* masked.shape[1]
1042-
perc = masked.count() / total
1043-
feature_stats = int(np.round(perc*100))
1040+
# this would be the perc of the bbox
1041+
#total = masked.shape[0]* masked.shape[1]
1042+
#perc = masked.count() / total
1043+
# mask does not help here
1044+
#TODO crap hack needs sorted
1045+
srcn = np.count_nonzero(src_array)
1046+
rvcn = np.count_nonzero(rv_array)
1047+
if srcn > rvcn:
1048+
perc = 1
1049+
elif srcn == 0:
1050+
perc = 0
1051+
else:
1052+
perc = srcn / rvcn
1053+
feature_stats = float(np.round(perc, decimals=2))
10441054
elif stat == 'var':
10451055
feature_stats = float(masked.var())
10461056
elif stat == 'skew':
@@ -1265,7 +1275,7 @@ def zonal_frac(inShp, inRas, band, bandname, layer=None,
12651275
unique = src_array[0]
12661276
count = np.array([1])
12671277
else:
1268-
unique, count = np.unique(src_array[rv_array>0], return_counts=True)
1278+
unique, count = np.unique(src_array[rv_array>0], return_counts=True,)
12691279

12701280
entry = [feat.GetFID(), unique.tolist(), count.tolist()]
12711281

@@ -2550,16 +2560,18 @@ def zonal_point(inShp, inRas, field, band=1, nodata_value=0, write_stat=True):
25502560
vds = ogr.Open(inShp, 1) # TODO maybe open update if we want to write stats
25512561
vlyr = vds.GetLayer(0)
25522562

2553-
if write_stat != None:
2554-
# if the field exists leave it as ogr is a pain with dropping it
2555-
# plus can break the file
2556-
if _fieldexist(vlyr, field) == False:
2557-
vlyr.CreateField(ogr.FieldDefn(field, ogr.OFTReal))
2563+
# writing via OGR is glacial
2564+
# if write_stat != None:
2565+
# # if the field exists leave it as ogr is a pain with dropping it
2566+
# # plus can break the file
2567+
# if _fieldexist(vlyr, field) == False:
2568+
# vlyr.CreateField(ogr.FieldDefn(field, ogr.OFTReal))
25582569

25592570

25602571

25612572
feat = vlyr.GetNextFeature()
25622573
features = np.arange(vlyr.GetFeatureCount())
2574+
outdata = []
25632575

25642576
for label in tqdm(features):
25652577

@@ -2584,19 +2596,21 @@ def zonal_point(inShp, inRas, field, band=1, nodata_value=0, write_stat=True):
25842596
# unlikely but if none will have no data in the attribute table
25852597
continue
25862598
outval = float(src_array.max())
2587-
2588-
# if write_stat != None:
2589-
feat.SetField(field, outval)
2590-
vlyr.SetFeature(feat)
2599+
outdata.append(outval)
2600+
# # if write_stat != None:
2601+
# feat.SetField(field, outval)
2602+
# vlyr.SetFeature(feat)
25912603
feat = vlyr.GetNextFeature()
2592-
2604+
2605+
gdf = gpd.read_file(inShp)
2606+
gdf[field] = np.array(outdata)
25932607
if write_stat != None:
2594-
vlyr.SyncToDisk()
2595-
2596-
2597-
2608+
gdf.to_file(inShp)
2609+
# vlyr.SyncToDisk()
25982610
vds = None
25992611
rds = None
2612+
2613+
return gdf
26002614

26012615
def zonal_point_stk(inShp, inRas, fields, write_stat=True):
26022616

@@ -2661,7 +2675,6 @@ def zonal_point_stk(inShp, inRas, fields, write_stat=True):
26612675
mx, my = geom.GetX(), geom.GetY()
26622676

26632677
# Convert from map to pixel coordinates.
2664-
# No rotation but for this that should not matter
26652678
px = int((mx - rgt[0]) / rgt[1])
26662679
py = int((my - rgt[3]) / rgt[5])
26672680

0 commit comments

Comments
 (0)