def compilable_transformation_dictionary(feature_var, sentinel_im, geometry_transformation=None): t_dict=\ {'feature':{'object':feature_var}, \ 'feature_id':{'function':(lambda y: y.get_id() if type(y)!=tridy.Feature else y.get_data()['pixel_valu']),'parameters':['feature']},\ 'feature_data':{'function':(lambda y: y.get_data()),'parameters':['feature']},\ 'feature_geometry':{'function':(lambda y: y.get_geometry()),'parameters':['feature']},\ 'sentinel_im':{'object': sentinel_im}, \ 'im_band2_cropped':{'function':(lambda y, z: Imagee(*y.get_raster_map()['im_band2'].clip_by_shape(z)) ),'parameters':['sentinel_im','feature_geometry']},\ 'im_band4_cropped':{'function':(lambda y, z: Imagee(*y.get_raster_map()['im_band4'].clip_by_shape(z)) ),'parameters':['sentinel_im','feature_geometry']},\ 'im_band8_cropped':{'function':(lambda y, z: Imagee(*y.get_raster_map()['im_band8'].clip_by_shape(z)) ),'parameters':['sentinel_im','feature_geometry']},\ 'cri2': {'function':(lambda y, z: Imagee((1 / (y.get_data()/10000) ) - (1 / (z.get_data()/10000) ), y.get_metadata() ) ),'parameters':['im_band2_cropped', 'im_band8_cropped']},\ 'msr': {'function':(lambda x, y, z: Imagee( (z.get_data()-x.get_data())/(y.get_data()-x.get_data()) , y.get_metadata() ) ),'parameters':['im_band2_cropped', 'im_band4_cropped', 'im_band8_cropped']},\ 'geometry_transformation':{'object': geometry_transformation}, \ 'transformed_geometry':{'function':(lambda y, z: transform_wkt_geometry(y,z) if z!=None else y ),'parameters':['feature_geometry','geometry_transformation']},\ 'result_feature':{'function':(lambda v, w, x, y, z: FeatureWithID(data={**v, **{'cri2':y.get_statistics()}, **{'msr':z.get_statistics()}}, geom=w, id=x) ),'parameters':['feature_data','transformed_geometry','feature_id','cri2', 'msr']},\ } return t_dict
def get_twi(im_object): with TemporaryDirectory() as tempdir: im_object.export_as_tif('%s/dem.tif' % tempdir) routing.fill_pits(('%s/dem.tif' % tempdir, 1), '%s/cdem.tif' % tempdir) routing.flow_dir_mfd(('%s/cdem.tif' % tempdir, 1), '%s/dir.tif' % tempdir) routing.flow_accumulation_mfd(('%s/dir.tif' % tempdir, 1), '%s/twi.tif' % tempdir) ds = gdal.Open('%s/twi.tif' % tempdir) metadata_dict = im_object.get_metadata() twi = Imagee(np.array(ds.GetRasterBand(1).ReadAsArray()), metadata_dict) return twi
def compilable_transformation_dictionary(feature_var, feature_geomorpho_var, feature_soils): t_dict=\ {'feature':{'object':feature_var}, \ 'feature_id':{'function':(lambda y: y.get_id() if type(y)!=tridy.Feature else 1),'parameters':['feature']},\ 'feature_data':{'function':(lambda y: y.get_data()),'parameters':['feature']},\ 'feature_geometry':{'function':(lambda y: y.get_geometry()),'parameters':['feature']},\ 'feature_geomorpho':{'object': feature_geomorpho_var}, \ 'feature_dem':{'function':(lambda y, z: Imagee(*y.get_raster_map()['dem'].clip_by_shape(z)) ),'parameters':['feature_geomorpho','feature_geometry']},\ 'feature_slope':{'function':(lambda y, z: Imagee(*y.get_raster_map()['slope'].clip_by_shape(z)) ),'parameters':['feature_geomorpho','feature_geometry']},\ 'feature_orientation':{'function':(lambda y, z: Imagee(*y.get_raster_map()['orientation'].clip_by_shape(z)) ),'parameters':['feature_geomorpho','feature_geometry']},\ 'feature_twi':{'function':(lambda y, z: Imagee(*y.get_raster_map()['twi'].clip_by_shape(z)) ),'parameters':['feature_geomorpho','feature_geometry']},\ 'feature_soils':{'object': feature_soils}, \ 'feature_aglim1':{'function':(lambda y, z: Imagee(*y.get_raster_map()['aglim1'].clip_by_shape(z)) ),'parameters':['feature_soils','feature_geometry']},\ 'feature_aglim2':{'function':(lambda y, z: Imagee(*y.get_raster_map()['aglim2'].clip_by_shape(z)) ),'parameters':['feature_soils','feature_geometry']},\ 'result_feature':{'function':(lambda r, s, t, u, v, w, x, y, z: FeatureWithRasterMap(data=r, geom=s,id=t,raster_map={'dem':u,'slope':v,'orientation':w,'twi':x,'aglim1':y,'aglim2':z}) ),'parameters':['feature_data','feature_geometry','feature_id','feature_dem', 'feature_slope', 'feature_orientation', 'feature_twi', 'feature_aglim1', 'feature_aglim2']},\ } return t_dict
grid_clip = Grid( np.array(grid.get_gridorigin()) + np.array(tuple(grid.find_index( (envelope[0], envelope[3])))) * np.array(grid.get_gridstepsize()), (metadata_dict['affine_transformation'][1], metadata_dict['affine_transformation'][5])) # %% clip_metadata_dict = {} clip_metadata_dict[ 'affine_transformation'] = grid_clip.get_affinetransformation() clip_metadata_dict['nodata'] = float(np.min(a)) if np.min(a) < 0 else np.nan clip_metadata_dict['proj_wkt'] = etrs3035_sr.ExportToWkt() # %% big_im = Imagee(a, clip_metadata_dict) # %% big_twi = get_twi(big_im) big_orientation = Imagee(*big_im.calculate_azimuth()) big_slope = Imagee(*big_im.calculate_slope()) # %% feature_geomorpho = FeatureWithRasterMap( data={}, geom=('POLYGON ((%d %d, %d %d, %d %d, %d %d, %d %d))' % (envelope[0], envelope[2], envelope[0], envelope[3], envelope[1], envelope[3], envelope[1], envelope[2], envelope[0], envelope[2])), id=1, raster_map={ 'dem': big_im,
def geomorphology_transformations(ogr_olu_object, attributes_table, attributes2object_table, attributes_fid, dem_im, slope_im, aspect_im, twi_im): o_dict=\ { 'feature':{'object':ogr_olu_object},\ 'feature_json':{'function':(lambda y: json.loads(y.ExportToJson())),'parameters':['feature']},\ 'feature_geometry':{'function':(lambda y: y.GetGeometryRef().ExportToWkt() ),'parameters':['feature']},\ 'feature_id':{'function':(lambda y: int(y['properties']['fid'])),'parameters':['feature_json']},\ 'attributes_table':{'object':attributes_table},\ 'attributes2object_table':{'object':attributes2object_table},\ 'attributes_fid':{'object':attributes_fid},\ 'dem_image':{'object':dem_im},\ 'slope_image':{'object':slope_im},\ 'azimuth_image':{'object':aspect_im},\ 'twi_image':{'object':twi_im},\ 'attribute_properties':{'function':(lambda u, v, w, x,y,z: {**{'fid':u},**{'dataset_id':5},**{'atts':{'elevation':Imagee(*w.clip_by_shape(v)).get_statistics()['mean'], 'slope':Imagee(*x.clip_by_shape(v)).get_statistics()['mean'], 'azimuth':Imagee(*y.clip_by_shape(v)).get_statistics()['mean'], 'twi':Imagee(*z.clip_by_shape(v)).get_statistics()['mean']} } }),'parameters':['attributes_fid','feature_geometry','dem_image', 'slope_image', 'azimuth_image', 'twi_image']}, 'attributes_insert_statement':{'function':(lambda x, y,z: "INSERT INTO %s (fid,atts,dataset_fid) VALUES (%s,('%s'::json),%s)" % (x,y,json.dumps(z['atts']),z['dataset_id']) ),'parameters':['attributes_table','attributes_fid','attribute_properties']},\ 'attributes2object_insert_statement':{'function':(lambda x,y,z: "INSERT INTO %s (object_fid,atts_fid,atts_origin) VALUES (%s,%s,4)" % (z,x,y) ),'parameters':['feature_id','attributes_fid','attributes2object_table']},\ 'two_insert_statements':{'function':(lambda y,z: [y,z]),'parameters':['attributes_insert_statement','attributes2object_insert_statement']},\ } return o_dict
size=tuple(np.array(grid.find_index((geom_utm_envelope[1],geom_utm_envelope[2])))-np.array(grid.find_index((geom_utm_envelope[0],geom_utm_envelope[3]))))+np.array([1,1]) # %% a=np.array(ds_b2.GetRasterBand(1).ReadAsArray(xoff=int(origin[0]),yoff=int(origin[1]),win_xsize=int(size[0]),win_ysize=int(size[1]))) # %% grid_clip=Grid(np.array(grid.get_gridorigin())+np.array(tuple(grid.find_index((geom_utm_envelope[0],geom_utm_envelope[3]))))*np.array(grid.get_gridstepsize()),(metadata_dict['affine_transformation'][1],metadata_dict['affine_transformation'][5])) # %% clip_metadata_dict={} clip_metadata_dict['affine_transformation']=grid_clip.get_affinetransformation() clip_metadata_dict['nodata']=float(np.min(a)) if np.min(a)<0 else np.nan clip_metadata_dict['proj_wkt']=utm32635_sr.ExportToWkt() # %% im=Imagee(a,clip_metadata_dict) # %% im.export_as_tif('vyrez.tif') # %% a=np.array(ds_b4.GetRasterBand(1).ReadAsArray(xoff=int(origin[0]),yoff=int(origin[1]),win_xsize=int(size[0]),win_ysize=int(size[1]))) im_b4=Imagee(a,clip_metadata_dict) im_b4.export_as_tif('vyrez_b4.tif') # %% a=np.array(ds_b8.GetRasterBand(1).ReadAsArray(xoff=int(origin[0]),yoff=int(origin[1]),win_xsize=int(size[0]),win_ysize=int(size[1]))) im_b8=Imagee(a,clip_metadata_dict) im_b8.export_as_tif('vyrez_b8.tif') # %%
data_source=eudem_cz_ds, subgeoconcepts=[]) eudem_cz.set_raster_output_backend( '', eudem_cz.get_data_source().get_attributes()['local']) f = admunit_cz.read_features_from_table_by_sqlcondition('id=538493', 1) ff = next(f)[0] ff.transform_geometry(sjtsk5514_to_wgs84) ff.transform_geometry(wgs84_to_etrs3035) bbox = ogr.CreateGeometryFromWkt(ff.get_geometry()).Buffer(10).GetEnvelope() im = eudem_cz.read_raster_output_backend(1, (bbox[0], bbox[3], bbox[1], bbox[2])) im_slope = Imagee(*im.calculate_slope()) im_azimuth = Imagee(*im.calculate_azimuth()) im_twi = get_twi(im) olu_atts_fid_maxvalue = dbs_olu.execute( 'SELECT max(fid) FROM olu2.olu_attribute_set')[0][0] dbs_olu.execute("select setval('olu2.olu_attributes_fid_seq', %s)" % olu_atts_fid_maxvalue) olu_atts_id_gen = sequence_generator( dbs_olu.execute('SELECT last_value FROM olu2.olu_attributes_fid_seq')[0] [0]) dbs_olu_ogr_conn = dbs_olu.create_ogr_connection() lyr = dbs_olu_ogr_conn.GetLayerByName('olu_object.538493')
np.array([-500, 500, 500, -500])) cci__im = cci_africa.read_raster_output_backend(1, bbox_r3857) colnames = ['id', 'lc_class', 'frequency'] df = pd.DataFrame(columns=colnames) lyr.ResetReading() bad_list = [] for c in range(lyr.GetFeatureCount()): lyr_f = lyr.GetNextFeature() row_d = {} if lyr_f.GetGeometryRef().IsEmpty(): continue try: geom = lyr_f.GetGeometryRef() geom.Transform(wgs84_to_mercator3857) statistics = Imagee( *cci__im.clip_by_shape(geom.ExportToWkt())).get_statistics( categoric=True, percentage=True, full=True) row_d['id'] = lyr_f.GetFieldAsInteger64(0) row_d['lc_class'] = statistics['mode'] row_d['frequency'] = statistics['frequencies'][str( statistics['mode'])] df = df.append(row_d, ignore_index=True) except: bad_list.append(lyr_f.GetFieldAsInteger64(0)) df.set_index(df.id, inplace=True) dbs.execute("create table %s.atts_%s () inherits (%s) " % (country.lower(), table, olu_attribute_set_table)) for index, row in df.iterrows(): atts_fid = next(olu_atts_id_gen) dbs.execute( 'insert into %s.atts_%s (fid,atts,dataset_fid,clc_id) select %d as fid, \'{"frequency":%s}\'::jsonb as atts, %d as dataset_fid, %s as clc_id '
tuple( grid.find_index((feature_geometry3035.GetEnvelope()[0], feature_geometry3035.GetEnvelope()[3])))) * np.array(grid.get_gridstepsize()), (metadata_dict['affine_transformation'][1], metadata_dict['affine_transformation'][5])) # %% clip_metadata_dict = {} clip_metadata_dict[ 'affine_transformation'] = grid_clip.get_affinetransformation() clip_metadata_dict['nodata'] = float(np.min(a)) if np.min(a) < 0 else np.nan clip_metadata_dict['proj_wkt'] = etrs3035_sr.ExportToWkt() # %% im = Imagee(a, clip_metadata_dict) # %% im.export_as_tif('Mnichovice.tif') # %% G = apply_function(compilable_tree_dictionary(admunit_cz), 'admunit__tree') # %% list(find_neighbors_level(G.reverse(), str(f.get_data()['Kod']), 4)) # %% features_lpis = lpis_cz.get_subgeoconcept_by_name( '697541').read_features_from_table(1) # %%
lyr.GetExtent()[1], lyr.GetExtent()[2] ] cci20__im = cci20.read_raster_output_backend(1, bbox_r) colnames = ['id', 'lc_class', 'frequency'] df = pd.DataFrame(columns=colnames) lyr.ResetReading() bad_list = [] for c in range(lyr.GetFeatureCount()): lyr_f = lyr.GetNextFeature() row_d = {} if lyr_f.GetGeometryRef().IsEmpty(): continue try: statistics = Imagee(*cci20__im.clip_by_shape( lyr_f.GetGeometryRef().ExportToWkt())).get_statistics( categoric=True, percentage=True, full=True) row_d['id'] = lyr_f.GetFieldAsInteger64(0) row_d['lc_class'] = statistics['mode'] row_d['frequency'] = statistics['frequencies'][str( statistics['mode'])] df = df.append(row_d, ignore_index=True) except: bad_list.append(lyr_f.GetFieldAsInteger64(0)) df.set_index(df.id, inplace=True) all_args = '' for index, row in df.iterrows(): args = '),('.join([ str(int(index)) + ',' + str(int(row['lc_class'])) + ',' + str(float(row['frequency'])) ])
tuple( grid.find_index((feature_geometry_buffer.GetEnvelope()[0], feature_geometry_buffer.GetEnvelope()[3])))) * np.array(grid.get_gridstepsize()), (metadata_dict['affine_transformation'][1], metadata_dict['affine_transformation'][5])) # %% clip_metadata_dict = {} clip_metadata_dict[ 'affine_transformation'] = grid_clip.get_affinetransformation() clip_metadata_dict['nodata'] = float(np.min(a)) if np.min(a) < 0 else np.nan clip_metadata_dict['proj_wkt'] = etrs3035_sr.ExportToWkt() # %% im = Imagee(a, clip_metadata_dict) # %% im.export_as_tif('pole_s_bufrem500.tif') # %% im_twi = get_twi(im) # %% im_twi.export_as_tif('akumulace_vody_na_poli_s_bufrem500.tif') # %% cropped_im = Imagee(*im.clip_by_shape(feature_geometry.ExportToWkt())) # %% plt.imshow(cropped_im.get_data(),