-
Notifications
You must be signed in to change notification settings - Fork 1
/
ARF_sp_DataPreparation
414 lines (340 loc) · 19.8 KB
/
ARF_sp_DataPreparation
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
###############
# Script for data preparation using GDAL tools and Linux terminal
#
# Author: Felipe Barros ([email protected])
#
# Institution: International Institute for Sustainability (IIS-Rio.org)
#
# this script was developed to ensure the documentation of all procedures and that all rasters has the same propreties:
# Origin:
# Pixel resolution: 1000, 1000 (in meters)
# Raster Extent: -1654726.4418294357601553 -470314.6068012891337276 3542273.5581705644726753 4210685.3931987108662724
# SRC (Albers):
#
###############
## DATA PREPARATION
--## Using data from SDM as standart for a vector grid:
cd psql/modelagem_priorizacao/
# Modified the SDM to Albers QGIS
# Resampling the grid to 1000X1000 Km² due to Albers transofrmation the pixel size in bigger than 1000
gdalwarp -dstnodata 0 -tr 1000 -1000 -r "near" -of GTiff Alt_Albers.tif modelo_albers_100.tif -overwrite
--## Transofrming the raster to SQL raster then importing to PostGIS to use as reference raster.
raster2pgsql -c -C -s 102033 -b 1 -I -M modelo_albers_100.tif public.rast_modelo>rast.sql
sudo su
su postgres
--## Importing sql file to DB
psql -d modelagem -f rast.sql
--## After converted the raster to shp on GIS, saving it as SQL and importing to PostGIS
shp2pgsql -W LATIN1 -s 102033 grid_modelo_Albers.shp public.grid_priori_ma>grid.sql
sudo su
su postgres
--## Before, Albers projection must be implemented in DB:
INSERT into spatial_ref_sys (srid, auth_name, auth_srid, proj4text, srtext) values ( 102033, 'ESRI', 102033, '+proj=aea +lat_1=-5 +lat_2=-42 +lat_0=-32 +lon_0=-60 +x_0=0 +y_0=0 +ellps=aust_SA +units=m +no_defs ', 'PROJCS["South_America_Albers_Equal_Area_Conic",GEOGCS["GCS_South_American_1969",DATUM["South_American_Datum_1969",SPHEROID["GRS_1967_Truncated",6378160,298.25]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Albers_Conic_Equal_Area"],PARAMETER["False_Easting",0],PARAMETER["False_ ",0],PARAMETER["longitude_of_center",-60],PARAMETER["Standard_Parallel_1",-5],PARAMETER["Standard_Parallel_2",-42],PARAMETER["latitude_of_center",-32],UNIT["Meter",1],AUTHORITY["EPSG","102033"]]');
--## Importing sql file to DB
psql -d modelagem -f grid.sql
--## Removing the external grid (using R)
R
install.packages('RPostgreSQL')
library(RPostgreSQL)
con<-dbConnect(drv="PostgreSQL", host="localhost", port=5432, dbname="modelagem", user="postgres", password="postgres")
for (i in 1:500){
start=Sys.time()
print(i)
Dados_Disponíveis<-dbGetQuery(con, "DELETE from public.grid_priori_ma where gid in (select gid from public.grid_priori_ma where st_disjoint(geom, (select st_transform(b.geom, 102033) from biorregioes.ma_1148 as b)) limit 10000);")
print(Sys.time()-start)
}
quit()
# adding all columns that will be used
--area_ha
ALTER TABLE priorizacao_ma.grid_priori_ma add column area_ha numeric(10,2) NOT NULL DEFAULT(0);
--area
ALTER TABLE priorizacao_ma.grid_priori_ma add column area numeric(10,2) NOT NULL DEFAULT(0);
--perc_remnant
ALTER TABLE priorizacao_ma.grid_priori_ma add column perc_remnant numeric(10,2) NOT NULL DEFAULT(0);
--perct_restoration
ALTER TABLE priorizacao_ma.grid_priori_ma add column perct_restoration numeric(10,2) NOT NULL DEFAULT(0);
# Adding area information
update priorizacao_ma.grid_priori_ma set area_ha = st_area(geom)/10000;
update priorizacao_ma.grid_priori_ma set area = st_area(geom);
# Creating table with real Altlantic Rain forest area (Considering the area of bioma in the grid only):
--drop table priorizacao_ma.ma_real
CREATE table priorizacao_ma.ma_real AS
SELECT g.id as id,
row_number() over () as id2,
ST_Multi(st_intersection(g.geom,st_transform(ma.geom, 102033)))::geometry(MultiPolygon,102033) as real_geom,
st_area(st_intersection(g.geom,st_transform(ma.geom, 102033)))/10000 as realarea_ha
FROM priorizacao_ma.grid_priori_ma as g
JOIN biorregioes.ma_1148 as ma
on ((g.geom && st_transform(ma.geom, 102033)) and st_intersects(g.geom, st_transform(ma.geom, 102033)));
--limit 255964
# backuping
pg_dump modelagem --table=grid_priori_ma> grid_priori_ma.backup
pg_dump modelagem --table=rast_modelo> rast_modelo.backup
# restoring in other DB
psql -f grid_priori_ma.backup iis
psql -f rast_modelo.backup iis
#Changing the schema
psql iis
CREATE schema priorizacao_ma
ALTER TABLE public.grid_priori_ma SET SCHEMA priorizacao_ma;
ALTER TABLE public.rast_modelo SET SCHEMA priorizacao_ma;
#Creating spatial index
CREATE INDEX grid_priori_ma_geom_gist ON grids.grid_priori_ma USING GIST (geom);
CREATE INDEX rem_11_12_albers_gist ON sos_ma.remanescentes_2011_2012 USING GIST (geom_albers);
#####
--## 1) layer: raster with total forest area remnant.
#####
# The column perct_remnant will be used.
# 1.1) updating table setting perct_remnant with percent of forest in grid.
update priorizacao_ma.grid_priori_ma as g set perc_remnant = p.perc_veg from (
select
g.gid,
(round(st_area(st_union(st_intersection(g.geom, geom_albers)))::numeric/g.area,2))*100 as perc_veg
from priorizacao_ma.grid_priori_ma as g
join sos_ma.remanescentes_2011_2012 as f
on ((g.geom && f.geom_albers) and st_intersects(g.geom, f.geom_albers)) where f.legenda LIKE 'Mata%' Group by g.gid, g.geom) p
where g.gid=p.gid;
--## 1.2) Exporting from postgis to shp2
\q
exit
pgsql2shp -f /home/felipe/psql/forest_area.shp -h localhost -u postgres -P postgres iis priorizacao_ma.grid_priori_ma
--## 1.3) Rasterizing
gdal_rasterize -a PERC_REMNA -tr 1000 1000 -a_nodata 999 -l forest_area -te -1654726.4418294357601553 -470314.6068012891337276 3542273.5581705644726753 4210685.3931987108662724 /home/felipe/psql/forest_area.shp /home/felipe/psql/forest_area.tif
gzip /home/felipe/psql/forest_area.tif -9 -c >/home/felipe/psql/forest_area.tif.gz
#####
--## 2) layer: raster with oportunity cost
#####
--## Data was produced by Daniel Silva ([email protected])
--## 2.1) Rasterizing vector layer
gdal_rasterize -a Op_cost -tr 1000 1000 -a_nodata 999 -l Op_Cost_MA -te -1654726.4418294357601553 -470314.6068012891337276 3542273.5581705644726753 4210685.3931987108662724 /home/felipe/psql/modelagem_priorizacao/OportunityCost/uso_MA_shp/Op_Cost_MA.shp /home/felipe/psql/modelagem_priorizacao/OportunityCost/uso_MA_shp/Oportunity_cost_albers.tif
--# Falta inserir no banco de dados
#####
--## 3) layer: raster with area to be restored.
#####
--## 3.1) A unique vector layer was created merging all areas that should'nt be restored (e.g.: Urban Areas):
--agua: bc250.hid_massa_dagua_a; bc250.hid_trecho_massa_dagua_a; bc250.hid_rocha_em_agua_a as rocha_agua
--extracao vegetal: bc250.eco_area_agropec_ext_vegetal_pesca_a
--industrias: bc250.eco_edif_industrial_a; bc250.eco_ext_mineral_a
--area edificada: bc250.loc_area_edificada_a
--UCs excluindo APAs: bc250.lim_unidade_protecao_integral_a; bc250.lim_unidade_uso_sustentavel_a as ucs2 where sigla = 'APA'
--area militar: bc250.lim_terra_publica_a
--DESCONSIDERADO: mineração em fase de mineracao: dnpm.dnpm where dnpm.fase in ('CONCESSÃO DE LAVRA','LAVRA GARIMPEIRA','LICENCIAMENTO','REGISTRO DE EXTRAÇÃO')
--Area urbana: ibge.setores_censitarios where urbana.tipo='URBANO'
--Area de floresta: sos_ma.remanescentes_2011_2012 where florestas.legenda like 'Decremento%' or florestas.legenda like 'NMata%' or florestas.legenda like 'Desmatamento%';
--#All data were merged and dissolved using GIS
#############
# 3.2) After GIS processing: rasterizing
gdal_rasterize -a restore -tr 1000 1000 -a_nodata 999 -l grid_ma_Albers -te -1654726.4418294357601553 -470314.6068012891337276 3542273.5581705644726753 4210685.3931987108662724 /home/felipe/psql/modelagem_priorizacao/grid_ma_Albers.shp /home/felipe/psql/modelagem_priorizacao/Area_ToRestore_albers.tif
#####
--## 4) layer: raster with area to be restored discounting Riparian area (From Britaldo).
#####
##-- Britaldo raster layer
# 4.1) cropping raster without changing pixel size
gdalwarp -multi -dstnodata 0 -q -cutline /home/felipe/Projetos/Analise_area_relevo/Vetores/MataAtlantica_1148_Albers.shp -crop_to_cutline -of GTiff /home/felipe/psql/modelagem_priorizacao/apps/apps_hierarchical.tif /home/felipe/psql/modelagem_priorizacao/apps_hierarchical.tif -overwrite
# 4.2) Converting to shp
gdal_polygonize.py /home/felipe/psql/modelagem_priorizacao/apps_hierarchical.tif -f "ESRI Shapefile" /home/felipe/psql/modelagem_priorizacao/apps_hierarchical_MA.shp apps_hierarchical_MA DN
# 4.3) After removing the RPA from grid using GIS: rasterizing
gdal_rasterize -a torestapp -tr 1000 1000 -a_nodata 999 -l grid_ma_Albers -te -1654726.4418294357601553 -470314.6068012891337276 3542273.5581705644726753 4210685.3931987108662724 /home/felipe/psql/modelagem_priorizacao/grid_ma_Albers.shp /home/felipe/psql/modelagem_priorizacao/Area_ToRestore_app_albers.tif
#####
--## 5) layer: Percent remnant considering Riparian area (From Britaldo).
#####
--# After GIS processing (merging riparian area with remnant from SOS_MA)
# 5.1) After considering the RPA using GIS:
gdal_rasterize -a ForARAPP -tr 1000 1000 -a_nodata 999 -l grid_ma_Albers -te -1654726.4418294357601553 -470314.6068012891337276 3542273.5581705644726753 4210685.3931987108662724 /home/felipe/psql/modelagem_priorizacao/grid_ma_Albers.shp /home/felipe/psql/modelagem_priorizacao/apps/ForestArea_app_albers.tif
#####
## 6) Layer: Carbon stock (From Robin Chazdon)
#####
--## 6.1) Resampling to the same grid structure
gdalwarp -dstnodata -9999 -s_srs EPSG:4326 -t_srs '+proj=aea +lat_1=-5 +lat_2=-42 +lat_0=-32 +lon_0=-60 +x_0=0 +y_0=0 +ellps=aust_SA +units=m +no_defs' -tr 1000 -1000 -te -1654726.4418294357601553 -470314.6068012891337276 3542273.5581705644726753 4210685.3931987108662724 -r "near" -cutline /home/felipe/Projetos/Analise_area_relevo/Vetores/MataAtlantica_1148_Albers.shp -of GTiff "/home/felipe/psql/modelagem_priorizacao/Carbon/Brazil Atlantic Forest IIS/AGB_20yr_IIS_v6.tif" "/home/felipe/psql/modelagem_priorizacao/Carbon/Brazil Atlantic Forest IIS/AGB_20yr_IIS_v6_Albers.tif" -overwrite
--##layer: SDMs
##FLORA
cd ~/Projetos/ARF_spatial_planning/ENM/FLORA_buffermax2/final
ls
#Changinf the Coordinate Reference System CRS
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for f in *.tif; do echo "Processing $f"; gdalwarp -s_srs EPSG:4326 -t_srs '+proj=aea +lat_1=-5 +lat_2=-42 +lat_0=-32 +lon_0=-60 +x_0=0 +y_0=0 +ellps=aust_SA +units=m +no_defs' -dstnodata 9999 -tr 1000 -1000 -te -1654726.4418294357601553 -470314.6068012891337276 3542273.5581705644726753 4210685.3931987108662724 -r "near" -of GTiff $f ${f%.*}_Albers.tif -overwrite
done
IFS=$SAVEIFS
# Changing datatype:
R
for (a in 1:length(list.files('./FLORA_buffermax2/final', pattern='_Albers.tif$'))){
print(a)
modelos.list <- list.files('./FLORA_buffermax2/final', pattern='_Albers.tif$', full.names = T)[a]
modelos.list2 <- list.files('./FLORA_buffermax2/final', pattern='_Albers.tif$', full.names = F)[a]
modelos.bin<-raster(modelos.list)
writeRaster(modelos.bin, filename = paste0("./FLORA_buffermax2/final/mod_",modelos.list2), datatype="INT1U", overwrite=TRUE)
}
quit()
#AVES
cd ~/Projetos/ARF_spatial_planning/ENM/AVES_buffermax2/final
ls
#Changinf the Coordinate Reference System CRS
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for f in *.tif; do echo "Processing $f"; gdalwarp -s_srs EPSG:4326 -t_srs '+proj=aea +lat_1=-5 +lat_2=-42 +lat_0=-32 +lon_0=-60 +x_0=0 +y_0=0 +ellps=aust_SA +units=m +no_defs' -dstnodata 9999 -tr 1000 -1000 -te -1654726.4418294357601553 -470314.6068012891337276 3542273.5581705644726753 4210685.3931987108662724 -r "near" -of GTiff $f ${f%.*}_Albers.tif -overwrite
done
IFS=$SAVEIFS
cd ~/Projetos/ARF_spatial_planning/ENM/
# Changing datatype:
R
library(raster)
for (a in 1:length(list.files('./AVES_buffermax2/final', pattern='_Albers.tif$'))){
print(a)
modelos.list <- list.files('./AVES_buffermax2/final', pattern='_Albers.tif$', full.names = T)[a]
modelos.list2 <- list.files('./AVES_buffermax2/final', pattern='_Albers.tif$', full.names = F)[a]
modelos.bin<-raster(modelos.list)
writeRaster(modelos.bin, filename = paste0("./AVES_buffermax2/final/mod_",modelos.list2), datatype="INT1U", overwrite=TRUE)
}
quit()
#Anfibios
cd ~/Projetos/ARF_spatial_planning/ENM/ANFIBIOS_buffermax2/final
ls
#Changinf the Coordinate Reference System CRS
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for f in *.tif; do echo "Processing $f"; gdalwarp -s_srs EPSG:4326 -t_srs '+proj=aea +lat_1=-5 +lat_2=-42 +lat_0=-32 +lon_0=-60 +x_0=0 +y_0=0 +ellps=aust_SA +units=m +no_defs' -dstnodata 9999 -tr 1000 -1000 -te -1654726.4418294357601553 -470314.6068012891337276 3542273.5581705644726753 4210685.3931987108662724 -r "near" -of GTiff $f ${f%.*}_Albers.tif -overwrite
done
IFS=$SAVEIFS
cd ~/Projetos/ARF_spatial_planning/ENM/
# Changing datatype:
R
library(raster)
for (a in 1:length(list.files('./ANFIBIOS_buffermax2/final', pattern='_Albers.tif$'))){
print(a)
modelos.list <- list.files('./ANFIBIOS_buffermax2/final', pattern='_Albers.tif$', full.names = T)[a]
modelos.list2 <- list.files('./ANFIBIOS_buffermax2/final', pattern='_Albers.tif$', full.names = F)[a]
modelos.bin<-raster(modelos.list)
writeRaster(modelos.bin, filename = paste0("./ANFIBIOS_buffermax2/final/mod_",modelos.list2), datatype="INT1U", overwrite=TRUE)
}
quit()
#Compressing
gzip -rv ~/Projetos/ARF_spatial_planning/ENM/FLORA_buffermax2/final -9 -c >/home/felipe/psql/Flora_sdm.gz
gzip -rv ~/Projetos/ARF_spatial_planning/ENM/AVES_buffermax2/final -9 -c >/home/felipe/psql/Aves_sdm.gz
gzip -rv ~/Projetos/ARF_spatial_planning/ENM/ANFIBIOS_buffermax2/final -9 -c >/home/felipe/psql/Anfibios_sdm.gz
#####
# Data from Britaldo
#####
#Hilltop
#NEW
gdalwarp -dstnodata -9999 -te -1654726.4418294357601553 -470314.6068012891337276 3542273.5581705644726753 4210685.3931987108662724 -cutline /home/felipe/Projetos/Analise_area_relevo/Vetores/MataAtlantica_1148_Albers.shp -of GTiff "/media/felipe/Seagate Expansion Drive/Banco de dados Geograficos/BKP/Britaldo/codigo_florestal/ForestCodeBalance/Brazil_newFC_hilltops.tif" "/home/felipe/psql/modelagem_priorizacao/BritaldoNewHillTop_MA.tif" -overwrite
#OLD
gdalwarp -dstnodata -9999 -te -1654726.4418294357601553 -470314.6068012891337276 3542273.5581705644726753 4210685.3931987108662724 -cutline /home/felipe/Projetos/Analise_area_relevo/Vetores/MataAtlantica_1148_Albers.shp -of GTiff "/media/felipe/Seagate Expansion Drive/Banco de dados Geograficos/BKP/Britaldo/codigo_florestal/ForestCodeBalance/Brazil_oldFC_hilltops.tif" "/home/felipe/psql/modelagem_priorizacao/BritaldoOldHillTop_MA.tif" -overwrite
####
# current Forest area + potential app
####
# Estimando Area de app e Floresta atual no pixel.
pgsql2shp -f /home/felipe/psql/forest_area2.shp -h localhost -u postgres -P postgres iis "select * from sos_ma.remanescentes_2011_2012 as florestas where florestas.legenda LIKE 'Mata%'";
#EITO NO SIG
gdal_rasterize -a area_appFo -tr 1000 1000 -a_nodata 999 -l grid_ma_Albers -te -1654726.4418294357601553 -470314.6068012891337276 3542273.5581705644726753 4210685.3931987108662724 /home/felipe/psql/modelagem_priorizacao/grid_ma_Albers.shp /home/felipe/psql/modelagem_priorizacao/Area_appForest_albers.tif
#####
--## 7) layer: Area to be restored considering Riparian area (From Britaldo) as restored.
#####
##-- Britaldo raster layer
--# After britaldo's raster convertion to shp, submitted to modelagem
cd psql/modelagem_priorizacao/
--##Converting to sql
shp2pgsql -W LATIN1 -s 102033 apps_hierarchical_MA.shp public.apps_britaldo>apps_brit.sql
sudo su postgres
--#Importing to modelagem db
psql -f apps_brit.sql -d modelagem
#backuping
pg_dump modelagem --table=apps_britaldo> apps_brit.backup
#restoring in other DB
psql -f apps_brit.backup iis
#Changing the schema
psql iis
ALTER TABLE public.apps_britaldo SET SCHEMA priorizacao_ma;
#Adciionando coluna de perct_remnant_app
alter table priorizacao_ma.grid_priori_ma add column perct_remnant_app numeric(10,2) not null default (0);
#Adicionando percent area
update priorizacao_ma.grid_priori_ma as g set perct_remnant_app = p.perc_veg_app from (
select
g.gid,
(round(st_area(st_union(st_intersection(g.geom, geom_albers), st_intersection(g.geom, app.geom)))::numeric/g.area,2))*100 as perc_veg_app
from priorizacao_ma.grid_priori_ma as g
join sos_ma.remanescentes_2011_2012 as f
on ((g.geom && f.geom_albers) and st_intersects(g.geom, f.geom_albers))
join priorizacao_ma.apps_britaldo as app
on ((g.geom && app.geom) and st_intersects(g.geom, app.geom)) where f.legenda LIKE 'Mata%' Group by g.gid, g.geom, perc_veg_app) p
where g.gid=p.gid;
--## Exporting from postgis to shp2
\q
exit
pgsql2shp -f /home/felipe/psql/forest_area_app.shp -h localhost -u postgres -P postgres iis priorizacao_ma.grid_priori_ma
--##Rasterizing
gdal_rasterize -a perct_remnant_app -tr 1000 1000 -a_nodata 999 -l forest_area -te -1654726.4418294357601553 -470314.6068012891337276 3542273.5581705644726753 4210685.3931987108662724 /home/felipe/psql/forest_area.shp /home/felipe/psql/forest_area.tif
gzip /home/felipe/psql/forest_area.tif -9 -c >/home/felipe/psql/forest_area.tif.gz
#####
#-- rasterizing Brazilian states using IBGE code
#####
gdal_rasterize -a CODIGOIB1 -tr 1000 1000 -a_nodata 999 -l Estados_Albers -te -1654726.4418294357601553 -470314.6068012891337276 3542273.5581705644726753 4210685.3931987108662724 /home/felipe/Projetos/Base_dados/IBGE/Estados/Estados_Albers.shp /home/felipe/psql/states.tif
#####
--## Data Base procedure (not working so far)
#####
--## layer: raster with total forest area remnant.
--##Trying to rasterize in postgis --NOT WORKING
#SELECT ronw_number() over() as id, ST_AsRaster(geom, (select rast from priorizacao_ma.rast_modelo limit 1), '32BF', #perc_remnant, -9999))
#FROM priorizacao_ma.grid_priori_ma limit 10;
#SELECT ST_Union(ST_AsRaster(geom, rast, '32BF', height, -9999)) rast
#FROM forestcover, (SELECT rast FROM elevation LIMIT 1) rast;
##############
## Layer: area to be restored
##############
cd /home/felipe/psql/modelagem_priorizacao/
ls *.shp -1
shp2pgsql -W LATIN1 -s 102033 TeRestore_Albers.shp public.torestore>torestore.sql
sudo su postgres
--##Importing sql file to DB
psql -d modelagem -f torestore.sql
#backuping
pg_dump modelagem --table=torestore> torestore.backup
#restoring in other DB
psql -f torestore.backup iis
#Changing the schema
psql iis
ALTER TABLE public.torestore SET SCHEMA priorizacao_ma;
#Creating spatial index
CREATE INDEX torestore_geom_gist ON priorizacao_ma.torestore USING GIST (geom);
\q
exit
#Adicionando coluna de perct_restoration
--## NOTE percent retore is thje erase (difference) of grid with area not to restore!!!
ALTER TABLE priorizacao_ma.grid_priori_ma add column perct_restoration numeric(10,2) NOT NULL DEFAULT(0);
# Criando tabela com área real da MA:
--drop table priorizacao_ma.ma_real
CREATE table priorizacao_ma.ma_real AS
SELECT g.id as id,
row_number() over () as id2,
ST_Multi(st_intersection(g.geom,st_transform(ma.geom, 102033)))::geometry(MultiPolygon,102033) as real_geom,
st_area(st_intersection(g.geom,st_transform(ma.geom, 102033)))/10000 as realarea_ha
FROM priorizacao_ma.grid_priori_ma as g
JOIN biorregioes.ma_1148 as ma
on ((g.geom && st_transform(ma.geom, 102033)) and st_intersects(g.geom, st_transform(ma.geom, 102033)));
--limit 255964
#Adicionando percent restoration area
update priorizacao_ma.grid_priori_ma as g set perct_restoration = p.perc_rest from (
WITH grid_ma AS(
SELECT g.id as id,
st_intersection(g.geom,st_transform(ma.geom, 102033)) as real_geom,
st_area(st_intersection(g.geom,st_transform(ma.geom, 102033)))/10000 as realarea_ha
FROM priorizacao_ma.grid_priori_ma as g
JOIN biorregioes.ma_1148 as ma
on ((g.geom && st_transform(ma.geom, 102033)) and st_intersects(g.geom, st_transform(ma.geom, 102033)))
limit 255964)
select
greal.id,
round((sum((st_area(st_Difference(real_geom, f.geom))/10000)/realarea_ha)*100)::numeric,2)
as perc_rest
from grid_ma as greal
join priorizacao_ma.torestore as f
on ((greal.real_geom && f.geom)
and st_intersects(greal.real_geom, f.geom))
Group by greal.id
) p
where g.id=p.id;
select count(g.gid) FROM priorizacao_ma.grid_priori_ma as g
join priorizacao_ma.torestore as f
on ((g.geom && f.geom)
and st_intersects(g.geom, f.geom))
#######