<?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 Stef on Medium]]></title>
        <description><![CDATA[Stories by Stef on Medium]]></description>
        <link>https://medium.com/@stefcroo?source=rss-3106fb9754ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Stef on Medium</title>
            <link>https://medium.com/@stefcroo?source=rss-3106fb9754ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 10:55:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stefcroo/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[Gas Production Profiles in Streamlit App]]></title>
            <link>https://stefcroo.medium.com/gas-production-profiles-in-dynamic-python-based-streamlit-app-e2fd20fe145e?source=rss-3106fb9754ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2fd20fe145e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[gas-production]]></category>
            <category><![CDATA[netherlands]]></category>
            <category><![CDATA[energy]]></category>
            <category><![CDATA[streamlit]]></category>
            <dc:creator><![CDATA[Stef]]></dc:creator>
            <pubDate>Thu, 03 Feb 2022 20:03:04 GMT</pubDate>
            <atom:updated>2023-04-05T12:31:17.005Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mD0xT43e6E4vCQFqM61ZgQ.gif" /><figcaption>App built to track production profiles of on- and offshore gas fields in the Netherlands</figcaption></figure><p>Dutch Gas production data is publicly available and its abundance makes for an suitable big data project to dissect using Python packages including (geo)pandas, matplotlib, folium, json, (geo)pandas and seaborn. This article explores how an exploratory data analysis tool can be built using Python’s Streamlit as an app framework.</p><p>Streamlit is an open-source framework built on Python, which allows for rapid deployment of Python code to an application.</p><p>Consolidating data combined with effective visualisation can save hours of time searching databases and extracting useful information. Streamlit’s user-friendly open-source framework allows for neat and elegant deployment of products derived from processed data in Python.</p><p>Python’s capabilities allow to gain powerful insights with just of a few lines of code. Subsequently, high level observations about macro (gas production) trends can be made to drive meaningful policy and business decisions. The next sections will cover the datasets and key functionality of the app.</p><h3>Datasets</h3><p>The following open-source datasets have been used to build this app:</p><ul><li><a href="https://www.nlog.nl/datacenter/"><strong>NLOG</strong></a><strong> :</strong> Production data for fields and wells on- and offshore the Netherlands since 2003. Displayed Production data from Natural (indigenous) Gas contains extraction of natural gas from nature, on-shore and off-shore fields in the Dutch territorial part of the North Sea. Data available from oil, gas and geothermal wells for every month since 2003.</li><li><a href="https://opendata.cbs.nl/#/CBS/en/dataset/00372eng/table"><strong>CBS</strong></a>: National data on gas production, imports (liquefied natural gas (LNG) &amp; natural gas), exports and stock change.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4L9de9o4Hgaz-q4fIeDBUQ.png" /></figure><h3><strong>App</strong> <strong>Functionality</strong></h3><p>The production data spans over a period of from 2003 to 2021 and can be grouped by Year, Well, Field and Operator and hydrocarbon phase.</p><p>Data filters are added to provide customisation to the figures and map. We can dynamically extract unique values from our dataframe that respond to the user inputs. Based on user inputs, the dataframe is filtered and figures are updated.</p><h3><strong>Dynamic Data Filter</strong></h3><p>The aim of this project is to gain valuable insights from a large dataset of production profiles by dissecting a large dataset with Python code. The Streamlit app has the ability to generate and store figures on the fly based on user inputs.</p><p>The user input filters the data and dynamically updates figures and the map in the app as shown here:</p><pre>operator_dropdown = [&#39;ALL&#39;]+ list(df[&#39;OPERATOR&#39;].unique())<br>operator = st.selectbox(&#39;Operator&#39;,operator_dropdown)<br>if operator !=&#39;ALL&#39;:<br>    df = df.loc[df[&#39;OPERATOR&#39;]==operator].reset_index(drop=True)</pre><pre>field_dropdown = [&#39;ALL&#39;]+ list(df[&#39;FIELD&#39;].unique())<br>field = st.selectbox(&#39;Field&#39;,field_dropdown)<br>if field !=&#39;ALL&#39;:<br>    df = df.loc[df[&#39;FIELD&#39;]==field].reset_index(drop=True)</pre><pre>well_dropdown = [&#39;ALL&#39;]+ list(df[&#39;WELL&#39;].unique())<br>well = st.selectbox(&#39;Well&#39;,well_dropdown)<br>if well!=&#39;ALL&#39;:<br>    df = df.loc[df[&#39;WELL&#39;]==well].reset_index(drop=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wcrh4wZNFHTa4vaB3BNVnQ.gif" /><figcaption>Data filter in Streamlit</figcaption></figure><p>In order to understand the relative contributions of components to the aggregate data can be according to the aforementioned filters. In the example below we study relative temporal contribution of individual fields and wells to operator and field production, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6HvVxxDe6YS77SSXP6k6fA.png" /><figcaption>Field (left) and well (right) production profiles displayed. In blue production as a share of total Operator and Field production, respectively.</figcaption></figure><pre>fd[&#39;FIELD_PRODUCTION_YEAR&#39;] = fd.groupby([&#39;OPERATOR&#39;,&#39;YEAR&#39;])[&#39;PRODUCTION&#39;].transform(&#39;sum&#39;)</pre><pre># Calculate the percentage<br>fd[&#39;PRODUCTION_FIELD_SHARE&#39;] = 100*fd[&#39;PRODUCTION&#39;]/fd[&#39;FIELD_PRODUCTION_YEAR&#39;]</pre><pre># Check if all numbers add up to 100%<br>fd.loc[(fd[&#39;OPERATOR&#39;]==&#39;Dana&#39;)&amp;(fd[&#39;YEAR&#39;]==2009)][&#39;PRODUCTION_FIELD_SHARE&#39;].sum()</pre><pre># Create Plots<br>def field_fig(field, df, field_op, operator):<br>    colors = {&#39;Dana&#39;:&#39;#fee391&#39;,<br>    &#39;GDF&#39;:&#39;#ef3b2c&#39;,<br>    &#39;Kistos&#39;:&#39;#e0f3f8&#39;,<br>    &#39;NAM&#39;:&#39;#41ab5d&#39;,<br>    &#39;Neptune&#39;: &#39;#fb6a4a&#39;,<br>    &#39;ONE-Dyas&#39;: &#39;#e6f5d0&#39;,<br>    &#39;Petrogas&#39;:&#39;#ffffbf&#39;,<br>    &#39;Spirit&#39;:&#39;#e7298a&#39;,<br>    &#39;Taqa&#39;:&#39;#74add1&#39;,<br>    &#39;Total&#39;: &#39;#8c6bb1&#39;,<br>    &#39;Vermilion&#39;:&#39;#636363&#39;,<br>    &#39;Wintershall&#39;:&#39;#4292c6&#39;,<br>    &#39;ALL&#39;:&#39;#ef3b2c&#39;}<br>    <br>    if field==&#39;ALL&#39;:<br>        field = field_op.loc[field_op[&#39;OPERATOR&#39;]==operator].reset_index(drop=True)[&#39;FIELD&#39;][0]<br>    df = df.loc[df[&#39;FIELD&#39;]==field]<br>    fig2, ax2 = plt.subplots(figsize=(12,8))<br>    ax2.set_xlim(2003-.5,2021+.5)<br>    ax2.bar(df[&#39;YEAR&#39;], df[&#39;PRODUCTION&#39;], alpha = 0.5, label = f&#39;{field}&#39;,color=colors[operator],edgecolor=&#39;black&#39;)<br>    ax2.set_title(f&#39;{field} Field Annual Production since 2003&#39;, fontsize=25)<br>    ax2.grid()<br>    ax2.legend(loc=&#39;upper right&#39;, prop = {&#39;size&#39;:24})<br>    ax2.tick_params(axis=&#39;both&#39;, which=&#39;major&#39;, labelsize=20)<br>    ax2.set_xticks(np.arange(2003,2022,2))<br>    ax2.set_ylabel(&#39;Production bln m\u00b3&#39;, fontsize=26)<br>    ax2.set_xlabel(&#39;Year&#39;, fontsize=26)<br>    ax22 = ax2.twinx()<br>    ax22.plot(df[&#39;YEAR&#39;], df[&#39;PRODUCTION_FIELD_SHARE&#39;], color= &#39;blue&#39;, linewidth=2)<br>    ax22.set_ylabel(&#39;Operator Share %&#39;,fontsize=23, color=&#39;blue&#39;)<br>    ax22.tick_params(axis=&#39;both&#39;, which=&#39;major&#39;, labelsize=16)<br>    ax22.set_ylim([0,100])<br>    ax22.tick_params(axis=&#39;y&#39;, colors=&#39;blue&#39;)<br>    plt.tight_layout()<br></pre><h3><strong>Show Information When Hovering Over Fields in Map</strong></h3><p>To visualise data the app contains a folium map with two layers of geospatial data: licenses and field data. Both are supplied as shapefiles and can be converted to geojson data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n8FbUBaBNHUevabqk7HgUA.gif" /></figure><p>If an operator is selected the fields associated with the operator on the map are highlighted.</p><p>By hovering over the field one can supplement information such on field name, operator, well count, production share and total production.</p><pre>def add_fields(m,gdf, colors):<br>highlight_function = lambda x: {&#39;fillColor&#39;: &#39;#000000&#39;,<br>&#39;color&#39;:&#39;#000000&#39;, &#39;fillOpacity&#39;: 0.80, &#39;weight&#39;: 0.1}</pre><pre>for i in range(len(gdf)):<br>   row = gdf.loc[[i]]<br>   feature = folium.features.GeoJson(<br>   row, <br>   style_function=lambda feature: {<br>        &#39;fillColor&#39;: getcolor(feature, colors),<br>        &#39;weight&#39;: 1,<br>        &#39;opacity&#39;:.8,<br>        &#39;color&#39;:&#39;#525252&#39;,<br>        &#39;fillOpacity&#39;: 0.6},<br>   control=False,<br>   zoom_on_click=True,<br>   highlight_function=highlight_function,<br>   tooltip=folium.features.GeoJsonTooltip(<br>       fields=[<br>           &#39;FIELD&#39;,&#39;OPERATOR&#39;, &#39;WELL_COUNT&#39;, &#39;2021_SHARE&#39;, &#39;PRODUCTION_SINCE_2003&#39;],</pre><pre>       aliases=[<br>           &quot;Field: &quot;,<br>           &#39;Operator: &#39;,<br>           &#39;Well count:&#39;,<br>           &#39;2021 National Prod. %: &#39;,<br>           &#39;Production since 2003 bln m\u00b3: &#39;<br>       ],<br>       style=(&quot;background-color: white; color: #333333; font-family: arial; font-size: 13px; padding: 4px;&quot;),<br>       sticky=True)</pre><pre>)<br>   m.add_child(feature)<br>   m.keep_in_front(feature)<br>return m</pre><p>To access the complete code for the application click on the link below:</p><p><a href="https://github.com/stefcroo/NL_production_data">https://github.com/stefcroo/NL_production_data</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2fd20fe145e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Groningen Earthquake data with Python]]></title>
            <link>https://stefcroo.medium.com/exploring-groningen-earthquake-data-with-python-4dde2586b7ca?source=rss-3106fb9754ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dde2586b7ca</guid>
            <category><![CDATA[netherlands]]></category>
            <category><![CDATA[geoscience]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[earthquake]]></category>
            <dc:creator><![CDATA[Stef]]></dc:creator>
            <pubDate>Wed, 05 Jan 2022 19:01:46 GMT</pubDate>
            <atom:updated>2023-04-11T04:39:35.193Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring Groningen Earthquake data in Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5Qw3nSdtdbMgQ7EVvqMfA.gif" /><figcaption>Heat map of earthquake occurrences since January 2000. Polygons include Groningen province (black) and gas/oil fields (grey). Created with folium.</figcaption></figure><h3>Datasets</h3><p>In the mid 1990’s, the Royal Netherlands Meteorological Institute (KNMI) constructed a network of seismometers to measure the occurrences of earthquakes in Groningen. Earthquake data is monitored by the KNMI and can be scraped through API requests. Based on the longitude and latitude of the data we can filter the data within the geometry of a shapefile, in this case the province of Groningen.</p><pre>from shapely.geometry import Point</pre><pre>provinces = &#39;data/provincies/B1_Provinciegrenzen_van_NederlandPolygon.shp&#39;<br>provinces = gpd.read_file(provinces)<br>provinces.to_crs(epsg=4326, inplace=True)</pre><pre>df = pd.read_csv(&#39;output_df_earthquakes.csv&#39;)<br>df[&#39;within&#39;] = &quot;&quot;<br>gdf = GeoDataFrame(df, geometry=geometry)<br>gdf.to_crs(epsg=4326, inplace = True)<br>groningen = provinces[provinces.PROV_NAAM==&#39;Groningen&#39;]</pre><pre>within_list = []<br>for lon,lat in zip(df.lon, df.lat):<br>    pt =  Point(lon, lat)<br>    groningen = groningen.geometry<br>    within = pt.within(groningen.geometry.values[0]) # this yields values within the province<br>    within_list.append(within)</pre><pre>df[&#39;within&#39;] = within_list<br>df_within = df.loc[df.within ==True]</pre><h3>Github Repositories</h3><p>The code used to generate the graphics in this article can be found in this GitHub repositories below. Packages used for this project include selenium, json, pandas, seaborn, folium, and geopandas.</p><ul><li>API requests from the KNMI <a href="https://github.com/stefcroo/api_request_knmi">https://github.com/stefcroo/api_request_knmi</a></li><li>Web Scraping Borehole data from NLOG <a href="https://github.com/stefcroo/webscrape_nlog_well_data">https://github.com/stefcroo/webscrape_nlog_well_data</a></li><li>Generate Folium Heat Map <a href="https://github.com/stefcroo/generate_heat_map">https://github.com/stefcroo/generate_heat_map</a></li><li>Create avi from png <a href="https://github.com/stefcroo/video_from_png-s">https://github.com/stefcroo/video_from_png-s</a></li></ul><h3>Declining Production of the Groningen Gas Field</h3><p>The Groningen gas field was discovered in 1957. Since then, hundreds of wells have been drilled to enhance production from the field. Production <a href="https://www.nam.nl/gas-en-olie/gaswinning.html#iframe=L2VtYmVkL2NvbXBvbmVudC8_aWQ9Z2Fzd2lubmluZw">ramped up to 80–90 billion Nm³ per annum in 1970’s</a> and became responsible for nearly 7% of the GDP for the next decade.</p><p>Gas from the Groningen gas field is produced from a reservoir at a depth of approximately 3km. These reservoir contains compressed sand-grains which make up the matrix of the rock. Fluid filled pore space makes up the remainder of the rock. Fluid (gas) depletion causes the <em>sponge </em>to compress which in turn causes subsidence and differential stress along faults. The stress across faults builds and when movement occurs energy is released resulting in the occurrence of an earthquake.</p><h3>Have Earthquakes decreased in magnitude with decreasing gas production?</h3><p>Reservoir depletion combined with increasing political pressure due to damage of surrounding houses have <a href="https://www.nam.nl/gas-en-olie/gaswinning.html#iframe=L2VtYmVkL2NvbXBvbmVudC8_aWQ9Z2Fzd2lubmluZw">caused gas production to steadily decline at an annual rate of 10–15% from 52 billion Nm³ in 2013</a>. Politicians have decided to cease production from the largest gas field in the Netherlands in the coming year(s).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y7JfjqIKw4jHNDbWkFBClA.png" /><figcaption>Significant increase in earthquakes in Groningen since the early 2000&#39;s. Data highlights a disproportional increase in lower ’magnitude earthquakes since the beginning of the 21st century. See code below.</figcaption></figure><pre>import seaborn as sns<br>import numpy as np<br>import matplotlib.pyplot as plt</pre><pre>def add_mean_line(data, var=None, **kws):<br>    # Derive mean for each group<br>    m = np.mean(data[var])<br>    nums = np.array(data[var])<br>    # get axis <br>    ax = plt.gca()<br>    #add line at group_mean<br>    ax.axvline(m, color=&#39;black&#39;, lw=2, ls=&#39;--&#39;)<br>    # Annotate Group Mean<br>    x_pos = 0.5<br>    ax.text(x_pos, .6, f&#39;mean={m:.2f}&#39; &#39;\n&#39; f&#39;count={nums.size:.0f}&#39;,<br>            transform = ax.transAxes, fontsize=12)</pre><pre>sns.set_style(&#39;white&#39;)<br>bins = [0,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2,2.2,2.4,2.6,2.8,3.0,3.2,3.4,3.6,3.8]<br>var =&#39;mag&#39;<br>g = sns.FacetGrid(df, col=&#39;cat_y&#39;,col_wrap=2, sharex=False, xlim=(0,3.5))<br>g.map_dataframe(sns.histplot, x= &#39;mag&#39;, edgecolor=&quot;black&quot;, bins=bins)<br>g.map_dataframe(add_mean_line, var =var)<br>g.set_axis_labels(&#39;Magnitude&#39;, &#39;Frequency&#39;, fontsize=14)<br>g.set_titles(col_template = &#39;{col_name}&#39;, size=14)</pre><pre>g.fig.tight_layout()<br>g.savefig(&#39;facetgrid.png&#39;, dpi=300)</pre><p>The KNMI data highlights a twofold increase in earthquake occurrences in Groningen in the past decade relative to the beginning of the century. The number of earthquakes annually has increased to 100 per year in Groningen alone. More than 80% of the recorded earthquakes are below a magnitude of 2.0. Although it is possible that an increasing number of earthquakes occur, the <a href="https://www.knmi.nl/kennis-en-datacentrum/uitleg/aardbevingen-door-gaswinning">KNMI explains that it has increased the density of its stations since 2014–15 and subsequently has become better at identifying lower magnitude earthquakes.</a> The growth in earthquakes appears to have flattened in the past few years and may be linked to the sharp decline in gas production. The number of &gt;3 magnitude earthquakes appears steady, although they do continue to occur. The big questions is whether the decreasing production will pay dividends and lead to a further reduction of both the frequency and magnitude of earthquakes. Such a result may prove significant in affecting future government policies in- and outside the Netherlands.</p><h3>Spatial Distribution of Earthquakes across the Netherlands</h3><pre>def generate_heat_map(df, df2, date, colorGradient, colorGradient2):</pre><pre>#Give a start location<br>    location=[53.2194, 6.7563]</pre><pre># Filter dataframe by dates<br>    df = df.loc[df.dates&lt;=date]<br>    df2 = df2.loc[df2.dates&lt;=date]    <br># Assign heat map<br>    heat_map = folium.Map(location=location, tiles = &#39;CartoDB    positron&#39;, zoom_start=9) <br>    # save all lat and lon and rescaled magnitudes to list values <br>    latlons = df2[[&#39;lat&#39;, &#39;lon&#39;]].values.tolist()<br>    HeatMap(latlons, gradient=colorGradient2,min_opacity=.7, blur=1,   radius=2).add_to(heat_map)<br>    heat_map = add_provinces(provinces,heat_map)<br>    heat_map = add_fields(fields, heat_map)<br>    heat_map.save(f&#39;earthquakes_{date}.html&#39;)<br>    time.sleep(1)<br>    save_png(date)</pre><pre>dates = df.dates.unique()<br>start_date = str(dates[0])[:10]<br>stop_date = str(dates[-1])[:10]<br>start = datetime.strptime(start_date, &quot;%Y-%m-%d&quot;)<br>stop = datetime.strptime(stop_date, &quot;%Y-%m-%d&quot;)</pre><pre>colorGradient = {0.0:&#39;blue&#39;,0.25:&#39;cyan&#39;,0.5:&#39;lime&#39;,0.75:&#39;yellow&#39;, 1.0:&#39;red&#39;}<br>colorGradient2 = {0.0:&#39;grey&#39;,1.0:&#39;grey&#39;}</pre><pre>#loop through dates <br>while start &lt; stop:<br>    generate_heat_map(df, df2, start, colorGradient,colorGradient2)<br>    start = start + relativedelta(months=+1)</pre><p>The heat map shows the spatial distribution of of earthquakes since 2000 across the Groningen province. The earthquakes coincide with the outlines of the gas fields and appear to spread more towards the outer edges of the field (deeper parts of the gas reservoir) that get depleted with increasing production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dde2586b7ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>