r.landslide allows the identification of landslide susceptible areas on the basis of Artificial Neural Networks (ANNs), environmental parameters and landslide databases.
3 |In this guide, the user must enter the parameters related to the ANN architecture. There is the option to produce the susceptibility map only with an ANN, or from the ANN that had the best performance within a set of networks, from batch mode option (To do this, the user must check the box 'Train a set of ANNs and select the best one [batch mode]').
5 |Single ANN mode
6 |To create the map of susceptibility from a single ANN architeture, the user should not check the box 'Train a set of ANNs and select the best one [batch mode]'. The parameters required to use this mode are:
7 |Number of hidden neurons: The number of neurons in the hidden layer must be an integer. It is recommended that the maximum number of neurons in the intermediate layer be defined based on the Netch-Nielsen equation (Netch-Nielsen, 1987), which ensures that the neural network is able to approximate any continuous function and that depends on the number of thematic input parameters used by the user: NH ≤ 2NI + 1, where NH is the number of neurons in the intermediate layer and NI is the number of input parameters. A default value of 12 is set.
8 |Learning rate: Learning rate is a hyper-parameter that controls how much we are adjusting the weights of our network with respect the loss gradient. This paramter is generally chosen in the interval [0,1]. Lower learning rates may require a great number of training epochs. A default value of 0.6 is set.
9 |Number of epochs: An epoch is a measure of the number of times all of the training vectors are used to update the weights. A default value of 200 is set. In order to avoid overfitting due to a probable high number of epochs, the early stopping method was implemented.
10 |Batch mode
11 |Batch mode is activated when the 'Train a set of ANNs and select the best one [batch mode]' box is selected. In this mode, a set of ANNs is generated from the variation of the number of neurons in the hidden layer and the set of initial conditions of the synaptic weights. The network that presented the best performance is then used to produce the susceptibility map.
12 |To do this, the user must specify the parameters marked with [batch mode] in the tab, in addition to the learning rate and number of epochs parameters previously described.
13 |Minimum number of hidden neurons: Minimum number of hidden neurons to be tested. It is recommended that this parameter is not less than 2.
14 |Maximum number of hidden neurons: Maximum number of hidden neurons to be tested. As previously mentioned, it is recommended that this value does not exceed that proposed by the equation of Netch-Nielsen (Netch-Nielsen, 1987) in order to ensure that the neural network is able to approximate any continuous function. If this parameter is set to 0, the maximum number of neurons will be calculated automatically based on equation.
15 |Number of initial conditions: Number of initial sets of synaptic weights that will be tested for each set of neurons in the hidden layer. Attention: too high values can result in a long processing time.
16 |Optional parameters of the ANN parameters tab
17 |Considering that the construction phase of an ANN comprises three main steps: training, validation and testing, the input database must be restructured into three sets to serve these processes. The module allows the user to define a percentage of data that will be selected for the validation step and for the test step (0-1); however, it is recommended that the default values of 0.15 be maintained to avoid losses in the learning process from ANN.
18 |In this tab, the raster format thematic input parameters and the landslides and non-landslides events location vector files must be inserted. In this tab, there is also the option to perform only the training, validation and test steps. In this case, the module does not perform the calculation of susceptibility maps. This allows different network structures to be tested before the final susceptibility of the study area is evaluated. To do this, the users have to check the box 'Perform ONLY the training, validation and test steps'.
20 |A description of the parameters is given below:
21 |Thematic layers: Thematic layers refer to environmental parameters of the region study that may influence the occurrence of a landslide event. Some examples include: elevation, slope, aspect, topographic wetness index, soil type, soil use, among others. The user can add different layers, and can verify the influence of each one of them by the sensitivity analysis performed by the module.
22 |This information can be obtained from online databases for the region of interest and must be entered into the module in raster format.
23 |Point vector with landslides locations: Here, the user must indicate the vector file containing the location, in point format, of places where there were landslides of the region of interest. It is from this georeferenced information and thematic layers that the module will create the database for ANN training and application. It is recommended that for good ANN learning, a considerable number of slip points should be entered (averaging > 50, depending on the size of the area).
24 |This type of information can be obtained from online databases, scientific works, public organs, etc.
25 |Point vector with non-landslides locations: The user must specify the location of examples of places where there was no occurrence of slides in point vector format. The generation of these localities is usually given in a random manner, and should not overlap the landslide regions. It is recommended to generate the same number of points present in the vector file of landslide points.
26 |Text-file with X,Y coordinates of landslides location: This is an optional feature that allows the user to enter a text file containing the coordinates in the form X, Y that will be automatically converted to vector format, instead of entering the vector file of the location of landslides from the previous option. The user can also enter the values directly in the box that appears.
27 |Name of output susceptibility map: If the training-only checkbox is not checked, you must enter the name of the output raster map for susceptibility.
28 |Directory name to save files (it will be created): You must enter the path to create the directory that will save performance results, ANN architecture, and sensitivity assessment.
The Reckoning tab should be used in the case where only the network training, validation and test steps were performed by checking the 'check box' in the Training tab specified above. To perform this process, it is necessary to check the 'Perform ONLY the reckoning' check box and insert the directory containing the ANN architecture parameters which were stored after the training. Also, the user must identify the name of the map of susceptibility that will be generated.
31 |Here, the user can insert a raster layer to delimit a smaller region of interest for the generation of the susceptibility map. When this option is used, a temporary region is created from the active layer. This function is interesting in cases where the user wants to perform the evaluation of a smaller area, thus reducing time and computational demand.
33 |The module will generate a raster map representing the susceptibility to landslides of the area of interest. The raster will contain values ranging from 0 to 1, values close to 0 will represent areas of lesser susceptibility, while values closer to 1 will represent areas of greater susceptibility to these events.
35 |In the user-specified directory on the Training tab, different information about the selected ANN performance will be saved, which include: training error graph, validation and test, text files containing input information, ANN architecture, and performance, and graphs of the sensitivity evaluation of each of the parameters used.
36 |Note that the directory still includes text files called weights, peights, biasH and biasO, which will be used by the Reckoning tab. Therefore, it is recommended that the names of these files not be changed.
37 |After generating the module's susceptibility map, the user must load the raster map to the workspace via the d.rast module.
39 |R. Netch-Nielsen, Kolmogorov’s mapping neural network existence theorem, First IEEE International Joint Conference on Neural Networks 26 (1987) 11–14.
41 |Lucimara Bragagnolo
45 |Roberto Valmir da Silva
46 |José Mario Vicensi Grzybowski
47 |Last changed: $Date: 2019-01-03 12:59:19 +0200 (Thu, 03 Jan 2019) $
-------------------------------------------------------------------------------- /r.landslide.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ############################################################# 3 | # 4 | # MODULE: r.landslide 5 | # 6 | # AUTHOR(S): Lucimara Bragagnolo -------- lucimarabragagnolo@hotmail.com 7 | # Roberto Valmir da Silva --------- roberto.silva@uffs.edu.br 8 | # Jose Mario Vicensi Grzybowski - jose.grzybowski@uffs.edu.br 9 | # 10 | # PURPOSE: Uses r.landslide for identification of areas 11 | # susceptible to landslides 12 | # 13 | # COPYRIGHT: (C) 2019 by the GRASS Development Team 14 | # 15 | # This program is free software; you can redistribute it and/or modify 16 | # it under the terms of the GNU General Public License as published by 17 | # the Free Software Foundation; either version 2 of the License, or 18 | # (at your option) any later version. 19 | # 20 | # This program is distributed in the hope that it will be useful, 21 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 22 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 23 | # GNU General Public License for more details. 24 | ############################################################# 25 | 26 | 27 | #%module: r.landslide 28 | #% description: Creates a landslide susceptibility map 29 | #% keyword: raster 30 | #%end 31 | 32 | #%option 33 | #% key: num_hidden 34 | #% type: integer 35 | #% label: Number of hidden neurons 36 | #% answer: 12 37 | #% guisection: ANN parameters 38 | #% required: no 39 | #%end 40 | 41 | #%option 42 | #% key: lr_rate 43 | #% type: double 44 | #% label: Learning rate (0-1) 45 | #% answer: 0.6 46 | #% guisection: ANN parameters 47 | #% required: no 48 | #%end 49 | 50 | #%option 51 | #% key: nr_epochs 52 | #% type: integer 53 | #% label: Number of epochs 54 | #% answer: 200 55 | #% guisection: ANN parameters 56 | #% required: no 57 | #%end 58 | 59 | #%option 60 | #% key: val_samples 61 | #% type: double 62 | #% label: Percentage of data for validation (0-1) 63 | #% answer: 0.15 64 | #% guisection: ANN parameters 65 | #% required: no 66 | #%end 67 | 68 | #%option 69 | #% key: test_samples 70 | #% type: double 71 | #% label: Percentage of data for test (0-1) 72 | #% answer: 0.15 73 | #% guisection: ANN parameters 74 | #% required: no 75 | #%end 76 | 77 | #%flag 78 | #% key: b 79 | #% label: Train a set of ANNs and select the best one [batch mode] 80 | #% guisection: ANN parameters 81 | #%end 82 | 83 | #%option 84 | #% key: min_hidden 85 | #% type: integer 86 | #% label: [batch mode] Minimum number of hidden neurons 87 | #% answer: 2 88 | #% guisection: ANN parameters 89 | #% required: no 90 | #%end 91 | 92 | #%option 93 | #% key: max_hidden 94 | #% type: integer 95 | #% label: [batch mode] Maximum number of hidden neurons 96 | #% guisection: ANN parameters 97 | #% answer: 0 98 | #% required: no 99 | #%end 100 | 101 | #%option 102 | #% key: init_cond 103 | #% type: integer 104 | #% label: [batch mode] Number of initial conditions 105 | #% description: Number of times the synaptic weights are restarted 106 | #% guisection: ANN parameters 107 | #% answer: 1 108 | #% required: no 109 | #%end 110 | 111 | #%flag 112 | #% key: s 113 | #% label: Perform ONLY the training, validation and test steps 114 | #% guisection: Training 115 | #%end 116 | 117 | #%option G_OPT_R_INPUT 118 | #% key: layers 119 | #% multiple: yes 120 | #% label: Thematic layers 121 | #% description: Insert rasters of environmental parameters that influence the occurrence of landslides 122 | #% guisection: Training 123 | #% required: no 124 | #%end 125 | 126 | #%option G_OPT_V_INPUT 127 | #% key: landslide 128 | #% label: Point vector with landslides locations 129 | #% description: Vector layer containing the location of landslides points 130 | #% required: no 131 | #% guisection: Training 132 | #%end 133 | 134 | #%option G_OPT_V_INPUT 135 | #% key: nolandslide 136 | #% label: Point vector with non-landslides locations 137 | #% description: Vector layer containing the location of non-landslides points 138 | #% required: no 139 | #% guisection: Training 140 | #%end 141 | 142 | #%option G_OPT_F_INPUT 143 | #% key: coord 144 | #% label: [optional] Text file with X,Y coordinates of landslides locations 145 | #% description: Text file containing the landslides points coordinates 146 | #% required: no 147 | #% guisection: Training 148 | #% required: no 149 | #%end 150 | 151 | #%option G_OPT_F_SEP 152 | #% key: separator 153 | #% label: Character separator of text file containing the X,Y coordinates 154 | #% description: Character separator of text file containing the X,Y coordinates 155 | #% required: no 156 | #% guisection: Training 157 | #% answer: comma 158 | #% required: no 159 | #%end 160 | 161 | #%option G_OPT_R_OUTPUT 162 | #% key: output 163 | #% description: Name of output susceptibility map 164 | #% guisection: Training 165 | #% required: no 166 | #%end 167 | 168 | #%option G_OPT_F_OUTPUT 169 | #% key: directory 170 | #% label: Directory name to save files (it will be created) 171 | #% description: Directory name to save the ANN training results 172 | #% required: no 173 | #% guisection: Training 174 | #%end 175 | 176 | #%flag 177 | #% key: r 178 | #% description: Perform ONLY the application 179 | #% guisection: Application 180 | #%end 181 | 182 | #%option G_OPT_M_DIR 183 | #% key: direc_reckon 184 | #% description: Input path directory containing weights, peights and bias text files 185 | #% guisection: Application 186 | #% required: no 187 | #%end 188 | 189 | #%option G_OPT_R_OUTPUT 190 | #% key: outputr 191 | #% description: Name of output susceptibility map 192 | #% guisection: Application 193 | #% required: no 194 | #%end 195 | 196 | #%flag 197 | #% key: f 198 | #% description: Save susceptibility raster in directory 199 | #%end 200 | 201 | #%option G_OPT_R_INPUT 202 | #% key: dregion 203 | #% label: Insert a rast map to define a temporary region to reckoning step 204 | #% required: no 205 | #%end 206 | 207 | import sys 208 | import grass.script as gscript 209 | from grass.script import array as garray 210 | import numpy as np 211 | from ANN_module import ann_module 212 | from ANN_module import ann_reckon 213 | from ANN_module import ANN_batch 214 | import os 215 | 216 | def main(): 217 | options, flags = gscript.parser() 218 | 219 | #Output 220 | raster_final = options['output'] 221 | 222 | #Inputs 223 | nr_epochs = int(options['nr_epochs']) 224 | num_hidden = int(options['num_hidden']) 225 | coef = float(options['lr_rate']) 226 | val_samples = float(options['val_samples']) 227 | test_samples = float(options['test_samples']) 228 | min_hidden = int(options['min_hidden']) 229 | max_hidden = int(options['max_hidden']) 230 | trials = int(options['init_cond']) 231 | directory = options['directory'] 232 | flag_batch = flags['b'] #To train a set of ANNs 233 | flag_train = flags['s'] 234 | flag_reckon = flags['r'] 235 | flag_save = flags['f'] 236 | direc_reckon = options['direc_reckon'] 237 | coord = options['coord'] 238 | tregion = options['dregion'] 239 | 240 | 241 | #Parameters verification 242 | if num_hidden == 0: 243 | gscript.fatal(_("Zero is not a valid value for number of hidden neuros.")) 244 | 245 | if nr_epochs == 0: 246 | gscript.fatal(_("Zero is not a valid value for number of epochs.")) 247 | 248 | if coef == 0: 249 | gscript.fatal(_("Zero is not a valid value for learning rate.")) 250 | 251 | if coef >= 1: 252 | gscript.fatal(_("This is not a valid value for the learning rate. Please enter a value within the range 0-1.")) 253 | 254 | if val_samples == 0: 255 | gscript.fatal(_("Zero is not a valid value to create the validation dataset.")) 256 | 257 | if val_samples >= 1: 258 | gscript.fatal(_("This is not a valid value to create the validation dataset.")) 259 | 260 | if trials == 0: 261 | gscript.fatal(_("This is not a valid value for the number of initial conditions.")) 262 | 263 | if flag_train and flag_reckon: 264 | gscript.fatal(_("The both flags Perform ONLY reckoning and Perform ONLY training are selected. Please uncheck one.")) 265 | 266 | if flag_batch and flag_reckon: 267 | gscript.fatal(_("The both flags Train a set of ANNs and Perform ONLY reckoning are selected. Please uncheck one.")) 268 | 269 | if test_samples == 0: 270 | gscript.fatal(_("Zero is not a valid value to create the test dataset.")) 271 | 272 | if val_samples >= 1: 273 | gscript.fatal(_("This is not a valid value to create the test dataset.")) 274 | 275 | if flag_batch: 276 | if min_hidden == 0: 277 | min_hidden = 2 278 | gscript.warning(_("The minimum number of hidden neurons was defined as 2")) 279 | 280 | if max_hidden == 0: 281 | gscript.warning(_("The maximum number of hidden neurons will be calculated based on the number of input parameters.")) 282 | 283 | if val_samples > 0.20: 284 | gscript.warning(_("A high percentage for validation data reduces the number of training records. Consider reducing the value of this parameter.")) 285 | 286 | if test_samples > 0.20: 287 | gscript.warning(_("A high percentage for test data reduces the number of training records. Consider reducing the value of this parameter.")) 288 | 289 | 290 | #print flag_reckon 291 | work_dir = os.getcwd() #Get the current working directory 292 | 293 | if flag_reckon is False: 294 | #Get the input map layers 295 | rasters = options['layers'].split(",") #get the raster maps names (comma separated) 296 | #split: it separates the maps names and creates a list 297 | 298 | n = len(rasters) #number of input maps 299 | array_maps = [] 300 | 301 | #Creates a temporary region for calculation 302 | if tregion: 303 | gscript.use_temp_region() 304 | gscript.run_command('g.region', raster=tregion, align=rasters[0]) 305 | 306 | #Create a matrix with the map layers for reckon with tregion 307 | for i in range(0,n): 308 | a = garray.array(mapname=rasters[i],null=-9999) #this function does not aceppt NAN values 309 | a[a==-9999]=np.nan #replacing to NaN 310 | array_maps.append(a) #List with all maps 311 | 312 | row = int(a.shape[0]) 313 | col = int(a.shape[1]) 314 | lines = int(row*col) 315 | 316 | reckon = np.zeros((lines,n)) 317 | for i in range(0,n): 318 | reckon[:,i] = np.asarray(array_maps[i].reshape((lines,))) 319 | 320 | gscript.del_temp_region() 321 | 322 | else: 323 | #Create a matrix with the map layers for reckon without region 324 | for i in range(0,n): 325 | a = garray.array(mapname=rasters[i],null=-9999) #this function does not aceppt NAN values 326 | a[a==-9999]=np.nan #replacing to NaN 327 | array_maps.append(a) #List with all maps 328 | 329 | row = int(a.shape[0]) 330 | col = int(a.shape[1]) 331 | lines = int(row*col) 332 | 333 | reckon = np.zeros((lines,n)) 334 | for i in range(0,n): 335 | reckon[:,i] = np.asarray(array_maps[i].reshape((lines,))) 336 | 337 | if not coord: 338 | landslide = options['landslide'] 339 | else: 340 | separator = options['separator'] 341 | gscript.run_command( 342 | "v.in.ascii", 343 | input=coord, 344 | output='landslide_points', 345 | separator=separator, 346 | overwrite=True) 347 | landslide = 'landslide_points' 348 | 349 | #Get the vector points layers 350 | nolandslide = options['nolandslide'] 351 | 352 | #Collect the information from the rasters (v.what.rast) 353 | vecname = landslide,nolandslide 354 | 355 | columnst = [] 356 | for i in range(n): 357 | r = rasters[i] #Get the raster name 358 | c = r #Vector column name is the same that raster name 359 | if c.endswith('@PERMANENT'): 360 | c = c[:-10] 361 | columnst.append(c) #Vector columns title 362 | for j in range(0,2): #vectors landslide/no-landslide 363 | v = vecname[j] #Landslides or nonlandslide 364 | gscript.run_command( 365 | "v.what.rast", 366 | map=v, 367 | raster=r, 368 | column=c 369 | ) 370 | 371 | tempfile = gscript.tempfile() #Creates a temporary file 372 | gscript.run_command( 373 | "v.out.ascii", 374 | input=landslide, 375 | output=tempfile+'.txt', 376 | columns=columnst, 377 | format='point', 378 | separator='comma' 379 | ) 380 | 381 | land = np.genfromtxt(tempfile+'.txt', delimiter=",") #This command permits open csv with missing values 382 | land = np.delete(land,[0,1,2],axis=1) #Delete columns with coords and ID 383 | 384 | nanvalues = np.argwhere(np.isnan(land)) #Checking for nan values 385 | 386 | if nanvalues.size > 0: 387 | k = 0 388 | nanvalues = np.argwhere(np.isnan(land)) 389 | while nanvalues.size > 0: 390 | k = k + 1 391 | land = np.delete(land, (int(nanvalues[0,0])), axis=0) #Delete the line with nan 392 | nanvalues = np.argwhere(np.isnan(land)) 393 | 394 | gscript.warning("Some rows with null values of landslide points were deleted.") 395 | 396 | land = np.append(land,np.ones((land.shape[0],1)),axis=1) #Add column of ones (landslides) 397 | 398 | tempfile2 = gscript.tempfile() 399 | gscript.run_command( 400 | "v.out.ascii", 401 | input=nolandslide, 402 | output=tempfile2+'.txt', 403 | columns=columnst, 404 | format='point', 405 | separator='comma' 406 | ) 407 | 408 | noland = np.genfromtxt(tempfile2+'.txt', delimiter=",") 409 | noland = np.delete(noland,[0,1,2],axis=1) 410 | 411 | nanvalues = np.argwhere(np.isnan(noland)) #Checking for nan values 412 | 413 | if nanvalues.size > 0: 414 | k = 0 415 | nanvalues = np.argwhere(np.isnan(noland)) 416 | while nanvalues.size > 0: 417 | k = k + 1 418 | noland = np.delete(noland, (int(nanvalues[0,0])), axis=0) #Delete the line with nan 419 | nanvalues = np.argwhere(np.isnan(noland)) 420 | 421 | gscript.warning("Some rows with null values of nonlandslide points were deleted.") 422 | 423 | noland = np.append(noland,np.zeros((noland.shape[0],1)),axis=1) #Add column of zeros (non landslides) 424 | 425 | #Join tables 426 | dataset = np.append(land,noland,axis=0) 427 | np.random.shuffle(dataset) #Randomize dataset 428 | 429 | #Input and outuput data from training, validation and test 430 | input_data = dataset[:,0:n] 431 | output_data = dataset[:,n] 432 | 433 | if not flag_batch: #Just one neural network trained 434 | final = ann_module(input_data,output_data,reckon,num_hidden,coef,nr_epochs, 435 | val_samples,test_samples,directory,columnst,col,row,flag_train) 436 | 437 | else: #Flag_batch is true 438 | if max_hidden == 0: 439 | max_hidden = n*2+1 440 | 441 | hidden = np.arange(min_hidden,max_hidden+1,1) 442 | 443 | gscript.message(_("Definitions for batch mode: ")) 444 | gscript.message(_("Hidden neurons: ")) 445 | gscript.message(hidden) 446 | gscript.message(_("Number of initial conditions: ")) 447 | gscript.message(trials) 448 | 449 | total_ANNs = len(hidden)*trials 450 | gscript.message(_("Number of ANNs that will be tested: ")) 451 | gscript.message(total_ANNs) 452 | gscript.warning(_("This may take a while!")) 453 | 454 | final = ANN_batch(input_data,output_data,reckon,hidden,trials,coef, 455 | nr_epochs,val_samples,test_samples,directory,columnst,col,row,flag_train) 456 | 457 | #Save rasters name in order 458 | os.chdir(directory) 459 | with open("rasters_names.txt", "w") as my_file: 460 | my_file.write(options['layers']) 461 | os.chdir(work_dir) 462 | 463 | if not flag_train: #Generates final map (is not just training) 464 | 465 | #In case there is temp region 466 | if tregion: 467 | gscript.use_temp_region() 468 | gscript.run_command('g.region', raster=tregion, align=rasters[0]) 469 | 470 | suscep = garray.array() 471 | for i in range(0,final.shape[0]): 472 | for j in range(0,final.shape[1]): 473 | suscep[i,j] = final[i,j] 474 | 475 | suscep.write(mapname=raster_final, overwrite=True) #Create raster file 476 | 477 | if flag_save: #Save final raster in the directory 478 | os.chdir(directory) 479 | gscript.run_command( 480 | "r.out.gdal", 481 | input=raster_final, 482 | output=str(raster_final)+'.tiff', 483 | format='GTiff', 484 | type='Float64' 485 | ) 486 | os.chdir(work_dir) 487 | gscript.del_temp_region() 488 | 489 | else: 490 | suscep = garray.array() 491 | for i in range(0,final.shape[0]): 492 | for j in range(0,final.shape[1]): 493 | suscep[i,j] = final[i,j] 494 | 495 | suscep.write(mapname=raster_final, overwrite=True) #Create raster file 496 | 497 | if flag_save: #Save final raster in the directory 498 | os.chdir(directory) 499 | gscript.run_command( 500 | "r.out.gdal", 501 | input=raster_final, 502 | output=str(raster_final)+'.tiff', 503 | format='GTiff', 504 | type='Float64' 505 | ) 506 | os.chdir(work_dir) 507 | 508 | else: #flag_reckon is True 509 | 510 | raster_final = options['outputr'] 511 | 512 | os.chdir(direc_reckon) 513 | weights = np.genfromtxt('weights.txt', delimiter=",") 514 | peights = np.genfromtxt('peights.txt', delimiter=",") 515 | peights = np.reshape(peights,(peights.shape[0],1)) 516 | biasH = np.genfromtxt('biasH.txt', delimiter=",") 517 | biasH = np.reshape(biasH,(biasH.shape[0],1)) 518 | biasO = np.genfromtxt('biasO.txt', delimiter=",") 519 | biasO = np.reshape(biasO,(1,1)) 520 | max_in = np.genfromtxt('max_in.txt', delimiter=",") 521 | max_in = np.reshape(max_in,(1,max_in.shape[0])) 522 | min_in = np.genfromtxt('min_in.txt', delimiter=",") 523 | min_in = np.reshape(min_in,(1,min_in.shape[0])) 524 | 525 | with open('rasters_names.txt', 'r') as myfile: 526 | rasters = myfile.read() 527 | os.chdir(work_dir) 528 | 529 | #Get the input map layers 530 | rasters = rasters.split(",") #get the raster maps names (comma separated) 531 | #split: it separates the maps names and creates a list 532 | n = len(rasters) #number of input maps 533 | array_maps = [] 534 | 535 | #Creates a temporary region for calculation 536 | if tregion: 537 | gscript.use_temp_region() 538 | gscript.run_command('g.region', raster=tregion, align=rasters[0]) 539 | 540 | #Create a matrix with the map layers for reckon with tregion 541 | for i in range(0,n): 542 | a = garray.array(mapname=rasters[i],null=-9999) #this function does not aceppt NAN values 543 | a[a==-9999]=np.nan #replacing to NaN 544 | array_maps.append(a) #List with all maps 545 | 546 | row = int(a.shape[0]) 547 | col = int(a.shape[1]) 548 | lines = int(row*col) 549 | 550 | reckon = np.zeros((lines,n)) 551 | for i in range(0,n): 552 | reckon[:,i] = np.asarray(array_maps[i].reshape((lines,))) 553 | 554 | gscript.del_temp_region() 555 | 556 | else: 557 | #Create a matrix with the map layers for reckon without region 558 | for i in range(0,n): 559 | a = garray.array(mapname=rasters[i],null=-9999) #this function does not aceppt NAN values 560 | a[a==-9999]=np.nan #replacing to NaN 561 | array_maps.append(a) #List with all maps 562 | 563 | row = int(a.shape[0]) 564 | col = int(a.shape[1]) 565 | lines = int(row*col) 566 | 567 | reckon = np.zeros((lines,n)) 568 | for i in range(0,n): 569 | reckon[:,i] = np.asarray(array_maps[i].reshape((lines,))) 570 | 571 | for j in range(0,reckon.shape[1]): 572 | if max_in[0,j] != 0: 573 | reckon[:,j] = (reckon[:,j] - min_in[0,j])/(max_in[0,j]-min_in[0,j]) 574 | 575 | output_reckon = ann_reckon(reckon,weights,peights,biasH,biasO) 576 | 577 | final = np.reshape(output_reckon,(col,row),order='F') 578 | final = np.transpose(final) 579 | 580 | #In case there is temp region 581 | if tregion: 582 | gscript.use_temp_region() 583 | gscript.run_command('g.region', raster=tregion, align=rasters[0]) 584 | 585 | suscep = garray.array() 586 | for i in range(0,final.shape[0]): 587 | for j in range(0,final.shape[1]): 588 | suscep[i,j] = final[i,j] 589 | 590 | suscep.write(mapname=raster_final, overwrite=True) #Create raster file 591 | 592 | if flag_save: #Save final raster in the directory 593 | os.chdir(directory) 594 | gscript.run_command( 595 | "r.out.gdal", 596 | input=raster_final, 597 | output=str(raster_final)+'.tiff', 598 | format='GTiff', 599 | type='Float64' 600 | ) 601 | os.chdir(work_dir) 602 | gscript.del_temp_region() 603 | 604 | else: 605 | suscep = garray.array() 606 | for i in range(0,final.shape[0]): 607 | for j in range(0,final.shape[1]): 608 | suscep[i,j] = final[i,j] 609 | 610 | suscep.write(mapname=raster_final, overwrite=True) #Create raster file 611 | 612 | if flag_save: #Save final raster in the directory 613 | os.chdir(directory) 614 | gscript.run_command( 615 | "r.out.gdal", 616 | input=raster_final, 617 | output=str(raster_final)+'.tiff', 618 | format='GTiff', 619 | type='Float64' 620 | ) 621 | os.chdir(work_dir) 622 | 623 | return 0 624 | #Do not use the print statement (print function in Python 3) for informational output. This is reserved for standard module output if it has one. 625 | #https://trac.osgeo.org/grass/wiki/Submitting/Python 626 | 627 | if __name__ == "__main__": 628 | sys.exit(main()) 629 | --------------------------------------------------------------------------------