<?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 Lorenzo Perozzi on Medium]]></title>
        <description><![CDATA[Stories by Lorenzo Perozzi on Medium]]></description>
        <link>https://medium.com/@lorenzoperozzi?source=rss-406aa32ffdee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ifxMSMb_bP0ugLcdkH_DQw.jpeg</url>
            <title>Stories by Lorenzo Perozzi on Medium</title>
            <link>https://medium.com/@lorenzoperozzi?source=rss-406aa32ffdee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 17:14:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lorenzoperozzi/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[Exploring spatial interpolation]]></title>
            <link>https://medium.com/@lorenzoperozzi/exploring-spatial-interpolation-f41e86d37a05?source=rss-406aa32ffdee------2</link>
            <guid isPermaLink="false">https://medium.com/p/f41e86d37a05</guid>
            <category><![CDATA[geostatistics]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[geospatial]]></category>
            <category><![CDATA[spatial-analysis]]></category>
            <category><![CDATA[plotly]]></category>
            <dc:creator><![CDATA[Lorenzo Perozzi]]></dc:creator>
            <pubDate>Tue, 05 Apr 2022 06:40:40 GMT</pubDate>
            <atom:updated>2022-04-05T06:45:09.559Z</atom:updated>
            <content:encoded><![CDATA[<p>Which algorithm is best fitted to interpolate location-oriented data?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjFHbWFc2hTiUvM0PSsXqA.png" /><figcaption>spatial-interpolation webapp</figcaption></figure><h3>Overview</h3><p>In the previous post I explained how to create a GIS webapp using <a href="https://dash.plotly.com/">plotly Dash</a>, a productive Python framework for building web analytic applications. With this post I would like to show how we can use dash to render 3D data, using dash-vtk. With dash-vtk you can for example render a mesh representing a <a href="https://dash.gallery/dash-vtk-explorer/pyvista-point-cloud">LiDAR dataset</a> or a <a href="https://dash.gallery/dash-vtk-explorer/pyvista-terrain-following-mesh">Terrain following mesh</a>. The objective here is to compare different algorithms used to interpolate the depth of a geological unit (Molasse) in the Geneva (Switzerland) area.</p><p>There is a GitHub <a href="https://github.com/lperozzi/Spatial_interpolation_analysis">repository</a> associated with this tutorial with the notebook for the spatial analysis.</p><p>The app is hosted on GitHub <a href="https://github.com/lperozzi/Spatial_interpolation_app">here</a> and deployed on Heroku at this address <a href="https://spatial-interpolation.herokuapp.com/">https://spatial-interpolation.herokuapp.com/</a>. Be patient, it takes a few seconds to wake app the Heroku dynos 🤞🤞.</p><h3><strong>About</strong></h3><p>The dataset used in this tutorials is from the well land register managed by the geological survey of the Canton of Geneva (GESDEC) and it is part of the open data catalogue of the SITG (Système d’Information du Territoire à Genève). It can be downloaded <a href="https://ge.ch/sitg/fiche/4108">here</a>. from this dataset we want to interpolate the depth of the Molasse over a subregion of the Geneva, using the following interpolation algorithms:</p><ul><li>Nearest-neighbors;</li><li>Biharmonic spline (usingverde);</li><li>Gaussian processes;</li><li>Kriging;</li><li>Sequential Gaussian Simulation;</li></ul><h3>Dataset</h3><p>The dataset can be downloaded <a href="https://ge.ch/sitg/fiche/4108">here</a> or fetched using the opendata.swiss API as follows:</p><pre>from zipfile import ZipFile<br>import urllib.request<br>from io import BytesIO<br>data_url = ‘<a href="https://ge.ch/sitg/geodata/SITG/OPENDATA/4108/CSV_GOL_SONDAGE.zip&#39;">https://ge.ch/sitg/geodata/SITG/OPENDATA/4108/CSV_GOL_SONDAGE.zip&#39;</a></pre><pre>zip_file = ZipFile(BytesIO(urllib.request.urlopen(data_url).read()))</pre><pre>dfs = {text_file.filename: pd.read_csv(zip_file.open(text_file.filename), encoding=’ISO-8859–1&#39;, <br>sep=’;’,)<br> for text_file in zip_file.infolist()<br> if text_file.filename.endswith(‘.csv’)}</pre><pre>sondage = dfs[‘GOL_SONDAGE.csv’]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*jnK0fz_0KKucrx8cG3JbDw.png" /><figcaption>Subset of wells with measured depth of Molasse in Geneva (Switzerland)</figcaption></figure><h3>Interpolation algorithms</h3><p>Refers to <a href="https://github.com/lperozzi/Spatial_interpolation_analysis/tree/master/notebook">these notebooks</a> for a detailed explanation of the spatial analysis presented in the next section.</p><h4>Nearest neighbors</h4><p>The easiest way to apply the NN algorithm is by using the <a href="https://www.fatiando.org/verde/latest/">Verde</a> package (Uieda L, 2018)¹. The dataset has been BlockReduced to a regular grid of 50m x 50m.</p><pre>import verde as vd<br>hain = vd.Chain(<br>    [<br>        (&quot;mean&quot;, vd.BlockReduce(np.mean, spacing=spacing )),<br>        (&quot;spline&quot;, vd.ScipyGridder(method=&quot;nearest&quot;)),<br>    ]<br>)<br><br>train, test = vd.train_test_split(<br>    coordinates,df.MOLASSE, random_state=0<br>)<br><br>chain.fit(*train)<br><br>grid = chain.grid(<br>    region=region,<br>    spacing=spacing,<br>    dims=[&quot;N&quot;, &quot;E&quot;],<br>    data_names=&quot;MOLASSE&quot;,<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*Ce-l5ykWsctXT4IDzeXGoQ.png" /><figcaption>Nearest-neighbor interpolation</figcaption></figure><h4>Biharmonic spline (default)</h4><p>Next a biharmonic spline interpolation using Green’s functions has been tested, where the two main parameters are mindist, the minimum distance the point forces and data points and damping, that controls how much smoothness is imposed on the estimated forces.</p><pre>chain = vd.Chain(<br>    [<br>        (&quot;mean&quot;, vd.BlockReduce(np.mean, spacing=spacing )),<br>        (&quot;spline&quot;, vd.Spline()),<br>    ]<br>)<br><br>chain.fit(coordinates, df.MOLASSE)<br><br>grid = chain.grid(<br>    region=region,<br>    spacing=spacing,<br>    # projection=projection,<br>    dims=[&quot;N&quot;, &quot;E&quot;],<br>    data_names=&quot;MOLASSE&quot;,<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*3fmZ-GEjpatxdLHQ2FHHcg.png" /><figcaption>Biharmonic spline interpolation with default parameters</figcaption></figure><h4>Biharmonic spline (cross validated)</h4><p>The verde.SplineCV class provides a cross-validated version of verde.Spline. It has almost the same interface but does all of the above automatically when fitting a dataset. The only difference is that you must provide a list of damping and mindist parameters to try instead of only a single value:</p><pre>dampings = [None, 1e-4, 1e-3, 1e-2]<br>mindists = [1e-5, 1, 100, 1000, 1000]<br><br>spline = vd.SplineCV(<br>    dampings=dampings,<br>    mindists=mindists,<br>)<br>spline.fit(coordinates, df.MOLASSE)<br>print(&quot;Highest score:&quot;, spline.scores_.max())<br>print(&quot;Best damping:&quot;, spline.damping_)<br>print(&quot;Best mindist:&quot;, spline.mindist_)</pre><p>Calling fit will run a grid search over all parameter combinations to find the one that maximizes the cross-validation score.</p><pre>chain = vd.Chain(<br>    [<br>        (&quot;mean&quot;, vd.BlockReduce(np.mean, spacing=spacing )),<br>        (&quot;spline&quot;, vd.Spline(damping=spline.damping_, mindist=spline.mindist_)),<br><br>    ]<br>)<br><br>chain.fit(coordinates,df.MOLASSE)<br><br>grid = chain.grid(<br>    region=region,<br>    spacing=spacing,<br>    # projection=projection,<br>    dims=[&quot;N&quot;, &quot;E&quot;],<br>    data_names=&quot;MOLASSE&quot;,<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*32TXNZPBR3uM5OfAc2HYcg.png" /><figcaption>Biharmonic spline interpolation after cross validation</figcaption></figure><p>Notice that, for sparse data like these, smoother models tend to be better predictors. This is a sign that you should probably not trust many of the short wavelength features that we get from the defaults.</p><h4>Gaussian Processes</h4><p>Gaussian Processes (GP) are a generic supervised learning method designed to solve regression and probabilistic classification problems.</p><p>The advantages of Gaussian processes are:</p><ul><li>The prediction interpolates the observations (at least for regular kernels).</li><li>The prediction is probabilistic (Gaussian) so that one can compute empirical confidence intervals and decide based on those if one should refit (online fitting, adaptive fitting) the prediction in some region of interest.</li><li>Versatile: different kernels can be specified. Common kernels are provided, but it is also possible to specify custom kernels.</li></ul><pre>from sklearn.gaussian_process.kernels import RBF<br>from sklearn.gaussian_process import GaussianProcessRegressor as GPR<br>from sklearn.gaussian_process.kernels import RBF, ConstantKernel as C<br><br>kernel = C(50.0) * RBF([50 ,50])<br><br><br>gp = GPR(normalize_y=True, alpha=0.5, kernel=kernel,)<br><br>gp.fit(df[[&#39;E&#39;, &#39;N&#39;]].values, df.MOLASSE.values)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*pmZ8Ai2NcCpCZ8SvObg85g.png" /><figcaption>Gaussian Processes interpolation</figcaption></figure><h4>Kriging</h4><p>Kriging is a widly used spatial interpolator. Here we use the GeostatPy package (Pyrcz et al., 2021)², which is the python version of translated to Python from the original FORTRAN GSLIB: Geostatistical Library methods (Deutsch and Journel, 1997)³ . Here are some important properties of kriging (Pyrcz, 2021):</p><ul><li>Exact interpolator — kriging estimates with the data values at the data locations</li><li>Kriging variance can be calculated before getting the sample information, as the kriging estimation variance is not dependent on the values of the data nor the kriging estimate, i.e. the kriging estimator is homoscedastic.</li><li>Spatial context — kriging takes into account, furthermore to the statements on spatial continuity, closeness and redundancy we can state that kriging accounts for the configuration of the data and structural continuity of the variable being estimated.</li><li>Scale — kriging may be generalized to account for the support volume of the data and estimate. We will cover this later.</li><li>Multivariate — kriging may be generalized to account for multiple secondary data in the spatial estimate with the cokriging system. We will cover this later.</li><li>Smoothing effect of kriging can be forecast. We will use this to build stochastic simulations later.</li></ul><p>The step to obtain a kriging estimate are a little more complex, first a variogram should be computed. For an in depth review of variogram calculation and modeling look <a href="https://github.com/GeostatsGuy/PythonNumericalDemos/blob/master/GeostatsPy_variogram_calculation.ipynb">here</a> and <a href="https://github.com/GeostatsGuy/PythonNumericalDemos/blob/master/GeostatsPy_variogram_modeling.ipynb">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AWxNDB63Nn-xqSzbrqLhTw.png" /><figcaption>Ordinary Kriging interpolation</figcaption></figure><h4>Sequential Gaussian Simulation</h4><p>The objective of SGS is to building spatial models that honor the univariate and spatial distribution of the property of interest. As for Kriging some excellent resources for SGS can be found <a href="https://github.com/GeostatsGuy/PythonNumericalDemos/blob/master/GeostatsPy_simulation.ipynb">here</a>, <a href="https://github.com/GeostatsGuy/PythonNumericalDemos/blob/master/GeostatsPy_kriging_vs_simulation.ipynb">here</a>, and <a href="https://github.com/GeostatsGuy/PythonNumericalDemos/blob/master/GeostatsPy_simulation_postsim.ipynb">here</a>.</p><p>For this tutorials 10 likely realization have been generated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*08MBbd0ZL1GP05G8l1vkdg.png" /><figcaption>Sequential Gaussian Simulation realization of the depth of the Molasse</figcaption></figure><p>One advantage of the geostatistical simulations over Kriging and determinist interpolators is the possibility to summarize uncertainty over the realizations that is useful for:</p><ul><li>Quantifying local uncertainty away from wells</li><li>Accessing the probability / risk of specific local outcomes</li></ul><p>In particular we focus on the following local summaries:</p><ul><li><strong>e-type</strong> is the local expectation (since equal weighted the same as the average)</li><li><strong>conditional standard deviation</strong> is the local standard deviation over the realizations</li><li><strong>local percentile</strong> is the local percentile over the realizations</li></ul><h4>E-type and Conditional Variance</h4><p>We will start with the e-type and the conditional variance.</p><ul><li><strong>e-type</strong> is the local expectation (just the average of the L realizations at location u(α​) as we assume all realizations are equally likely).</li><li><strong>conditional variance</strong> is the local variance</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*G9lLWVXRyyc3WVuPN9Pv9w.png" /><figcaption>E-type and local standard deviation of realizations</figcaption></figure><p>The e-type model is very similar to a kriging model, except for:</p><ul><li>the Gaussian forward and back transform may change the results</li><li>result are noisy due to too few realizations</li></ul><p>The conditional variance is lowest at the data locations and increased away from the data</p><ul><li>the result is noisy due to too few realizations</li></ul><h4>Local Percentiles</h4><p>Now let’s look at the:</p><ul><li><strong>local percentile</strong> maps are the maps with the local percentile values sampled from the local realizations</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o_XyjVjhbxTr--PPHuMP9w.png" /><figcaption>Local percentiles of realizations</figcaption></figure><p>We can interpret them as follows, at a location if we have a local P10 of -300m, then we have a 90% probability of the depth is closer to the surface.</p><p>🚀🚀 Let’s explore all the interpolated surfaces interactively in 3D through this <a href="https://spatial-interpolation.herokuapp.com/">app</a> (Be patient, it takes a few seconds to wake app the Heroku dynos). 🚀🚀</p><h3>Additional resources</h3><p>There is a GitHub <a href="https://github.com/lperozzi/dash-tutorial">repository</a> associated with this tutorial if you are interested.</p><p>There are lots of tutorials and resources on Dash, here is a short list of them:</p><h4>Spatial analysis in python</h4><ul><li><a href="https://www.youtube.com/GeostatsGuyLectures">Youtube channel of GeostatGuy lectures</a></li><li><a href="https://github.com/GeostatsGuy">Github of GeostatGuy with a lot, really a lot of high level resources in data analytics, geostatistics and Machine Learning</a></li><li><a href="https://www.fatiando.org/">Fatiando a Terra — Fatiando provides Python libraries for data processing, modeling, and inversion across the Geosciences</a></li></ul><h4>Web app</h4><ul><li><a href="https://www.youtube.com/c/CharmingData/videos">Youtube channel of Charming Data</a></li><li><a href="https://dash-bootstrap-components.opensource.faculty.ai/examples/">Dash Bootstrap Components examples</a></li><li><a href="https://www.geomaap.io/blog/tutorial/dash-tutorial">A journey into Plotly Dash</a></li><li><a href="https://community.plotly.com/c/dash/python/25">Dash community forum</a></li></ul><p>That’s it, enjoy interpolating with your own data! If you found this tutorial useful, please leave a comment below. 👇👇👇</p><p><em>Originally published at </em><a href="https://www.geomaap.io/blog/tutorial/dash-tutorial"><em>https://www.geomaap.io</em></a><em> on April 01, 2022</em></p><h4><strong>References</strong></h4><p>[1]: Uieda, L. (2018). Verde: Processing and gridding spatial data using Green’s functions. Journal of Open Source Software, 3(29), 957. doi:10.21105/joss.00957</p><p>[2]: Pyrcz, M.J., Jo. H., Kupenko, A., Liu, W., Gigliotti, A.E., Salomaki, T., and Santos, J., 2021, GeostatsPy Python Package, PyPI, Python Package Index</p><p>[3]: Deutsch, Clayton V., and A. G. Journel. 1998. <em>GSLIB: geostatistical software library and user’s guide</em>. New York: Oxford University Press.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f41e86d37a05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A journey into Plotly Dash]]></title>
            <link>https://medium.com/@lorenzoperozzi/a-journey-into-plotly-dash-5791228212ff?source=rss-406aa32ffdee------2</link>
            <guid isPermaLink="false">https://medium.com/p/5791228212ff</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dash]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[gis-web]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Lorenzo Perozzi]]></dc:creator>
            <pubDate>Wed, 10 Nov 2021 00:00:00 GMT</pubDate>
            <atom:updated>2021-11-15T10:35:05.393Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sYo20i1usRbW_yk8.png" /></figure><h3><strong>Overview</strong></h3><p><a href="https://dash.plotly.com/">Plotly Dash</a> is a productive Python framework for building web analytic applications. It is fairly easy to use and allows the creation of awesome web applications. Written on top of Plotly.js and React.js, Dash is ideal for building and deploying data apps with customized user interfaces in pure Python. Plotly’s Python is a free and open-source graphing library that makes interactive, publication-quality graphs and maps. A series of tutorials and tips about fundamental features of Plotly’s python are available <a href="https://plotly.com/python/plotly-fundamentals/">here</a>.</p><p>Dash It’s particularly suited for anyone who works with data. Dash apps are rendered in the web browser. You can deploy your apps to VMs or Kubernetes clusters and then share them through URLs. Since Dash apps are viewed in the web browser, Dash is inherently cross-platform and mobile-ready. To see the potential of Dash look at the <a href="https://dash.gallery/Portal/">Dash App Gallery</a>.</p><p>This article will show how to use Plotly Dash to create a simple GIS web app similar to the <a href="https://gecosapp.herokuapp.com/">GECOS app</a> developed by the <a href="https://www.unige.ch/ge-rgba/welcome/">GE-RGBA</a> group of the University of Geneva.</p><h3>About</h3><p>So, we have a nice geodataset, we have made a great analysis on it and we want to disseminate the results. One way is to plot the result on a map. One awesome example is <a href="https://timogrossenbacher.ch/2019/04/bivariate-maps-with-ggplot2-and-sf/">Switzerland’s regional income (in-)equality</a> map made by <a href="https://timogrossenbacher.ch/">Timo Grossenbacher</a> using the ggplot2 R package. This is nice for printed communication such as journals or infographics but we cannot interact with the data. To display multiple datasets GIS software such as <a href="https://qgis.org/">QGIS</a> offers lots of (advanced) tools. However, they have two main limitations:</p><ul><li>the user needs to have an installed version of the GIS software,</li><li>due to their steep learning, only GIS professionals will really use it.</li></ul><p>Instead, Web GIS applications allow us to disseminate the results to a broader audience, including public users who may know less or nothing about GIS, such as Governments/Administration/public stakeholders, in a user-friendly way that is specifically designed for simplicity, intuition, and convenience, making it typically much easier to use than desktop GIS.</p><h3>Dataset</h3><p>The dataset used is similar to the one used in the <a href="https://gecos.geoenergy.ch/">GECOS</a> web app however, due to permission limitations it has been slightly modified. It contains 6 columns:</p><pre>====  =======  =======  ============  ============  =======  =====<br>..        X        Y  MEASUREMEN      TARGET DEP    SCORE    COS<br>====  =======  =======  ============  ============  =======  =====<br>0  6.05173  46.1659  Gravimetry            3000        5      1<br>1  6.05175  46.165   Seismic 2D             500       20     40<br>2  6.05178  46.1641  Seismic 2D            2000       20      5<br>3  6.0518   46.1632  Seismic 2D            1000       15     49<br>4  6.05302  46.1659  Gravimetry            3000        5      8<br>====  =======  =======  ============  ============  =======  =====</pre><p>The target is to map SCORE and COS column in Dash. Here coordinates are already in EPSG:4326; however, we need to convert from local projection (for Switzerland this is often EPSG:2056) to global Mercator projection. In <a href="https://www.geomaap.io/blog/visualization/DST-viz-pydeck">this</a> post, I showed how to do that.</p><h3>Dash app</h3><h4>Packages and data</h4><p>The Dash python packages are:</p><pre>import dash</pre><pre>from dash.dependencies import Input, Output, State<br>from dash import dcc<br>from dash import html</pre><p>In addition import dash_bootstrap_components as dbc has been used. <a href="https://dash-bootstrap-components.opensource.faculty.ai/">Dash-bootstrap-components</a> is a library of Bootstrap components for Plotly Dash, that makes it easier to build consistently styled apps with complex, responsive layouts. Another very useful resource for the app layout is <a href="https://hellodash.pythonanywhere.com/">Dash Bootstrap Theme Explorers</a>.</p><p>Then we need to import the Plotly Python library for graphing. <a href="https://plotly.com/python/maps/">Here</a> there is a list of available Maps we can create with Plotly and <a href="https://www.mapbox.com/">Mapbox</a>. We are interested to create a Hexagonal Binning density map. This technique allows aggregating points into hexagon as the following images show and it is particularly useful for visualizing large numbers of points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*4FUZUgmQTepDCZP-ce1UxA.png" /><figcaption>Hexagonal Binning (source: <a href="https://eng.uber.com/h3/">https://eng.uber.com/h3/</a>)</figcaption></figure><p>The Plotly package we need for hexbin map is:</p><pre>import plotly.figure_factory as ff</pre><p>then we also need:</p><pre>import pandas as pd<br>import numpy as np<br>import math<br>import geopandas as gpd</pre><p>especially pandas will be used to import and apply a few operations to the data.</p><h3>App layout</h3><p>After importing all the necessary package, we start the app:</p><pre>app = dash.Dash(__name__,<br>                external_stylesheets=[dbc.themes.LUX],<br>                title=&#39;GEOMAAP.io | Hexbin Map example&#39;,<br>                meta_tags=[{&#39;name&#39;: &#39;viewport&#39;,<br>                            &#39;content&#39;: &#39;width=device-width,    <br>                                        height=device-height,  <br>                                        initial-scale=1.0, <br>                                        maximum-scale=1.2&#39;}]<br>                )</pre><p>where the meta_tags arguments allow controlling the size of the app component through different devices size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KOIcdEmWc-IhSHhLBmBtjQ.png" /><figcaption>App layout structure</figcaption></figure><h4><strong>Navigation bar</strong></h4><p>The navigation bar represents the title of the application. Thanks to the dash bootstrap components package, we can use dbc.Row and dbc.Col to subdivide the layout. For the Navbar we have a row and two columns representing the logo and the title:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3b9053d10d5f7dc4c180eb5372a59af/href">https://medium.com/media/b3b9053d10d5f7dc4c180eb5372a59af/href</a></iframe><p><strong>Control Layout<br></strong>The control layout is where we interact with the map. Dash core <a href="https://dash.plotly.com/dash-core-components">components</a> allow for interactive user interfaces. For this tutorial, we used a mix of Dash core components and <a href="https://dash-bootstrap-components.opensource.faculty.ai/docs/components/">dash bootstrap components</a> library that makes it easier to build responsive layouts. In particular, we used <strong>RangeSlider</strong>, <strong>Dropdown,</strong> and <strong>Markdown</strong> components, inside <strong>Card</strong> bootstrap components.</p><p>The range slider for targeting the depth of investigation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/667a76599d6be6ae29fc74746f6e3a21/href">https://medium.com/media/667a76599d6be6ae29fc74746f6e3a21/href</a></iframe><p>The colormap choice and hexagon resolution:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cc156d8a6aa46045b4a934ced683555/href">https://medium.com/media/3cc156d8a6aa46045b4a934ced683555/href</a></iframe><p>and the card with some text:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b93306022bf1a26aabda5d2dfca7004/href">https://medium.com/media/8b93306022bf1a26aabda5d2dfca7004/href</a></iframe><h4>Map layout</h4><p>The right side of the app is where the hexbin maps are visualized. A convenient way to visualize different maps without decreasing their size is by using self-contained tabs component:</p><p>We first define the density and chance of success (cos) map components:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fa02bac835dcfd476c77a73b2c86d02/href">https://medium.com/media/2fa02bac835dcfd476c77a73b2c86d02/href</a></iframe><p>And we then make a tabs component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/209281825c27bbc7ff41210039b6dc1d/href">https://medium.com/media/209281825c27bbc7ff41210039b6dc1d/href</a></iframe><p>Finally, we put all the individual components together, where the left layout occupies 4/12 ( width=4) columns and the right layout (maps) 8/12 ( width=8) columns:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1882202c70dffdf1dc547c0958dde69/href">https://medium.com/media/c1882202c70dffdf1dc547c0958dde69/href</a></iframe><h3>App callbacks</h3><p>The last part (but the most important) part of a Dash application are the callback functions: functions that are automatically called by Dash whenever an input component’s property changes, in order to update some property in another component (the output). To better understand how callback functions <a href="https://dash.plotly.com/basic-callbacks">this</a> is a very good start.</p><p>We have two maps and 3 components to interact with each map. We then need two callback functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a68f3237efb790e1caa9bd55d63e0e2/href">https://medium.com/media/9a68f3237efb790e1caa9bd55d63e0e2/href</a></iframe><p>The last step is to activate the app with these two lines:</p><pre>if __name__ == &quot;__main__&quot;:<br>    app.run_server(debug=True)</pre><p>You are now ready to lunch the app with the command:</p><pre>python app.py</pre><p>and the Dash app will open at the address <a href="http://127.0.0.1:8050/">http://127.0.0.1:8050/</a></p><p>That’s it, enjoy Dash! If you found this tutorial useful, please leave a comment below. 👇</p><h3>Dash resources</h3><p>There is a GitHub <a href="https://github.com/lperozzi/dash-tutorial">repository</a> associated with this tutorial if you are interested.</p><p>There are lots of tutorials and resources on Dash, here is a short list of them:</p><p>- Youtube channel of Charming Data:<br><a href="https://www.youtube.com/c/CharmingData/videos">https://www.youtube.com/c/CharmingData/videos</a></p><p>- Dash Bootstrap Components examples:<br><a href="https://dash-bootstrap-components.opensource.faculty.ai/examples/">https://dash-bootstrap-components.opensource.faculty.ai/examples/</a></p><p>- Dash community forum:<br><a href="https://community.plotly.com/c/dash/python/25">https://community.plotly.com/c/dash/python/25</a></p><p><em>Originally published at </em><a href="https://www.geomaap.io/blog/tutorial/dash-tutorial"><em>https://www.geomaap.io</em></a><em> on November 10, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5791228212ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visual exploratory analysis with pydeck]]></title>
            <link>https://medium.com/@lorenzoperozzi/visual-exploratory-analysis-with-pydeck-19423f679aa4?source=rss-406aa32ffdee------2</link>
            <guid isPermaLink="false">https://medium.com/p/19423f679aa4</guid>
            <category><![CDATA[pydeck]]></category>
            <category><![CDATA[deckgl]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Lorenzo Perozzi]]></dc:creator>
            <pubDate>Tue, 28 Sep 2021 00:00:00 GMT</pubDate>
            <atom:updated>2021-11-15T11:48:26.284Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fC-UudXtsOan-6HM.png" /></figure><h3>Overview</h3><p>This tutorial is part of a Data Science Tools meeting organized by the <a href="https://datascience.unige.ch/en">Data Science Competence Center (CDD)</a> of the University of Geneva (Switzerland).<br>The GitHub repo is available <a href="https://github.com/lperozzi/DST1_pydeck_visual">here</a>.</p><h3>About</h3><p>Geothermal is a hot topic right now in Switzerland and especially in the Canton of Geneva. <a href="https://www.geothermies.ch/#">The ongoing 3D seismic exploration campaign</a>, which aims to better understand the subsurface structures and geological properties and develop geothermal energy that will be integrated into the district heating of the Canton of Geneva, to reduce the dependence on fossil fuels. For the moment, geothermal probes are the most common method of using geothermal heat in Switzerland. The probes extract geothermal energy from the soil and conduct it via a heat pump to a heating system.</p><p>During this tutorial, it will be shown how to use python to process and visualize a dataset about geothermal probes availability in the Canton of Geneva. This dataset can be obtained (open access) through the <a href="https://ge.ch/sitg/fiche/6867">SITG</a> (Système d’Information du Territoire à Genève). We will cover these aspects:</p><ul><li>Load the geothermal probes dataset from the [Système d’Information du<br>Territoire à Genève (SITG)](<a href="https://ge.ch/sitg/fiche/6867">https://ge.ch/sitg/fiche/6867</a>);</li><li>Convert CRS coordinate system with pyproj;</li><li>Extract depth information from attributes;</li><li>Visualizing the results with pydeck .</li></ul><h3>Import packages</h3><pre>import pydeck<br>import pandas as pd<br>import numpy as np<br>import matplotlib.cm<br>import matplotlib.pyplot as plt<br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)  # filter out warning messages</pre><pre>plt.rcParams[&#39;figure.dpi&#39;] = 150 # plot bigger figure inlineLoad and inspect the dataset</pre><p>The dataset is stored on the <a href="https://ge.ch/sitg/fiche/6867">SITG</a> (Système d’information du territoire à Genève) and publicly available.</p><pre>filename = &#39;data/CTSS_CHAUFFAGE_SONDE.csv&#39;</pre><p>To open the dataset we use the package. By default in a csv file, columns are separated by a comma (,), however, we can specify different methods for this. In this tutorial, the dataset columns are separated by a semicolon, we need then to specify the sep arguments in the pd.read_csv class.</p><pre>sondes = pd.read_csv(filename, encoding=&#39;latin-1&#39;, sep=&#39;;&#39;)</pre><p>We can inspect the dataset.</p><pre>sondes.head(5) # first 5 rows</pre><p>By using the info() method we can retrieve more details about the dataset such as the total number of rows and columns, the type of the columns, and so on.</p><pre>sondes.info()</pre><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 2033 entries, 0 to 2032<br>Data columns (total 11 columns):<br> #   Column                       Non-Null Count  Dtype  <br>---  ------                       --------------  -----  <br> 0   ID_SONDE                     170 non-null    object <br> 1   ID_DOSSIER                   1933 non-null   object <br> 2   ALTITUDE_MIN                 1888 non-null   float64<br> 3   ALTITUDE_MAX                 1965 non-null   float64<br> 4   DIMENSION                    1548 non-null   object <br> 5   FLUIDE                       2031 non-null   object <br> 6   ETAT                         1989 non-null   object <br> 7   DETERMINATION_PLANIMETRIQUE  1982 non-null   object <br> 8   REMARQUES                    481 non-null    object <br> 9   E                            2033 non-null   float64<br> 10  N                            2033 non-null   float64<br>dtypes: float64(4), object(7)<br>memory usage: 174.8+ KB</pre><p>The file contains 11 columns (attributes) and 2033 entries. The objective here is to analyse/visualize the geothermal probes using pydeck, a high-scale spatial rendering powered by <a href="http://deck.gl/">deck.gl</a>. We need at least 3 attributes: the spatial coordinates ( X and Y) as well as the depth of each probe. In the dataset, the only attributes that do not have NaN values are E and N corresponding to the Easting and Northing coordinates.</p><pre>sondes[[&#39;E&#39;,&#39;N&#39;]].head(5)</pre><pre>====  ===========  ===========<br>  ..            E            N<br>====  ===========  ===========<br>   0  2.50313e+06  1.11669e+06<br>   1  2.50397e+06  1.11748e+06<br>   2  2.50397e+06  1.11748e+06<br>   3  2.50038e+06  1.12468e+06<br>   4  2.50039e+06  1.12469e+06<br>====  ===========  ===========</pre><p>E and N are in the CH1903+_LV95 reference system (also known as EPSG:2056). To visualize the data with pydeck (and in general with all geospatial visualization packages) however, we need to work on <em>World Geodetic System 1984 - WGS84</em> (also know as EPSG:4326).</p><p>The first step will then reproject the data from the EPSG:2056 system to the EPSG:4326 system.</p><h3>Reproject coordinate from EPSG:2056 to EPSG:4326</h3><p>There are several online converters for that such as <a href="https://epsg.io/">EPSG.io</a>, which works well when we have a few sets of coordinates to transform. However, to be efficient, we use pyproj that is a Python interface to <a href="https://proj.org/">PROJ</a> (cartographic projections and coordinate transformation library).</p><pre>from pyproj import Transformer<br>from pyproj import CRS</pre><ol><li>Initializing CRS and creating a transformer to convert from 2056 to 4326.</li></ol><pre>crs_4326 = CRS.from_epsg(4326)<br>crs_2056 = CRS.from_epsg(2056)<br>transformer = Transformer.from_crs(crs_2056, crs_4326)</pre><p>2. Convert E and N to Latitude and Longitude respectively.</p><pre>sondes[&#39;lat&#39;], sondes[&#39;lon&#39;] = transformer.transform(sondes.E.values, sondes.N.values)<br>sondes[[&#39;E&#39;,&#39;N&#39;,&#39;lat&#39;,&#39;lon&#39;]].head(5)</pre><h3>Retrieve depth of geothermal probes</h3><p>We want also to know the depth of the geothermal probes. In the dataset we do not have an attribute for that, we need further inspection. Among the 11 columns we have ALTITUDE_MIN, ALTITUDE_MAX and DIMENSION that should give us this information. However, these attributes contain several NaN. Let&#39;s inspect these attributes.</p><pre>sondes[[&#39;ALTITUDE_MIN&#39;,&#39;ALTITUDE_MAX&#39;,&#39;DIMENSION&#39;]].sample(8, random_state=51)</pre><pre>====  ==============  ============== ===============================<br>  ..    ALTITUDE_MIN    ALTITUDE_MAX  DIMENSION<br>====  ==============  ============== ===============================<br>1024               0           374    Diamètre 4x32mm Profondeur137m<br>1255               0           393.8  Diamètre 40mm Profondeur 185m<br> 907               0             0    diamètre 32mm profondeur 290m<br>1763               0             0    nan<br>1181               0           455.5  4x diamètre 32mm Profondeur85m<br>1136             nan           451.3  Diamètre 4x32mm Profondeur140m<br>  18               0             0    Profondeur 90m<br>1301               0             0    nan<br>====  ==============  ============== ===============================</pre><p>We have several cases:</p><ol><li>NaN everywhere, we will drop these lines while useless</li><li>Depth information contained in the DIMENSION attributes, as a string text</li><li>Depth information contained in the (ALTITUDE_MAX - ALTITUDE_MIN) attributes, as a string text</li></ol><p>Note: Normally, with pd.read_csv() the NaNs are automatically detected, however, depending on how the data have been compiled, it is not always the case. For example, the 0.0 value in ALTITUDE_MAX or ALTITUDE_MIN attribute corresponds clearly to NaNs values.</p><p>The next step will be to clean up all lines that contain NaN. Then we remove all rows with NaN in ALTITUDE_MAX, ALTITUDE_MIN, DIMENSION</p><pre>sondes.dropna(subset=[&#39;ALTITUDE_MIN&#39;, &#39;ALTITUDE_MAX&#39;, &#39;DIMENSION&#39;], thresh=2, inplace=True)<br>sondes[[&#39;ALTITUDE_MIN&#39;,&#39;ALTITUDE_MAX&#39;,&#39;DIMENSION&#39;]].sample(8, random_state=51)</pre><pre>====  ==============  ============== ======================<br>  ..    ALTITUDE_MIN    ALTITUDE_MAX  DIMENSION<br>====  ==============  ==============  =====================<br> 390          233.11          393.11  Long.max.160ml,4 sonde.<br>                                      diam.34mm par tube<br> 948          134             404     nan<br>1485          300             433     nan<br> 861          nan             395.5   Diamètre 4x40mm Profondeur135m<br>1080          nan             434.7   Profondeur 135m<br> 373          303.8           428.8   Long. totale = 125ml / Diam. 4<br>                                      x 32<br> 822          nan             383     Diamètre 4x32mm Profondeur150m<br>1129          nan             433.9   Diamètre 4x 32mm Profondeur<br>                                      160m<br>====  ==============  ==============  =======================</pre><p>We then need to create a DEPTH attributes that retrieve geothermal probe information from ALTITUDE_MIN and ALTITUDE_MAX, if these attributes do not contain NaN...</p><pre>sondes.reset_index(inplace=True)<br>idx1 = np.where((~np.isnan(sondes[&#39;ALTITUDE_MIN&#39;].values)) &amp; (~np.isnan(sondes[&#39;ALTITUDE_MAX&#39;].values)))<br>sondes[&#39;DEPTH&#39;] = np.nan<br>sondes[&#39;DEPTH&#39;].loc[idx1] = sondes.ALTITUDE_MAX - sondes.ALTITUDE_MIN<br>sondes[[&#39;ALTITUDE_MIN&#39;,&#39;ALTITUDE_MAX&#39;,&#39;DIMENSION&#39;, &#39;DEPTH&#39;]].sample(8, random_state=2)</pre><p>… or from the DIMENSION column. This attribute is a string, from which we need to extract depth information. For this, we use the following regular expression str.extract(&#39;(\d+)&#39;) that allows extracting the digits from the last 5 characters of the DIMENSION string text.</p><pre>idx2 = np.where((np.isnan(sondes[&#39;DEPTH&#39;].values)))<br>sondes[&#39;DEPTH&#39;].loc[idx2] = sondes[&#39;DIMENSION&#39;].loc[idx2].str[-5:].str.extract(&#39;(\d+)&#39;, expand=False).astype(np.float32)<br>sondes[[&#39;ALTITUDE_MIN&#39;,&#39;ALTITUDE_MAX&#39;,&#39;DIMENSION&#39;, &#39;DEPTH&#39;]].sample(8, random_state=2)</pre><p>Now we have all the information needed to visualize the geothermal probes dataset with pydeck.</p><h3>Interactive visual exploration using pydeck</h3><p>The “Layer” is a core concept of <a href="http://deck.gl/">deck.gl</a>. A deck.gl layer is a packaged visualization type that takes a collection of datums, associate each with positions, colors, extrusions, etc., and renders them on a map. For this visualization, we use a ColumnnLayer. Read <a href="https://deck.gl/docs/api-reference/layers">this</a> for a deck.gl layer catalog overview.</p><pre>layer = pydeck.Layer(<br>    &#39;ColumnLayer&#39;,  # `type` positional argument is here<br>    data=sondes,<br>    get_position=[&#39;lon&#39;, &#39;lat&#39;],<br>    auto_highlight=True,<br>    get_elevation=&#39;DEPTH&#39;,<br>    elevation_scale=25,<br>    radius=50,<br>    pickable=True,<br>    get_fill_color = [69,162,128,255],<br>    coverage=2)</pre><pre>view_state = pydeck.ViewState(<br>    longitude=6.183829,<br>    latitude=46.194656,<br>    zoom=10,<br>    min_zoom=5,<br>    max_zoom=15,<br>    pitch=25,<br>    bearing=0)</pre><pre># Combined all of it and render a viewport<br>r = pydeck.Deck(layers=[layer],<br>                height=1500, <br>                initial_view_state=view_state,<br>               )<br>r.to_html(&#39;geothermal-probes-viz-1.html&#39;,open_browser=False, iframe_height=750)</pre><p>The resulting visualization is a .html file that can be opened in any browser ( <a href="https://www.geomaap.io/static/images/tutorial/visualization/geothermal-probes-viz-custom.html">click here to show the results in a browser</a>)</p><p>Data and code to reproduce this work can be found <a href="https://github.com/lperozzi/DST1_pydeck_visual">here.</a></p><p><em>Originally published at </em><a href="https://www.geomaap.io/blog/tutorial/DST-viz-pydeck"><em>https://www.geomaap.io</em></a><em> on September 28, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19423f679aa4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>