<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Omar Seleem on Medium]]></title>
        <description><![CDATA[Stories by Omar Seleem on Medium]]></description>
        <link>https://medium.com/@omar.abdwahab92?source=rss-a76b76bcf2b4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bZwOvpMPj8OFiuUup5rymA.jpeg</url>
            <title>Stories by Omar Seleem on Medium</title>
            <link>https://medium.com/@omar.abdwahab92?source=rss-a76b76bcf2b4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 18:41:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@omar.abdwahab92/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Potential damage calculation based on BEAM-Dataset]]></title>
            <link>https://medium.com/@omar.abdwahab92/potential-damage-calculation-based-on-beam-dataset-c3f99c74eac8?source=rss-a76b76bcf2b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3f99c74eac8</guid>
            <category><![CDATA[floods]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[european-union]]></category>
            <category><![CDATA[germany]]></category>
            <dc:creator><![CDATA[Omar Seleem]]></dc:creator>
            <pubDate>Wed, 14 Feb 2024 13:33:16 GMT</pubDate>
            <atom:updated>2024-02-14T13:35:38.241Z</atom:updated>
            <content:encoded><![CDATA[<p>The Bund/Länder- Arbeitsgemeinschaft Wasser (LAWA-AH) has mandated a preliminary assessment beginning with the 3rd cycle of the EU Flood Risk Management Directive. This assessment relies on a nationwide dataset of damage potential and a unified methodology for calculating potential damage.</p><p>This article provides a comprehensive guide on calculating damage data using Python. You’ll need two input files: water depth and the BEAM dataset. For more information about the BEAM dataset and to download it, visit this link: <a href="https://www.wasserblick.net/servlet/is/219256/">BEAM Dataset</a>.</p><p>You can find the Python script and an example in this GitHub repository: <a href="https://github.com/omarseleem92/Potential_damage/tree/main">Potential Damage Repository</a>.</p><h3>BEAM dataset :</h3><p>The BEAM (Basic European Assets Map) dataset offers a comprehensive dataset for calculating potential damages caused by natural disasters across Europe. It provides monetary asset values per unit area (€/m²) through a geospatial dataset, enabling detailed damage assessments and enhancing disaster risk management efforts continent-wide. The dataset comprises multiple asset layers representing population density, household goods, vehicles, and more.</p><p>The BEAM dataset is provided in the Lambert Azimuthal Equal Area projection and the ETRS 1989 LAEA coordinate system (EPSG code: 3035). It is recommended to use a minimum resolution of 5 meters.</p><h3>Potential damage calculation:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cY-Bh7cBQl97KeX9RQzGpQ.png" /><figcaption>Overview of the tool</figcaption></figure><p>The Python script performs the following tasks:</p><ol><li>The script initially reads the water depth raster, which should adhere to specific criteria: i<strong>t must be in 5-meter resolution, with water depth represented in centimeters, and it should share the same projection as the BEAM dataset.</strong> Once read, the script transforms the water depth raster into a polygon shapefile layer and subsequently dissolves it to obtain the boundary. Using the generated shapefile, the script then proceeds to clip the BEAM dataset accordingly.</li><li>Then, it creates a raster for each land use type found within the BEAM dataset. These rasters are saved in a designated folder named “Beam_rasters_clipped.” Moreover, the script identifies and extracts fixed values based on the land use category code (ln_value). These fixed values are clipped and stored in a separate folder named “Fixed_values_rasters_clipped.” The determination of fixed values follows a predefined guideline outlined below.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*xiBomVovDgH85cMNBEuEHQ.png" /><figcaption>Land use categories and associated asset value categories in the attribute “fix_value”. Source: <a href="https://www.wasserblick.net/servlet/is/219256/20220927_Empfehlung-PFRA-Anlage.pdf">https://www.wasserblick.net/servlet/is/219256/20220927_Empfehlung-PFRA-Anlage.pdf</a></figcaption></figure><p>3. The script proceeds to compute the potential damage for each land use type. This computation relies on the water depth data and utilizes predefined damage equations, which are outlined in the table below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*wFaBYtK2NDjQNnem53SZ5Q.png" /><figcaption>Overview of the damage functions of the respective BEAM asset categories as mathematical expressions (source: <a href="https://www.wasserblick.net/servlet/is/219256/20220927_Empfehlung-PFRA-Anlage.pdf">https://www.wasserblick.net/servlet/is/219256/20220927_Empfehlung-PFRA-Anlage.pdf</a>)</figcaption></figure><p>Finally, the Python script sums all the calculated damage from each land use and saves them in a raster named “Sum_damage.tif”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*P1ahH1OWKlnSatmuDKHhxQ.png" /><figcaption>Calculated damage and the corresponding water depth for a case study in Berlin</figcaption></figure><h3>References:</h3><p><a href="https://www.wasserblick.net/servlet/is/219256/">BEAM-DE Basic European Assets Map</a></p><p><a href="https://www.wasserblick.net/servlet/is/219256/20220927_Empfehlung-PFRA-Anlage.pdf">https://www.wasserblick.net/servlet/is/219256/20220927_Empfehlung-PFRA-Anlage.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3f99c74eac8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parallel Simulations and Green Infrastructure Analysis with PySWMM]]></title>
            <link>https://medium.com/hydroinformatics/parallel-simulations-and-green-infrastructure-analysis-with-pyswmm-dbf79409b73e?source=rss-a76b76bcf2b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbf79409b73e</guid>
            <category><![CDATA[swmm5]]></category>
            <category><![CDATA[urban-planning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[floods]]></category>
            <category><![CDATA[green-infrastructure]]></category>
            <dc:creator><![CDATA[Omar Seleem]]></dc:creator>
            <pubDate>Wed, 02 Aug 2023 11:54:22 GMT</pubDate>
            <atom:updated>2023-08-02T11:54:22.970Z</atom:updated>
            <content:encoded><![CDATA[<p>PySWMM, a Python wrapper for the EPA Storm Water Management Model (SWMM), has become a powerful tool for simulating stormwater systems and analyzing their performance. Despite its capabilities, it lacks a direct approach to parallelizing simulations, which hinders the potential for executing multiple simulations in a shorter timeframe. In this article, I will show a way to run parallel simulations using PySWMM.</p><p><strong>The python script and the SWMM inp file are on </strong><a href="https://github.com/omarseleem92/PySWMM/tree/main"><strong>github</strong></a></p><p>The SWMM model enables the representation of various combinations of green infrastructure practices (also known as Low Impact Development (LID) techniques) to investigate their effectiveness in mitigating runoff generation and enhancing water storage. The performance of the LID controls depends on several parameters. For simplicity, this article focuses only on Bio-retention cells. The Bio-retention cell consists of 4 layers: surface, soil, storage, and drain layers, as shown in Figure 1. We will vary the following parameters:</p><ul><li>Sub-catchment area and width.</li><li>Ratio of Bio-retention area to the total sub-catchment area.</li><li>Berm height of the surface layer.</li><li>Thickness of the soil layer.</li><li>Thickness of the storage layer.</li><li>Seepage rate of the storage layer.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2E_qqz46E915jZxUFk7gZA.png" /><figcaption>Figure 1. Schematic figure of the bioretention unit model (source Lerer et al., 2022)</figcaption></figure><h3><strong>SWMM model:</strong></h3><p>Adopting a similar approach to Lerer et al., 2022, in order to distinguish the rainfall-runoff process in the catchment from the hydrological processes in the LID controls, I positioned the Bio-retention cell within a sub-catchment that receives excess runoff from the upstream sub-catchment (representing the area that drains into the Bio-retention cell), as depicted in Figure 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*zVRM5EUOZzzXtbiWFW4TGQ.png" /><figcaption>Figure 2. Schematic illustration of the water flows in the SWMM models used to simulate Bio-retention performance</figcaption></figure><h4><strong>Parallelizing PySWMM simuations:</strong></h4><p>The SWMM model is not thread-safe, which means that only one model can be opened at a time per ‘instance’ of Python. To overcome this limitation, we can utilize a combination of queue, threading, and subprocess. This approach enables us to run each model on its own process simultaneously. The workflow is as follows:</p><p>1- Begin by listing the parameters we need to vary and store them in a Queue (a list of job descriptions).</p><p>2- Utilize threads to handle the various jobs in the queue. Each thread represents a simulation that can run in parallel, and the number of threads depends on the system’s capabilities.</p><p>3- Within the worker function, call a subprocess to execute the ‘<a href="https://github.com/pyswmm/swmmio/blob/master/swmmio/wrapper/pyswmm_wrapper.py">pyswmm_wrapper.py</a>’ file, where we can make the desired changes to the SWMM model.</p><h4><strong>Python Script:</strong></h4><p>1- Begin by listing the parameters we need to vary and store them in a Queue (a list of job descriptions).</p><p>I generated 1000 random combinations of parameters (num_iterations) by selecting values within predefined ranges. These combinations were then stored in a queue named “simulations_queue.</p><pre># Number of simulations <br>num_iterations=1000 # You can change it depending on your problem<br><br># Parameter Range<br><br>area2_range=[0.02,0.2] # Percentage range of Bioretention cell area<br><br># Surface layer thickness<br>surface_thickness=[100,600]<br><br># soil layer thickness<br>soil_thickness=[300,600]<br><br>#Storage layer thickness<br>storage_thickness=[800,2000]<br><br>#Drain offset<br>drain_offset=[0,1000]<br><br>#Soil layer conductivity<br>seepage_rate=[0.5,120]<br><br># Create a queue and add all the simulations to it<br>simulations_queue = queue.Queue()<br>for _ in range(num_iterations):<br>        params = (<br>            round(random.uniform(min(area2_range), max(area2_range)), 2),<br>            round(random.uniform(min(surface_thickness), max(surface_thickness)), 2),<br>            round(random.uniform(min(soil_thickness), max(soil_thickness)), 2),<br>            round(random.uniform(min(storage_thickness), max(storage_thickness)), 2),<br>            random.choice(drain_offset),<br>            round(random.uniform(min(seepage_rate), max(seepage_rate)), 2)<br>        )<br>        simulations_queue.put(params)<br>#simulations_queue.get()</pre><p>2- Utilize threads to handle the various jobs in the queue. Each thread represents a simulation that can run in parallel, and the number of threads depends on the system’s capabilities.</p><p>In the following function:</p><ul><li>“pyswmm_wrapper.py” represents the Python code where we modify the parameters in the SWMM model and specify the desired output.</li><li>&#39;SWMM.inp&#39; refers to the SWMM model that we will modify using the &#39;pyswmm_wrapper.py&#39; code.</li><li>The list of parameters follows the same order as they are added to the simulation queue.</li><li>Finally, the function’s output is saved in pre-created lists for further analysis.</li></ul><pre># Function to process the simulations from the queue<br>def process_simulation_queue():<br>    while not simulations_queue.empty():<br>        sim_params = simulations_queue.get()<br>        result = subprocess.run([&quot;python&quot;, &quot;pyswmm_wrapper.py&quot;, &quot;SWMM.inp&quot;,<br>                                 str(sim_params[0]),  # A2<br>                                 str(sim_params[1]),  # Surface_thickness_value<br>                                 str(sim_params[2]),  # Soil_thickness_value<br>                                 str(sim_params[3]),  # Storage_thickness_value<br>                                 str(sim_params[4]),  # Drain_offset_value<br>                                 str(sim_params[5])   # Seepage_rate_value<br>                                ], capture_output=True, text=True)<br>        <br>        #print(result)<br>        #print(&quot;---------------------------------------------------------------------------------------------------&quot;)<br>        <br>                                 <br>        if result.returncode == 0:<br>            #print(&quot;YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY&quot;)<br>            output_lines = result.stdout.splitlines()<br>            #print(output_lines)<br>            Results_area2.append(float(output_lines[0]))           <br>            Results_Bio_surface_thickness.append(float(output_lines[1]))<br>            Results_Bio_soil_thickness.append(float(output_lines[2]))<br>            Results_Bio_storage_thickness.append(float(output_lines[3]))<br>            Results_Bio_drain_offset.append(float(output_lines[4]))<br>            Results_Bio_seepage_rate.append(float(output_lines[5]))<br>            Results_S1_stat.append(output_lines[6])<br>            Results_S2_stat.append(output_lines[7])<br>            Results_system_stat.append(output_lines[8])<br><br>        simulations_queue.task_done()</pre><p>Then, I made adjustments to the ‘<a href="https://github.com/omarseleem92/PySWMM/blob/main/Parallelizing%20PySWMM/pyswmm_wrapper.py">pyswmm_wrapper.py</a>’ to obtain the parameter values for each thread, perform the simulations, and subsequently return the parameter values along with the statistics of the two subcatchments and the entire system.</p><p>Finally we create and start the threads using the below code. You will need to adjust the <strong><em>number of threads</em></strong> as per your system&#39;s capabilities</p><pre># Create and start the threads<br>num_threads = 20  # Adjust the number of threads as per your system&#39;s capabilities<br>threads = []<br>start_time=time.time()<br>for _ in range(num_threads):<br>    thread = threading.Thread(target=process_simulation_queue)<br>    thread.start()<br>    threads.append(thread)<br><br># Wait for all threads to finish<br>for thread in threads:<br>    thread.join()<br>    <br>print(&quot;Finish&quot;)<br>end_time=time.time()<br><br>elapsed_time = (end_time - start_time)/3600<br><br>print(f&quot;Function took {elapsed_time:.6f} hrs to execute.&quot;)</pre><p>With the results now available, we can proceed to store them in a dataframe, facilitating further analysis. I would like to extend my gratitude to Bryant E. McDonnell for his invaluable guidance and support in resolving this matter.</p><h4>References:</h4><p>Lerer, S.M., Guidje, A.H., Drenck, K.M.L., Jakobsen, C.C., Arnbjerg-Nielsen, K., Mikkelsen, P.S. and Sørup, H.J.D., 2022. Constructing an inventory for fast screening of hydraulic and hydrologic performance of stormwater control measures. <em>Blue-Green Systems</em>, <em>4</em>(2), pp.213–229.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbf79409b73e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hydroinformatics/parallel-simulations-and-green-infrastructure-analysis-with-pyswmm-dbf79409b73e">Parallel Simulations and Green Infrastructure Analysis with PySWMM</a> was originally published in <a href="https://medium.com/hydroinformatics">Hydroinformatics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Towards urban flood susceptibility mapping using machine and deep learning models (part 5)…]]></title>
            <link>https://medium.com/hydroinformatics/towards-urban-flood-susceptibility-mapping-using-machine-and-deep-learning-models-part-5-d56c060964cc?source=rss-a76b76bcf2b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d56c060964cc</guid>
            <category><![CDATA[floods]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[urban-planning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Omar Seleem]]></dc:creator>
            <pubDate>Fri, 03 Feb 2023 20:57:09 GMT</pubDate>
            <atom:updated>2023-02-04T15:57:27.005Z</atom:updated>
            <content:encoded><![CDATA[<h3>Towards urban flood susceptibility mapping using machine and deep learning models (part 5): Convolutional neural networks</h3><blockquote>In the <a href="https://medium.com/hydroinformatics/towards-urban-flood-susceptibility-mapping-using-machine-and-deep-learning-models-part-4-a1ce44074872">last article</a>, we prepared a dataset to map urban flood susceptibility using convolutional neural networks (CNN) (image-based models). This article shows how to read the images, train the CNN model and use it to map urban flood susceptibility. This series of articles summarize and explain (with python code) the paper “ <a href="https://www.tandfonline.com/doi/full/10.1080/19475705.2022.2097131">Towards urban flood susceptibility mapping using data-driven models in Berlin, Germany</a>” published in Geomatics, Natural Hazards and Risk. The Python script and a data sample are found <a href="https://github.com/omarseleem92/flood_susceptibility_mapping">here</a></blockquote><p>We prepared two folders in the last article (Flooded and NotFlooded). Each folder includes images representing the predictive feature at each location in the flood inventory. Now we need to read these images and prepare it to be used as input to the model.</p><h3>Read the data and prepare it for the model</h3><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>import rasterio<br>import os<br>import cv2<br>import pandas as pd<br><br># Read the preditive features and the label (Notflooded=0 , flooded=1)<br>data_path=r&quot;D:\Predictive_features&quot; # created in data_preperation script (last article)<br>CATEGORIES= [&quot;NotFlooded&quot;, &quot;Flooded&quot;]<br><br>IMG_SIZE=23</pre><p>let us check that there is no error in the data by plotting a sample</p><pre># Check the images<br># plot the first band in the first image <br>for category in CATEGORIES:<br>    path=os.path.join(data_path,category) # Path to flooded and NotFlooded dir<br>    for img in os.listdir(path):<br>        img_open=rasterio.open(os.path.join(path,img))<br>        img_array=img_open.read(1) # open the image and read the first band<br>        #img_array= np.where(img_array &lt; 0, np.nan,img_array)<br>        #mean=np.nanmean(img_array)<br>        #img_array= np.where(np.isnan(img_array), mean,img_array)<br>        plt.imshow(img_array,cmap=&quot;gray&quot;)<br>        plt.show()<br>        #print(img_array)<br>        break<br>    break</pre><p>We used 11 predictive features, each feature is represented as a band in the images. i.e., each image has 11 bands. We need to read the images (11 bands and save them as a NumPy array). I prefer to save each predictive feature in a list of arrays. Therefore, I created an empty list for each predictive feature and then I put them in a list with the same order of the bands in the composite raster images.</p><pre># create a list for each predective feature<br><br>DEM=[]<br>Slope=[]<br>TWI=[]<br>DTRoad=[]<br>DTRiver=[]<br>CN=[]<br>Rain=[]<br>Aspect=[]<br>Curve=[]<br>Freq=[]<br>DTDrainage=[]<br>y=[]<br># we have 11 predictive features <br># every feature is presented in one band<br># create a list which include the 11 predictive feature to<br># loop over the predictive features<br>predictive_features=[DEM, Slope, TWI, DTRoad, DTRiver, CN, Rain, Aspect, Curve, Freq, DTDrainage] # the features muss be in the same order as the bands in the composite raster<br><br></pre><p>Now we can use the below function to read images and save them in the lists. Please note that we need also to save the label (0 if the location is not flooded or 1 if the location is flooded). As the flooded and not-flooded locations are saved in separate folders. I used this to get the label, if we read images from the Notflooded folder then they get a label 0 and 1 for images from the flooded folder.</p><pre>def create_training_data():<br>    for i in range(len(predictive_features)):<br>        print(i+1)<br>        for category in CATEGORIES:<br>            path= os.path.join(data_path,category) # Path to flooded and NotFlooded dir<br>            class_num= CATEGORIES.index(category)<br>            for img in os.listdir(path):<br>                try:<br>                    img_open=rasterio.open(os.path.join(path,img))<br>                    print(category,img,class_num)<br>                    img_array=img_open.read(i+1)<br>                    #img_array= np.where(img_array &lt; 0, np.nan,img_array)<br>                    #mean=np.nanmean(img_array)<br>                    #img_array= np.where(np.isnan(img_array), mean,img_array)<br>                    #new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))  # resize to normalize data size<br>                    predictive_features[i].append(img_array)<br>                    <br>                    if i==0:<br>                        y.append(class_num)<br>                        #print(class_num)<br>                except Exception as e:<br>                    pass<br>create_training_data()</pre><p>Now we have all the images saved in lists of Numpy arrays. We need to convert these lists of arrays into arrays with the following dimensions (Number of images * image size * image size * the number of bands). Using the sample data (84 * 23 * 23 * 1). Then, we need to combine all of the predictive features in one array with dimensions ( 84 * 23 * 23 *11 )</p><pre># convert the predictive feature lists to numpy arrays<br>DEM_array=np.array(DEM).reshape(-1, IMG_SIZE, IMG_SIZE, 1)<br>Slope_array=np.array(Slope).reshape(-1, IMG_SIZE, IMG_SIZE, 1)<br>TWI_array=np.array(TWI).reshape(-1, IMG_SIZE, IMG_SIZE, 1)<br>DTRoad_array=np.array(DTRoad).reshape(-1, IMG_SIZE, IMG_SIZE, 1)<br>DTRiver_array=np.array(DTRiver).reshape(-1, IMG_SIZE, IMG_SIZE, 1)<br>CN_array=np.array(CN).reshape(-1, IMG_SIZE, IMG_SIZE, 1)<br>DTDrainage_array=np.array(DTDrainage).reshape(-1, IMG_SIZE, IMG_SIZE, 1)<br>Aspect_array=np.array(Aspect).reshape(-1, IMG_SIZE, IMG_SIZE, 1)<br>Curvature_array=np.array(Curve).reshape(-1, IMG_SIZE, IMG_SIZE, 1)<br>Freq_Curve_array=np.array(Freq).reshape(-1, IMG_SIZE, IMG_SIZE, 1)<br>Rain_array=np.array(Rain).reshape(-1, IMG_SIZE, IMG_SIZE, 1)<br><br># concatenate all the predicvtive feature arrays into one array<br>X_array=np.concatenate([DEM_array,Slope_array,TWI_array,DTRoad_array, DTRiver_array,CN_array,Rain_array,Aspect_array, Curvature_array, Freq_Curve_array, DTDrainage_array], axis=-1)</pre><p>Then we split the data into training (60 %), validation (20 %) and testing (20 %). Firstly I split it into training and testing then later using Keras I will split the training data into training and validation</p><pre># split the data into training (60%), validation (20%) and testing (20%)<br><br>from sklearn.model_selection import train_test_split<br>x_train,x_test,y_train,y_test=train_test_split(X_array,y,test_size=0.2,random_state=42)</pre><h3>CNN Model: LeNet5 — Architecture</h3><p>In the paper, we used the LeNet5 architecture as shown in Fig 1. This architecture is simple and suitable when there is not much data to train the model. The model is explained in detail in the paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AlAMANHUvDvxQBRetrPBgA.png" /><figcaption>Fig 1. The used LeNet5 architecture</figcaption></figure><pre>import keras <br>from keras.models import Sequential<br>from keras.layers import Conv2D<br>from keras.layers import MaxPooling2D<br>from keras.layers import Flatten<br>from keras.layers import Dense<br>from keras.layers import Dropout<br>from keras.callbacks import TensorBoard<br><br>NAME = &quot;LeNet&quot;<br><br><br>model = Sequential()<br>#Layer 1<br>#Conv Layer 1<br>model.add(Conv2D(filters = 6, <br>                 kernel_size = 5, <br>                 strides = 1, <br>                 activation = &#39;relu&#39;, <br>                 input_shape = (23,23,11)))<br>#Pooling layer 1<br>model.add(MaxPooling2D(pool_size = 2, strides = 2))<br><br>#add a droupout<br>model.add(Dropout(0.4))<br><br>#Layer 2<br>#Conv Layer 2<br>model.add(Conv2D(filters = 16, <br>                 kernel_size = 5,<br>                 strides = 1,<br>                 activation = &#39;relu&#39;,<br>                 input_shape = (14,14,6)))<br>#Pooling Layer 2<br>model.add(MaxPooling2D(pool_size = 2, strides = 2))<br><br>#add a droupout<br>model.add(Dropout(0.4))<br><br><br>#Flatten<br>model.add(Flatten())<br><br><br>#Layer 3<br>#Fully connected layer 1<br>model.add(Dense(units = 120, activation = &#39;relu&#39;))<br><br>#add a droupout<br>model.add(Dropout(0.4))<br><br><br>#Layer 4<br>#Fully connected layer 2<br>model.add(Dense(units = 84, activation = &#39;relu&#39;))<br>model.add(Dropout(0.4))<br><br><br><br>#Layer 5<br>#Output Layer<br>model.add(Dense(units = 1, activation = &#39;sigmoid&#39;))<br><br>from keras.callbacks import ModelCheckpoint, EarlyStopping<br>checkpoint = ModelCheckpoint(&quot;LeNet.h5&quot;, monitor=&#39;val_loss&#39;, verbose=1, save_best_only=True, save_weights_only=False, mode=&#39;auto&#39;, period=1)<br>early = EarlyStopping(monitor=&#39;val_loss&#39;, min_delta=0, patience=20, verbose=1, mode=&#39;auto&#39;)<br><br>tensorboard = TensorBoard(log_dir=&quot;logs/{}&quot;.format(NAME))<br><br>model.compile(optimizer = &#39;adam&#39;, loss = &#39;binary_crossentropy&#39;, metrics = [&#39;accuracy&#39;])<br><br><br>model.summary()</pre><pre>history=model.fit(x_train ,y_train, batch_size=1024, epochs = 1000, validation_split=0.25, callbacks=[checkpoint,early,tensorboard])</pre><h3>Model Evaluation</h3><p>After training the model, we need first to check if the model is over or underfitting. We can look at the training and validation accuracy and loss at each epoch. The model must have similar performance on both datasets.</p><pre>#plot the training and validation accuracy and loss at each epoch<br>loss = history.history[&#39;loss&#39;]<br>val_loss = history.history[&#39;val_loss&#39;]<br>epochs = range(1, len(loss) + 1)<br>plt.plot(epochs, loss, &#39;y&#39;, label=&#39;Training loss&#39;)<br>plt.plot(epochs, val_loss, &#39;r&#39;, label=&#39;Validation loss&#39;)<br>plt.title(&#39;Training and validation loss&#39;)<br>plt.xlabel(&#39;Epochs&#39;)<br>plt.ylabel(&#39;Loss&#39;)<br>plt.legend()<br>plt.show()<br><br>acc = history.history[&#39;accuracy&#39;]<br>val_acc = history.history[&#39;val_accuracy&#39;]<br>plt.plot(epochs, acc, &#39;y&#39;, label=&#39;Training acc&#39;)<br>plt.plot(epochs, val_acc, &#39;r&#39;, label=&#39;Validation acc&#39;)<br>plt.title(&#39;Training and validation accuracy&#39;)<br>plt.xlabel(&#39;Epochs&#39;)<br>plt.ylabel(&#39;Accuracy&#39;)<br>plt.legend()<br>plt.show()</pre><p>Then, we can calculate performance indices as accuracy, kappa, and area under the ROC curve.</p><pre>_, acc = model.evaluate(x_test, y_test)<br>print(&quot;Accuracy = &quot;, (acc * 100.0), &quot;%&quot;)<br><br>#Confusion matrix<br>#We compare labels and plot them based on correct or wrong predictions.<br>#Since sigmoid outputs probabilities we need to apply threshold to convert to label.<br><br>mythreshold=0.5<br>from sklearn.metrics import confusion_matrix<br><br>y_pred = (model.predict(x_test)&gt;= mythreshold).astype(int)<br>cm=confusion_matrix(y_test, y_pred)  <br>print(cm)<br><br>from sklearn.metrics import classification_report<br>target_names = [&#39;NotFlooded&#39;, &#39;Flooded&#39;]<br>print(classification_report(y_test, y_pred_test, target_names=target_names))<br><br>from sklearn.metrics import cohen_kappa_score<br><br>cohen_kappa_score(y_test, y_pred, labels=None, weights=None)<br><br>#Check the confusion matrix for various thresholds. Which one is good?<br>#Need to balance positive, negative, false positive and false negative. <br>#ROC can help identify the right threshold.<br>#Receiver Operating Characteristic (ROC) Curve is a plot that helps us <br>#visualize the performance of a binary classifier when the threshold is varied. <br>#ROC<br><br>from sklearn.metrics import roc_curve<br>y_preds = model.predict(x_test).ravel()<br><br>fpr, tpr, thresholds = roc_curve(y_test, y_preds)<br>plt.figure(1)<br>plt.plot([0, 1], [0, 1], &#39;y--&#39;)<br>plt.plot(fpr, tpr, marker=&#39;.&#39;)<br>plt.xlabel(&#39;False positive rate&#39;)<br>plt.ylabel(&#39;True positive rate&#39;)<br>plt.title(&#39;ROC curve&#39;)<br>plt.show()<br><br>#AUC<br>#Area under the curve (AUC) for ROC plot can be used to understand how well a classifier is performing. <br>#% chance that the model can distinguish between positive and negative classes.<br><br>from sklearn.metrics import auc<br>auc_value = auc(fpr, tpr)<br>print(&quot;Area under curve, AUC = &quot;, auc_value)</pre><p>Finally, you can use the same steps to prepare data for the whole study area and predict the flood susceptibility for the whole area. It is not practical to use the CNN with a fine spatial resolution (&lt; 10 m) as mapping the study area will take too much time. We found that the CNN model could only recognize the topographic depressions as areas with high flood susceptibility at the fine resolutions (5 and 2 m) as shown in Fig 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CwSMMTqPwh7xfXophxyjdg.png" /><figcaption>Fig 2. Flood susceptibility mapping at different spatial resolutions.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d56c060964cc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hydroinformatics/towards-urban-flood-susceptibility-mapping-using-machine-and-deep-learning-models-part-5-d56c060964cc">Towards urban flood susceptibility mapping using machine and deep learning models (part 5)…</a> was originally published in <a href="https://medium.com/hydroinformatics">Hydroinformatics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Towards urban flood susceptibility mapping using machine and deep learning models (part 4)…]]></title>
            <link>https://medium.com/hydroinformatics/towards-urban-flood-susceptibility-mapping-using-machine-and-deep-learning-models-part-4-a1ce44074872?source=rss-a76b76bcf2b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1ce44074872</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[floods]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[urban]]></category>
            <dc:creator><![CDATA[Omar Seleem]]></dc:creator>
            <pubDate>Fri, 03 Feb 2023 09:45:00 GMT</pubDate>
            <atom:updated>2023-02-14T08:24:13.356Z</atom:updated>
            <content:encoded><![CDATA[<h3>Towards urban flood susceptibility mapping using machine and deep learning models (part 4): Convolutional neural networks</h3><blockquote>In this article, we will prepare the data to map urban flood susceptibility mapping using convolutional neural networks (CNN). This article shows how to develop the models and use the trained model to map urban flood susceptibility. This series of articles summarize and explain (with python code) the paper “ Towards urban flood susceptibility mapping using data-driven models in Berlin”. The complete Jupyter Notebook and a sample data for flooded and non flooded locations and the used predictive features in the paper are available <a href="https://github.com/omarseleem92/flood_susceptibility_mapping">here</a></blockquote><p>The first problem you face when you want to do a convolutional neural networks model is <strong><em>How to prepare your own dataset? </em></strong>all the online sources/courses are just using standard datasets so you do not know/learn how to prepare your own dataset.</p><p>In a previous <a href="https://medium.com/hydroinformatics/data-driven-model-for-mapping-urban-flooding-2-urban-flood-susceptibility-a346d7d751e">article</a>, I showed how to prepare datasets for the point-based model such as random forest and support vector machine. This article will show how to prepare data for convolutional neural networks using simple coding skills.</p><p>As mentioned before, we need flood inventory to map the urban flood susceptibility using the data-driven model. Flood inventories include flooded locations as points. Thus, we need to convert these points to images. We will continue as follow:</p><p>1- Convert the points to polygons (polygon dimensions represent the required image size). Then, we split the polygons&#39; shapefile into multiple shapefiles (each shapefile represents one polygon (image)) and save the flooded polygons and not flooded polygons in separate folders.</p><p>2- Read the raster (predictive feature) that you need to clip</p><p>3- Clip the raster with the polygons’ shapefiles</p><p>The final product of these steps is that we have two folders (Flooded and Notflooded) that include images corresponding to each flooded / Not flooded location (point).</p><h4>The used dataset and code are found <a href="https://github.com/omarseleem92/flood_susceptibility_mapping">here</a></h4><h3>1- Convert points to images(polygons) and split the polygons</h3><p>We will first import the packages which we will use. Then, we will use the buffer function to make a circle around the point then we use the envelope function to convert the circle to a square (image) as shown in Fig 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*kkwSRrs7FF3pSyBAP5W31Q.png" /><figcaption>Fig 1. Converting the point to an image with size (Image size x Image size).</figcaption></figure><pre># import the packages<br>import geopandas as gpd<br>import glob<br>import os<br>from osgeo import ogr<br>from osgeo import gdal<br>import numpy as np<br>import matplotlib.pyplot as plt</pre><pre># read the points shape file using geopandas and plot the points<br>points=gpd.read_file(&#39;Points.shp&#39;) <br>points.plot()</pre><pre>buffer_dist=115 #buffer distance = image size x spatial resolution /2<br><br># Read in the shapefile<br>points = gpd.read_file(&quot;Points.shp&quot;)<br><br># Create square buffers with a side length of buffer_dist units around the point features<br>points[&#39;geometry&#39;] = points.buffer(buffer_dist)<br><br>points[&#39;geometry&#39;] = points.geometry.envelope<br><br># Save the new shapefile<br>points.to_file(&quot;squares.shp&quot;)</pre><p>Now we have a polygon shapefile which includes all the flooded and non-flooded locations. Create a folder and call it <strong><em>divided. </em></strong>We then split the features in the polygon shapefile (save each feature in a separate shapefile)</p><pre># Split the flooded and nonflooded points <br>#points_flooded=points[points[&#39;Label&#39;]==1]<br>#points_notflooded=points[points[&#39;Label&#39;]==0]<br><br># Iterate over each feature in the shapefile<br>for index, feature in points.iterrows():<br>    # Create a new GeoDataFrame with just the current feature<br>    #print(index)<br>    <br>    feature_gdf = points.iloc[[index]]<br>    #print(feature_gdf)<br>    #print(feature_gdf[&#39;Label&#39;][index])<br>    <br>    <br>        <br>    # Save the feature to a new shapefile<br>    feature_gdf.to_file(r&quot;divided\feature_{}.shp&quot;.format(index))</pre><h3>2- Read the raster (predictive features) which you need to clip</h3><p>Here we open the raster using GDAL and read it as an array. We have several predictive features. Therefore, we can put all the predictive features in one raster (with several bands, each band represents one predictive feature ) or make a for loop to iterate over the predictive features so you repeat the following steps for each predictive feature.</p><p>Composite rasters can be made in Arcmap using the composite bands&#39; function or in QGIS as shown <a href="https://gis.stackexchange.com/questions/185064/how-to-make-band-composite-image-in-qgis">here</a></p><pre># Read raster files with GDAL<br># import <br>ds = gdal.Open(&quot;Composite_raster.tif&quot;) # open a raster with several bands, each band  represent one predictive feature<br>gt= ds.GetGeoTransform() #get the transformation data<br>proj = ds.GetProjection() #get the projection<br><br>band = ds.GetRasterBand(1) #read the first band <br>array = band.ReadAsArray() #read the first band as an array<br><br>plt.figure()  #plot the raster to check that you every thing is working well<br>plt.imshow(array)</pre><h3>3- Clip the raster with the polygons’ shapefiles</h3><p>Now we have the polygons which represent our images and the predictive features as a raster. So we will iterate over the polygons and clip the predictive features raster with each polygon. So the output will be two folders (Flooded and Notflooded) of images (in tiff format).</p><pre># change the path to the folder where we saved the splitted polygons<br>shp_path=r&quot;D:\divided&quot;<br>os.chdir(shp_path)<br>shp_file = glob.glob(&#39;*.shp&#39;)<br>#index =0<br>for file in shp_file:<br>        #print(str(file))         <br>        ds2 = ogr.Open(file, 1)<br>        layer = ds2.GetLayer()<br>        shp_ds=gpd.read_file(file)<br>        #print(shp_ds[&#39;Label&#39;][0])<br>        #index+=1<br>        # we will clip the raster with each polygon and save the flooded and notflooded locations in different folders<br>        # we will check the label, if label =0 then this is not flooded location<br>        # Label = 0 for non-flooded locations, Label = 1 for flooded locations<br>        if shp_ds[&#39;Label&#39;][0] == 0 : # clip and save not flooded locations<br>             #Save the feature to a new shapefile<br>            dsClip = gdal.Warp(r&quot;D:\Predictive_features\NotFlooded\feature_&quot;+str(file[:-4])+&quot;.tif&quot;, ds, cutlineDSName = file,<br>                       cropToCutline = True, dstNodata = np.nan)<br>        else: # clip and save flooded locations<br>            # Save the feature to a new shapefile<br>                  <br>            dsClip = gdal.Warp(r&quot;D:\Predictive_features\Flooded\feature_&quot;+str(file[:-4])+&quot;.tif&quot;, ds, cutlineDSName = file,<br>                       cropToCutline = True, dstNodata = np.nan)</pre><p>Now we prepared the images to train a convolutional neural network. In the next article, we will read these images in python and train the network.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1ce44074872" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hydroinformatics/towards-urban-flood-susceptibility-mapping-using-machine-and-deep-learning-models-part-4-a1ce44074872">Towards urban flood susceptibility mapping using machine and deep learning models (part 4)…</a> was originally published in <a href="https://medium.com/hydroinformatics">Hydroinformatics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using the topographic wetness index (TWI) to identify urban flood-prone areas.]]></title>
            <link>https://medium.com/hydroinformatics/using-the-topographic-wetness-index-twi-to-identify-urban-flood-prone-areas-65e50339ef7e?source=rss-a76b76bcf2b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/65e50339ef7e</guid>
            <category><![CDATA[urban-planning]]></category>
            <category><![CDATA[floods]]></category>
            <dc:creator><![CDATA[Omar Seleem]]></dc:creator>
            <pubDate>Wed, 11 Jan 2023 11:15:35 GMT</pubDate>
            <atom:updated>2023-01-11T11:27:27.255Z</atom:updated>
            <content:encoded><![CDATA[<p>This article summarizes the paper “Efficient Hazard Assessment for Pluvial Floods in Urban Environments: A Benchmarking Case Study for the City of Berlin, Germany” published in water. The python script used in this paper is <a href="https://github.com/omarseleem92/Urban-prone-area-based-on-topographic-indices/edit/main/readme">here</a>.</p><p>The Topographic Wetness Index (TWI) is a widely used method to analyze the hydrological behaviour of a landscape. It was introduced by Kirkby in 1975 based on the concept that water flows downhill, and calculates a numerical index that represents how “wet” a particular location is based on the combination of its slope and the upslope contributing area.</p><p>It is calculated using a simple mathematical formula that incorporates both the topographic slope and the specific catchment area. TWI is used in fields such as hydrology, geomorphology, ecology, and soil science to identify areas of high or low hydrologic potential, to identify potential erosion and sedimentation problems, and to map wetland and upland vegetation. TWI values can also be used as a predictor of soil moisture, evapotranspiration, and runoff. It’s a widely used technique for stream network extraction, and drainage pattern identification, it gives a good representation of the hydrological behaviour of a landscape. It is calculated using python or GIS as follows:</p><p>TWI = ln(a / tan(slope))</p><p>Where:</p><ul><li>“a” is the specific catchment area (the total area contributing runoff to a particular location)</li><li>“slope” is the local slope of the terrain, measured in radians</li></ul><h3>Identifying the urban flood-prone area (TWI method)</h3><p>The method is based on assuming that a location is defined as flood-prone (FP) if its TWI value exceeds a certain threshold (τ). The estimation of τ employs using the maximum likelihood function and the inundation maps from a hydrodynamic model based on the below equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxcMAY6tFBDU98Dv2wSnTA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*dY6oRDR7fo4Lt_i9.jpg" /><figcaption><strong>Figure.</strong> Flood-prone (FP) and inundated (IN) areas.</figcaption></figure><p>By using an inundation map for a small area within the city (called microscale ), the estimated TWI threshold identifies the flood-prone areas for the whole city (called mesoscale).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*HIRFBRUVsIBJLCIc.jpg" /><figcaption><strong>Figure.</strong> The spatial extent for the mesoscale and microscale.</figcaption></figure><p>We can then estimate the TWI threshold (τ) value associated with the maximum likelihood as shown in the below figure. The estimated threshold is τ = 5.3. This means, hence, that for a 100 mm storm, we would expect all areas in the city (mesoscale) with a TWI&gt;5.3 to inundate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*QNJcEc172dA14Od6.jpg" /><figcaption><strong>Figure.</strong> Likelihood function <em>L</em>(τ/<em>W</em>) for a 100 mm precipitation depth</figcaption></figure><h3>Limitations:</h3><p>1- The TWI method has the obvious advantage that a map of TWI values can be created with minimal effort from a DEM. The TWI method, however, requires a “calibration” in the sense that a TWI threshold τ has to be estimated above which a location is considered as flood-prone (by using maximum likelihood estimation). This calibration has to be repeated for each precipitation depth of interest. To this end, a reference is required, here are the simulation results of a hydrodynamic model (TELEMAC-2D). While this requirement is certainly undesirable, as it again involves the effort to set up and apply a hydrodynamic model.</p><p>2- Using maximum likelihood estimation, we were unable to identify a local likelihood maximum and hence a value for τ for lower but still impact-relevant precipitation depths.</p><p>3- It identifies flood-prone areas but it does not estimate the floodwater depth which is important for stormwater management.</p><h3>References</h3><ol><li>Kirkby, M. <em>Hydrograph Modelling Strategies, 69–90</em>; Peel, R., Chisholm, M., Haggert, P., Eds.; Processes in Physical and Human Geography, Heineman: London, UK, 1975. [<a href="https://scholar.google.com/scholar_lookup?title=Hydrograph+Modelling+Strategies,+69%E2%80%9390&amp;author=Kirkby,+M.&amp;publication_year=1975"><strong>Google Scholar</strong></a>]</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65e50339ef7e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hydroinformatics/using-the-topographic-wetness-index-twi-to-identify-urban-flood-prone-areas-65e50339ef7e">Using the topographic wetness index (TWI) to identify urban flood-prone areas.</a> was originally published in <a href="https://medium.com/hydroinformatics">Hydroinformatics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Towards urban flood susceptibility mapping using machine and deep learning models (part 3): Random…]]></title>
            <link>https://medium.com/hydroinformatics/towards-urban-flood-susceptibility-mapping-using-machine-and-deep-learning-models-3-random-9fe4e1279f3b?source=rss-a76b76bcf2b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fe4e1279f3b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[floods]]></category>
            <category><![CDATA[urban-planning]]></category>
            <dc:creator><![CDATA[Omar Seleem]]></dc:creator>
            <pubDate>Thu, 15 Dec 2022 19:21:54 GMT</pubDate>
            <atom:updated>2023-02-09T06:44:01.158Z</atom:updated>
            <content:encoded><![CDATA[<h3>Towards urban flood susceptibility mapping using machine and deep learning models (part 3): Random forest model</h3><p>In the <a href="https://medium.com/hydroinformatics/data-driven-model-for-mapping-urban-flooding-2-urban-flood-susceptibility-a346d7d751e">last article</a>, we prepared a dataset to map urban flood susceptibility using point-based models such as random forest (RF), support vector machine (SVM) and artificial neural network (ANN). This article shows how to develop the models and use the trained model to map urban flood susceptibility. This series of articles summarize and explain (with python code) the paper “ <a href="https://www.tandfonline.com/doi/full/10.1080/19475705.2022.2097131">Towards urban flood susceptibility mapping using data-driven models in Berlin, Germany</a>” published in Geomatics, Natural Hazards and Risk. The complete Jupyter Notebook and sample data for flooded and non-flooded locations and the used predictive features in the paper are available <a href="https://github.com/omarseleem92/flood_susceptibility_mapping">here</a></p><p>Deep learning is a subset of machine learning that uses neural networks to mimic the learning process of the human brain. The literature is rich with papers showing deep learning models outperforming traditional machine learning models. Deep learning models showed their superiority in different fields where the available data size was large. However, machine learning models are preferable with small data sizes.</p><p>It is challenging to collect a reliable flood inventory to map flood susceptibility (e.g., Termeh et al., <a href="https://www.tandfonline.com/doi/full/10.1080/19475705.2022.2097131#">2018</a> collected 53 flooded locations in an area of 5737 km2; Choubin et al., <a href="https://www.tandfonline.com/doi/full/10.1080/19475705.2022.2097131#">2019</a>: 51 locations in 126 km2; Zhao et al., 2020: 216 locations in 131 km2). New studies showed that machine-learning models outperformed deep-learning models for small datasets (Grinsztaj et al., 2022; Shwartz-Ziv and Armon 2022). Therefore, it is logical that machine learning models are more suitable for flood susceptibility than deep learning models.</p><h3>Random forest</h3><p>The random forest model consists of several individual decision trees. It divides the input dataset into several sub-samples and develops a decision tree model for each sub-sample. The final result is estimated based on the majority result of all the decision tree models (see figure below)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wsH5HZ8Z9RsimWiGJFK2zw.png" /><figcaption>Random forest model</figcaption></figure><p>Now we read the dataset, check for no-value data and drop them. Then we have a look at the correlation between the predictive features.</p><pre>import numpy as np<br>import cv2<br>import pandas as pd<br>from matplotlib import pyplot as plt<br>import seaborn as sns<br>import geopandas as gpd<br><br># Read the shapefile or pickle which we created in last article<br>df=gpd.read_file(&quot;points_data.shp&quot;)<br># df=pd.read_pickle(&quot;points_data.pkl&quot;) # in case of pickle<br>df.head()<br><br>#check that there is no no data values in the dataset<br>print(df.isnull().sum())<br>#df = df.dropna() # use this to remove rows with no data values <br><br>#Understand the data <br>#Here we can see that we have a balanced dataset (equal number of flooded and non flooeded locations<br>sns.countplot(x=&quot;Label&quot;, data=df) #0 - Notflooded   B - Flooded<br><br><br># show the correlation matric for the dataset<br>corrMatrix = df.corr()<br>fig, ax = plt.subplots(figsize=(10,10))         # Sample figsize in inches<br>#sns.heatmap(df.iloc[:, 1:6:], annot=True, linewidths=.5, ax=ax)<br>sns.heatmap(corrMatrix, annot=True, linewidths=.5, ax=ax)</pre><p>Your data frame should look like the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*hLrSVBfhRpCiUkRQlPh-cA.png" /><figcaption>The prepared dataset from the last article. The values in the table are normalized (between 0 and 1) as I used the same dataset with an artificial neural network. However, it is necessary to normalize the data for the random forests.</figcaption></figure><p>The dataset needs to be split into dependent and independent variables. The dependent variable is the variable that needs to be predicted (column name = Label) while the independent variables are the predictive features. The values in the Label column are 1 for flooded locations and 0 for non-flooded locations. The column geometry denotes the longitude and the latitude of the points and is automatically in the dataset because the dataset is originally a points shapefile.</p><p>Now, we will make two variables (X and Y). Y includes the label (dependent variable) and X includes the predictive features (independent variables). Then, we will split the dataset (X and Y) into training (60 %), validation (20%) and testing (20%) datasets. The training dataset is used to train the model while the validation dataset is used in hyperparameter tuning, i.e. estimating the best parameter combination that optimizes the model performance. Finally, the testing dataset is used to evaluate the model performance. Hence, we test the model on a dataset that was not included in the training and validation processes.</p><pre>#Define the dependent variable that needs to be predicted (labels)<br>Y = df[&quot;Label&quot;].values<br><br>#Define the independent variables. Let&#39;s also drop gemotry and label<br>X = df.drop(labels = [&quot;Label&quot;, &quot;geometry&quot;], axis=1) <br>features_list = list(X.columns)  #List features so we can rank their importance later <br><br>#Split data into train (60 %), validate (20 %) and test (20%) to verify accuracy after fitting the model.<br># training data is used to train the model<br># validation data is used for hyperparameter tuning<br># testing data is used to test the model<br><br>from sklearn.model_selection import train_test_split<br>X_train_val, X_test, y_train_val, y_test = train_test_split(X, Y, test_size=0.2,shuffle=True, random_state=42)<br>X_train, X_val, y_train, y_val = train_test_split(X_train_val, y_train_val, test_size=0.25,shuffle=True, random_state=42)</pre><p>Now we can train the random forest model. The model can be used for both classification and regression problems. However, flood susceptibility mapping is a classification problem as mentioned before. Therefore, we will use the RandomForestCalssifier from sklearn python module.</p><pre>#RANDOM FOREST<br>from sklearn.ensemble import RandomForestClassifier<br>model = RandomForestClassifier(random_state = 42) # I am using the default values of the parameters.<br><br># Train the model on training data<br>model.fit(X_train, y_train)<br><br># make prediction for the test dataset.<br>prediction = model.predict(X_test)<br><br># The prediction values are either 1 (Flooded) or 0 (Non-Flooded) <br>prediction<br><br># The AUC is considered one of the best performance indices<br># We can plot the curve and calculate it<br>from sklearn.metrics import plot_roc_curve<br><br>ax = plt.gca()<br>model_disp = plot_roc_curve(model, X_test, y_test, ax=ax, alpha=0.8)<br>plt.show()</pre><p>Please see <a href="https://towardsdatascience.com/hyperparameter-tuning-the-random-forest-in-python-using-scikit-learn-28d2aa77dd74">this article</a> for hyperparameter tuning. The random forest model has a built-in feature importance function which is implemented in scikit-learn python module. Hence, we can estimate which predictive features influence the model prediction.</p><pre># Estimate the feature importance<br>feature_imp = pd.Series(model.feature_importances_, index=features_list).sort_values(ascending=False)<br>print(feature_imp)<br><br># Plot the feature importance <br>feature_imp.plot.bar()</pre><p>Once you are satisfied with the model performance you can use the model to map flood susceptibility for your whole study area. We used the trained model to map flood susceptibility in Berlin. Firstly, we need a point shapefile for the whole study area as we did for the dataset in the <a href="https://medium.com/hydroinformatics/data-driven-model-for-mapping-urban-flooding-2-urban-flood-susceptibility-a346d7d751e">last article</a>.</p><pre># Read shapefile for the whole study area<br>df_SA=gpd.read_file(&quot;Study_area.shp&quot;)<br>df_SA.head() # make sure that the dataset has the same column arrangement as the training dataset<br><br>X_SA= df_SA.drop(labels = [&quot;geometry&quot;], axis=1) # we need to remove all the columns except the predictive features<br>X_SA.head()<br><br>prediction_SA = model.predict(X_SA) # predict if the location is flooded (1) or not flooded (0)<br><br># In order to map the flood susceptibility we need to cacluate the probability of being flooded<br>prediction_prob=model.predict_proba(X_SA) # This function return an array with lists <br># each list has two values [probability of being not flooded , probability of being flooded]<br><br># We need only the probablity of being flooded<br># We need to add the value coressponding to each point<br><br>df_SA[&#39;FSM&#39;]= prediction_prob[:,1]<br></pre><p>Now we have a point shapefile which has the flood susceptibility of each location. We need to convert it to a raster. There are many options. We can do this step in ArcMap or QGIS or we can continue in python.</p><pre># Save the dataframe tp a shapefile in case of converting the points to raster using QGIS or Arcmap<br>df_SA.to_file(&quot;FSM.shp&quot;)<br></pre><pre># Converting the point shapefile to raster.<br># We will use the model prediction (column FSM in df_SA to make a raster)<br>from geocube.api.core import make_geocube<br>import rasterio as rio<br><br>out_grid= make_geocube(vector_data=df_SA, measurements=[&quot;FSM&quot;], resolution=(-1, 1)) #for most crs negative comes first in resolution<br>out_grid[&quot;FSM&quot;].rio.to_raster(&quot;Flood_susceptibility.tif&quot;)</pre><p>Your final product would be a map like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*T5rAW_BkXqcT7jIhimP7KA.png" /></figure><p><strong>References</strong></p><p>Choubin B, Moradi E, Golshan M, Adamowski J, Sajedi-Hosseini F, Mosavi A. 2019. An ensemble prediction of flood susceptibility using multivariate discriminant analysis, classification and regression trees, and support vector machines. Sci Total Environ. 651(Pt 2):2087–2096.</p><p>Grinsztajn, L., Oyallon, E., &amp; Varoquaux, G. 2022. Why do tree-based models still outperform deep learning on tabular data?. <em>arXiv preprint arXiv:2207.08815</em>.</p><p>Shwartz-Ziv, R., &amp; Armon, A. 2022. Tabular data: Deep learning is not all you need. <em>Information Fusion</em>, <em>81</em>, 84–90.</p><p>Termeh SVR, Kornejady A, Pourghasemi HR, Keesstra S. 2018. Flood susceptibility mapping using novel ensembles of adaptive neuro fuzzy inference system and metaheuristic algorithms. Sci Total Environ. 615:438–451.</p><p>Zhao G, Pang B, Xu Z, Peng D, Zuo D. 2020. Urban flood susceptibility assessment based on convolutional neural networks. J Hydrol. 590:125235.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fe4e1279f3b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hydroinformatics/towards-urban-flood-susceptibility-mapping-using-machine-and-deep-learning-models-3-random-9fe4e1279f3b">Towards urban flood susceptibility mapping using machine and deep learning models (part 3): Random…</a> was originally published in <a href="https://medium.com/hydroinformatics">Hydroinformatics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Towards urban flood susceptibility mapping using machine and deep learning models (part 2)]]></title>
            <link>https://medium.com/hydroinformatics/data-driven-model-for-mapping-urban-flooding-2-urban-flood-susceptibility-a346d7d751e?source=rss-a76b76bcf2b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a346d7d751e</guid>
            <category><![CDATA[floods]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[urban-planning]]></category>
            <dc:creator><![CDATA[Omar Seleem]]></dc:creator>
            <pubDate>Tue, 13 Dec 2022 14:54:10 GMT</pubDate>
            <atom:updated>2023-02-09T06:43:18.344Z</atom:updated>
            <content:encoded><![CDATA[<p>We introduced urban pluvial flooding and the application of data-driven models to map urban pluvial flooding in the<a href="https://medium.com/hydroinformatics/data-driven-model-for-mapping-urban-flooding-1-d182a1e2dc9"> last article</a>. This series of articles summarize and explain (with python code) the paper “ <a href="https://www.tandfonline.com/doi/full/10.1080/19475705.2022.2097131">Towards urban flood susceptibility mapping using data-driven models in Berlin, Germany</a>” published in Geomatics, Natural Hazards and Risk. The complete Jupyter Notebook and a sample data for flooded and non flooded locations and the used predictive features in the paper are available <a href="https://github.com/omarseleem92/flood_susceptibility_mapping">here</a></p><p>Flood susceptibility maps show the likelihood that a specific location will experience flooding based on its physical characteristics, such as topography, infrastructure, and hydrometeorological conditions. Data-driven models approach it as a classification problem, i.e a location is either flooded or not flooded. Flooded and non-flooded locations are necessary to train, validate and test the data-driven models. A balanced dataset of equal number of flooded and not-flooded locations is necessary to train, validate and test the data-driven models. Flooded locations are obtained from flood inventories which include historical flood locations (see Fig. 1), while non-flooded locations are generated randomly in areas without flooding history. Data-driven models are then used to find a relationship between the characteristics of the flooded locations and flood occurrence.</p><figure><img alt="Spatial distribution of 4333 reported flooded locations between 2005 –2017 and administrative districts in Berlin, Germany." src="https://cdn-images-1.medium.com/max/1024/1*waDaUKNlnhqI_AHb3ripzw.jpeg" /><figcaption>Fig 1. Spatial distribution of 4333 reported flooded locations between 2005 –2017 and administrative districts in Berlin, Germany (The locations are obtained from Berlin Wasser Betrieb).</figcaption></figure><p>Urban pluvial flooding is expected to occur in low-elevated areas or within topographic depressions where runoff water tends to accumulate. Therefore topographic features such as altitude, slope, curvature and topographic wetness index (TWI) potentially indicate an increased flood hazard. Furthermore, urban pluvial flooding occurs due to the exceedance of the stormwater drainage system capacity. Excess runoff travels through the road network converting it to a preferential path. Therefore, the distance between a location and the nearest road, gully and channel are considered important to map flood susceptibility. Finally, urban pluvial flood is caused by intensive rainfall events. Thus, rainfall should be also included as a predictive feature. We used the maximum daily rainfall depth and the frequency of extreme rainfall events to represent the rainfall. Fig 2 shows the considered predictive features. These predictive features can be calculated in Arcmap, QGIS or python.</p><p>The paper compared the convolutioanl neural network (CNN)(raster-based model ) with traditional machine learning algorithms such as random forest (RF) and support vector machine (SVM)and artificial neural networks (ANN) (point-based models ). Our hypothesis was that the CNN is superior to other models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PLI6sVsNBG2wHkEjFEXFkw.png" /><figcaption>Fig 2. Spatial distribution of flood predictive features used to develop the models.</figcaption></figure><p>This article explains how to prepare the data for point-based models. We can read the shapefile containing flood and non-flooded points in python using geopandas. Then we need to add an empty column for each predictive feature.</p><pre># Import used packages<br>import geopandas as gpd  # used to read the shapfile<br>import rasterio as rio   # used to read the raster (.tif) files<br>from rasterio.plot import show # used to make plots using rasterio<br>import matplotlib.pyplot as plt #to make plots using matplotlib<br><br># Read your point shapefiles (Flooded and Non Flooded locations)<br>points=gpd.read_file(&#39;Points.shp&#39;)<br><br># make columns to extract the values of each predictive feature<br># for each point. <br>points[&#39;DEM&#39;]=0 #<br>points[&#39;Slope&#39;]=0<br>points[&#39;Aspect&#39;]=0<br>points[&#39;Curvature&#39;]=0<br>points[&#39;TWI&#39;]=0<br>points[&#39;DTDrainage&#39;]=0<br>points[&#39;DTRoad&#39;]=0<br>points[&#39;DTRiver&#39;]=0<br>points[&#39;CN&#39;]=0<br>points[&#39;AP&#39;]=0  #Max daily precipitation<br>points[&#39;FP&#39;]=0  #Frequency of extreme precipitation event.</pre><p>Then, we need to open the predictive features (raster images) using rasterio or gdal and read them as NumPy arrays so we can work with them in python.</p><pre>#The predictive features are in raster format so we use rasterio package to <br>#read them and convert them to numpy array<br><br>DEM_raster=rio.open(&#39;DEM.tif&#39;)<br>DEM_arr=DEM_raster.read(1)<br><br>Slope_raster=rio.open(&#39;Slope.tif&#39;)<br>Slope_arr=Slope_raster.read(1)<br><br>Aspect_raster=rio.open(&#39;Aspect.tif&#39;)<br>Aspect_arr=Aspect_raster.read(1)<br><br>Curvature_raster=rio.open(&#39;Curvature.tif&#39;)<br>Curvature_arr=Curvature_raster.read(1)<br><br>TWI_raster=rio.open(&#39;TWI.tif&#39;)<br>TWI_arr=TWI_raster.read(1)<br><br>DTRoad_raster=rio.open(&#39;DTRoad.tif&#39;)<br>DTRoad_arr=DTRoad_raster.read(1)<br><br>DTRiver_raster=rio.open(&#39;DTRiver.tif&#39;)<br>DTRiver_arr=DTRiver_raster.read(1)<br><br>DTDrainage_raster=rio.open(&#39;DTDrainage.tif&#39;)<br>DTDrainage_arr=DTDrainage_raster.read(1)<br><br>CN_raster=rio.open(&#39;CN.tif&#39;)<br>CN_arr=CN_raster.read(1)<br><br>AP_raster=rio.open(&#39;AP.tif&#39;)<br>AP_arr=AP_raster.read(1)<br><br>FP_raster=rio.open(&#39;FP.tif&#39;)<br>FP_arr=FP_raster.read(1)<br><br>#show point and raster on a matplotlib plot<br>fig, ax = plt.subplots(figsize=(12,12))<br>points.plot(ax=ax, color=&#39;orangered&#39;)<br>show(DEM_raster, ax=ax)</pre><p>Now we have read the points as a dataframe using geopandas and opened the predictive features using rasterio and read them as nump arrays. Next, we need to extract the predictive feature values for the flooded and non-flooded points.</p><pre># Extracting the raster values to the points shapefile<br># count=0<br>for index,row in points.iterrows(): #iterate over the points in the shapefile<br>    longitude=row[&#39;geometry&#39;].x #get the longitude of the point<br>    latitude=row[&#39;geometry&#39;].y  #get the latitude of the point<br><br>    #print(&quot;Longitude=&quot;+str(longitude))<br>    #print(count)<br>    #count +=1<br><br>    rowIndex, colIndex=DEM_raster.index(longitude,latitude) # the corresponding pixel to the point (longitude,latitude)<br><br>    # Extract the raster values at the point location<br>    points[&#39;DEM&#39;].loc[index]=DEM_arr[rowIndex, colIndex]<br>    points[&#39;Slope&#39;].loc[index]=Slope_arr[rowIndex, colIndex]<br>    points[&#39;Aspect&#39;].loc[index]=Aspect_arr[rowIndex, colIndex]<br>    points[&#39;Curvature&#39;].loc[index]=Curvature_arr[rowIndex, colIndex]<br>    points[&#39;DTRoad&#39;].loc[index]=DTRoad_arr[rowIndex, colIndex]<br>    points[&#39;DTRiver&#39;].loc[index]=DTRiver_arr[rowIndex, colIndex]<br>    points[&#39;DTDrainage&#39;].loc[index]=DTDrainage_arr[rowIndex, colIndex]<br>    points[&#39;TWI&#39;].loc[index]=TWI_arr[rowIndex, colIndex]<br>    points[&#39;CN&#39;].loc[index]=CN_arr[rowIndex, colIndex]<br>    points[&#39;AP&#39;].loc[index]=AP_arr[rowIndex, colIndex]<br>    points[&#39;FP&#39;].loc[index]=FP_arr[rowIndex, colIndex]<br><br>points.head() # to have a look on the calculated fields.<br><br># Save the points file<br>points.to_file(&#39;points_data.shp&#39;) # save as a shapfile <br># or<br>points.to_pickle(&#39;points_data.pkl&#39;) # save as a pickle.</pre><p>Now we have a points shapefile which specifies the location of flooded and non-flooded locations and includes the predictive feature values at each point. In the next article, we will explain how to implement point-based models to map urban pluvial flood susceptibility.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a346d7d751e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hydroinformatics/data-driven-model-for-mapping-urban-flooding-2-urban-flood-susceptibility-a346d7d751e">Towards urban flood susceptibility mapping using machine and deep learning models (part 2)</a> was originally published in <a href="https://medium.com/hydroinformatics">Hydroinformatics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Towards urban flood susceptibility mapping using machine and deep learning models (part1)]]></title>
            <link>https://medium.com/hydroinformatics/data-driven-model-for-mapping-urban-flooding-1-d182a1e2dc9?source=rss-a76b76bcf2b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d182a1e2dc9</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[floods]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[hydrology]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Omar Seleem]]></dc:creator>
            <pubDate>Tue, 29 Nov 2022 09:47:36 GMT</pubDate>
            <atom:updated>2023-02-03T21:08:00.570Z</atom:updated>
            <content:encoded><![CDATA[<p>In this series of articles, we will show the application of data-driven models in urban pluvial flood mitigation. Urban pluvial flood is caused by short intensive rainfall events that exceed the capacity of the storm drainage system. It could occur anywhere even in areas without flooding history. There are three types of flood maps as shown in the figure below:</p><ol><li>Flood susceptibility maps: they show the probability of flooding at a given location based on its physical characteristics.</li><li>Flood inundation maps: they identify the flood extent after or during a flood event. They are obtained from satellite images or drones.</li><li>Flood hazard maps: they show the spatial distribution of flood variables such as velocity, water depth, time of flooding, etc. They are obtained from hydrodynamic models.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*pjivyqUZyOQQgMoyZIKf7w.png" /><figcaption>Figure. Different types of flood maps (Bentivoglio et al.,2022)</figcaption></figure><p>While performing hydrologic modelling followed by 1D-2D hydrodynamic modelling is the best representation of the physical process of runoff generation and concentration in a complex urban watershed. These models are computationally expensive to be applied on a city scale and hence their application is limited to small study areas.</p><p>Data-driven models try to find a relationship between the input and output datasets (see Figure 2). They are raising as a surrogate to the complex hydrodynamic models. However, their major challenge is to generalise to a study area that was not included in the training dataset. Furthermore, they are considered as a black-box, they have a good performance but we are not able to understand how the model is working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*2L2VTYsMHV8hFua33Bq31Q.png" /><figcaption>Work flow of data-driven model</figcaption></figure><p>In the next articles, we will address the following:</p><ol><li>We will compare deep learning models with traditional machine learning algorithms for flood susceptibility and flood hazard mapping.</li><li>We will evaluate the models&#39; transferability in space.</li><li>We will use some methods to try to explain these black-box models.</li></ol><p>References:</p><p>Bentivoglio, R., Isufi, E., Jonkman, S. N., and Taormina, R.: Deep Learning Methods for Flood Mapping: A Review of Existing Applications and Future Research Directions, Hydrol. Earth Syst. Sci. Discuss. [preprint], <a href="https://doi.org/10.5194/hess-2021-614,">https://doi.org/10.5194/hess-2021-614,</a> 2021.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d182a1e2dc9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hydroinformatics/data-driven-model-for-mapping-urban-flooding-1-d182a1e2dc9">Towards urban flood susceptibility mapping using machine and deep learning models (part1)</a> was originally published in <a href="https://medium.com/hydroinformatics">Hydroinformatics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>