<?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 Tio Faizin on Medium]]></title>
        <description><![CDATA[Stories by Tio Faizin on Medium]]></description>
        <link>https://medium.com/@tiofaizintio?source=rss-7deed2edc451------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2pbtV5ln7eL2C8Tpy6UDqg.jpeg</url>
            <title>Stories by Tio Faizin on Medium</title>
            <link>https://medium.com/@tiofaizintio?source=rss-7deed2edc451------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 10:28:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tiofaizintio/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[Cohort Retention Analysis with Python]]></title>
            <link>https://tiofaizintio.medium.com/cohort-retention-analysis-with-python-8a4d0031fe9?source=rss-7deed2edc451------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a4d0031fe9</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[retention-rate]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cohort-analysis]]></category>
            <dc:creator><![CDATA[Tio Faizin]]></dc:creator>
            <pubDate>Tue, 16 May 2023 03:33:40 GMT</pubDate>
            <atom:updated>2023-05-16T03:33:40.524Z</atom:updated>
            <content:encoded><![CDATA[<p>Retention has been a popular term in the recent development of the analytical world. Cohort analysis is a well-known technique to easily grasp the fundamental of how retention works and benefits as a metric. This article specifically shows a step-by-step how to create a Python-based cohort retention heat map which is often used as a visual to help analysts better understand the retention rate of a particular subject in the business and simplify it to make the business team easily understand. You can access all my codes here: <a href="https://github.com/tiofaizin/retention_cohort_analysis/">https://github.com/tiofaizin/retention_cohort_analysis/</a></p><p><em>(Additional: I also add a SQL code to produce a cohort retention map).</em></p><p><strong>Data Context</strong><br>The data is daily customer transaction data from a marketplace company. The data only consists of user_id (unique id for each user), order_id (unique id for each purchase transaction made), created_date (user registration date), and trx_date (user transaction date). You can download the data here: <a href="https://drive.google.com/file/d/1Iy_K3y5iEr5PblI0CM6dVdwVYUF2Woc9/view?usp=sharing">https://drive.google.com/file/d/1Iy_K3y5iEr5PblI0CM6dVdwVYUF2Woc9/view?usp=sharing</a></p><p><strong>Goal</strong><br>To create a monthly user retention heat map. The business team needs to know the monthly retention rate of users since their registration.</p><p><strong>Definition</strong><br>Based on the context and goal above, we need to define several things, such as:</p><ol><li>Cohort: a group of users who share common characteristics around a time period. In this, the cohort is: users who register their account every month of 2022</li><li>Retention: this is a measure of how well your platform retains users. In this case, if 100 people sign ups for the marketplace in the first month, but only 20 of them have transactions in the next month, your “retention rate” is 20%.</li></ol><p><strong>Import required modules</strong></p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import warnings<br>warnings.filterwarnings(&quot;ignore&quot;)</pre><p><strong>Import data</strong></p><p>I normally use CSV format. The column arrangement is important to note. You might have various formats of data with different column names and arrangements. But I strongly suggest completely following my data column naming and arrangement (if you wish to use this notebook entirely). Since a different column naming will result in an error when running.</p><p>The column should consist of:</p><ol><li><strong>Retention subject column</strong>: this column represents an entity in the data in which you wish to calculate its retention. In this case, I want to know the user retention rate, so the column contains user_id information. (Other possible data for this column: merchant id, streamer id, user phone number, etc.)</li><li><strong>Retention object column</strong>: this column is an entity in the data that represent the activity of which the retention subject (<em>user</em> in this case) stated as retained. In this data the column is orderid. (Other possible data for this column: app session id, login session id, streaming id, etc.)</li><li><strong>Cohort head column</strong>: this column consists of a period of time (mostly in a date format) that your retention subject will be grouped into. As stated before, my cohort is users who register their accounts every month in 2022. So my cohort head column is created_date (user account registration date). (Other possible data for this column: user first time of transaction, user app installation date, etc.)</li><li><strong>Retain time column</strong>: this column simply represents the time when activity in the retention object column happens. In this case, the activity is a user transaction so the column is trx_date. (Other possible data for this column: user purchase time, post uploaded time, etc.).</li></ol><p>If you have other columns in your data (usually product_id, purchase_amount, customer_address, etc.), you must not include those columns for this cohort retention analysis.</p><pre># Import data<br>user_trans = pd.read_csv(&#39;user_transaction_data.csv&#39;)<br>user_trans.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*bIxwfnZK9cZWILXWcO2V3Q.png" /></figure><p><strong>Convert time data to datetime format</strong></p><p>We need to convert <strong>created_date</strong> and <strong>trx_date</strong> columns from <em>object</em> datatype to <em>datetime</em> datatype.</p><pre>user_trans[&#39;created_date&#39;] = pd.to_datetime(user_trans.created_date)<br>user_trans[&#39;trx_date&#39;] = pd.to_datetime(user_trans.trx_date)<br>user_trans[&#39;created_month&#39;] = pd.to_datetime(user_trans[&#39;created_date&#39;].dt.strftime(&#39;%Y-%m-01&#39;))<br>user_trans[&#39;trx_month&#39;] = pd.to_datetime(user_trans[&#39;trx_date&#39;].dt.strftime(&#39;%Y-%m-01&#39;))<br>user_trans.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*Pios9ROHAdsNJWKV8UvSCA.png" /></figure><p><strong>Calculate the cohort size</strong></p><p>Cohort size is the number of users that belong to each cohort. In this case, we need to calculate the number of users who registered their account in each month of 2022.</p><pre>cohort_size = user_trans.groupby(&#39;created_month&#39;).user_id.nunique().reset_index()<br>cohort_size.rename(columns = {&#39;user_id&#39;:&#39;cohort_size&#39;}, inplace = True)<br>cohort_size</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*f5y5Y2zP5ez0PHxfuuzlMg.png" /></figure><p><strong>Truncate the date columns</strong></p><p>Since we want to get the retention rate on a monthly basis, we need to truncate the date column so it’s rounded to the beginning of the month (e.g. created_date = “2022–04–24” &gt;&gt; “2022–04–01”). After that you need to apply pandas drop_duplicates as the data must have lots of duplicates after the truncation. <strong>Note</strong>: you only need 1 user transaction of each month to state that the user is a retained user.</p><pre>user_trans_trunc = user_trans[[&#39;user_id&#39;,&#39;created_month&#39;,&#39;trx_month&#39;]].drop_duplicates().reset_index().drop([&#39;index&#39;], axis=1)</pre><p><strong>Calculate the time difference between trx_month and created_month</strong></p><p>At this step, we add a new column called <em>month_diff</em> which consists of a month difference between the trx_month and created_month. If the <em>created_month</em> is <em>2022–04–01</em> and <em>trx_month</em> is <em>2022–07–01</em>, the month_diff will be 3 (3 months between July and April). It means the user has a transaction in the third month after their registration, and is considered as a retained customer in ‘2022–07–01’.</p><pre>user_trans_trunc[&#39;month_diff&#39;] = user_trans_trunc[&#39;trx_month&#39;].dt.to_period(&#39;M&#39;).astype(int) - user_trans_trunc[&#39;created_month&#39;].dt.to_period(&#39;M&#39;).astype(int)<br>user_trans_trunc.tail()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*0OoiyVHa882nLSt_3uZpaw.png" /></figure><p><strong>Pivot</strong></p><p>Let’s pivot the data with <em>month_diff</em> as columns and <em>created_month</em> as rows. The value of each cell will be the count unique of retained users.</p><pre>monthly_pivot_count = pd.DataFrame(pd.pivot_table(user_trans_trunc, values=&#39;user_id&#39;, index=&#39;created_month&#39;, columns=&#39;month_diff&#39;, aggfunc=lambda x: len(x.unique())).to_records())<br>monthly_pivot_count</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_TC73-4ZtVpmByK5vKAE2g.png" /></figure><p><strong>Join with the cohort size data frame</strong></p><p>To get the retention rate (in %) we need to compare the number of retained users in each month with the cohort size. At this step, we join the pivot data frame with the cohort size data frame. As can be seen from the result, there are 23,713 users who registered their accounts in January 2022, and only 14,500 of them carried out at least one transaction in the same month.</p><pre>monthly_pivot_join = pd.merge(<br>                        monthly_pivot_count,<br>                        cohort_size,<br>                        how=&quot;inner&quot;,<br>                        on=&quot;created_month&quot;)<br><br>monthly_pivot_join = monthly_pivot_join[[&#39;created_month&#39;,&#39;cohort_size&#39;,&#39;0&#39;,&#39;1&#39;,&#39;2&#39;,&#39;3&#39;,&#39;4&#39;,&#39;5&#39;,&#39;6&#39;,&#39;7&#39;,&#39;8&#39;,&#39;9&#39;,&#39;10&#39;,&#39;11&#39;]]<br>monthly_pivot_join</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WrCGM1G4hou64KlIstJGPA.png" /></figure><p><strong>Get the retention rate</strong></p><p>This step simply transforms the number of monthly retained users into a percentage format, dividing them by cohort size. As can be seen from the result, only 61% of the users who registered their accounts in January 2022 have transactions (retained) in the same month.</p><pre>monthly_pivot_pct = monthly_pivot_join[[&#39;created_month&#39;,&#39;cohort_size&#39;]]<br>for i in range (0,12):<br>    monthly_pivot_pct[str(i)] = np.round((monthly_pivot_join[str(i)]/monthly_pivot_join[&#39;cohort_size&#39;])*100,0).fillna(0).astype(int)</pre><pre># Transform to percentage (number of retained users in each month/cohort size)<br>monthly_pivot_pct = monthly_pivot_pct.fillna(0)<br>monthly_pivot_pct[&#39;created_month&#39;] = monthly_pivot_pct[&#39;created_month&#39;].astype(str)<br>monthly_pivot_pct[&#39;cohort_size&#39;] = monthly_pivot_pct[&#39;cohort_size&#39;].astype(str)<br>monthly_pivot_pct</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*tn0rDLqIE8pFqDDQ3pVBDg.png" /></figure><p><strong>Coloring</strong></p><p>Let’s color the retention rate and don’t forget to set the min-max value of the rate.</p><pre>monthly_pivot_pct.style.background_gradient(cmap=&#39;Blues&#39;,vmin=0,vmax=100)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*Y4GtGhn3SBJq5FoJQ7ydlg.png" /></figure><p><strong>Highlight</strong></p><p>From the result, we can see that the user retention rate goes lower as the month passed. Even users tend to not purchase anything right after their registration, there are months with the lowest retention rate in the same month of users’ registration (February and August, only 27%). This isn’t a good sign for the business. The business team should find a way how to attract users to do more frequent purchases and to acquire more potential users. Or they can reflect on what they are doing in October to December 2022, since the retention in that period is improving.</p><p>It has been a long time for me not to work with python. I’m fully aware that my code isn’t perfect. Even I actually found multiple sources out there that perform more advanced code and delivered a more sophisticated result. Nevertheless, I hope it helps!</p><h3>THANKS!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a4d0031fe9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Indonesian Rainfall Pattern Classification using Time Series K-means]]></title>
            <link>https://tiofaizintio.medium.com/indonesian-rainfall-pattern-classification-using-time-series-k-means-6679326b459b?source=rss-7deed2edc451------2</link>
            <guid isPermaLink="false">https://medium.com/p/6679326b459b</guid>
            <category><![CDATA[meteorology]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[k-means]]></category>
            <category><![CDATA[atmospheric-sciences]]></category>
            <category><![CDATA[time-series-clustering]]></category>
            <dc:creator><![CDATA[Tio Faizin]]></dc:creator>
            <pubDate>Thu, 01 Apr 2021 13:35:41 GMT</pubDate>
            <atom:updated>2021-04-01T13:35:41.574Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong><em>Intermezzo</em></strong></h3><p>Flanked by two continents and two important factors of global climate driving force, the Pacific and Indian ocean, rendering Indonesia to constantly experience a variety of climate and weather events. Located in the low latitude, makes Indonesian only experiences fewer forms of precipitation. Once hail pouring our neighborhood, the whole local news would come up and make it as their headline. It’s very uncommon in here, moreover hail usually came with a devastating thunderstorm. I couldn’t imagine how astonished Indonesian would be if the snow came down to them (which probably won’t happen). Because the only precipitation form we familiar with is the rain.</p><h3><strong><em>Indonesian Rainfall Pattern</em></strong></h3><p>Rain is hard to predict in Indonesia. Plenty of climate variabilities play a role to trigger the occurrence of rain. Java is highly affected by monsoon activity, which usually experiences a high amount of precipitation from December to February. In most parts of Borneo and Sumatra, the rain usually peaks two times a year, in March and October, follows the movement of the sun around the equator. A profusion of pouring rain happens mostly in June-July for the most part of the middle Sulawesi and Maluku. These three types of rain patterns in Indonesia introduced in 1999 by Bayong in his book “Klimatologi Umum”. Lots of the subsequent research approved and support these rainfall patterns, such as Aldrian in his dissertation: A regionalization of Indonesian climate based on its annual patterns using double correlation method (2001).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/0*z-PPxDepk1vkVZrT.jpg" /><figcaption>Bayong, 1999</figcaption></figure><p>In this article, I try to classify Indonesian rainfall patterns using a well-known unsupervised learning method, K-means. Since I use time series data for the analysis, one little adjustment is done, which I use Dynamic Time Warping (DTW) instead of Euclidean for the distance computation.</p><p>Ok well, let the work commence!</p><h3><strong>Time Series K-means and DTW</strong></h3><p>K-means algorithm is one of the classification methods which works by allocating every data points to each pre-defined nearest cluster centroid. There are four major steps in K-means:</p><ol><li>Set the K: The number of clusters/K/number of the centroid is arbitrarily picked at the first which makes the result is super depending on how many K set</li><li>Assign each observation to the nearest cluster’s centroid</li><li>Recalculate the centroids</li><li>Repeat steps 2 and 3 until the centroids don’t change.</li></ol><p>The difference between k-means and time series k-means is only on the use of distance computation method. In time-series k-means, the proper distance calculation is Dynamic Time Warping (DTW).</p><p>DTW is good for measuring similarity between two temporal sequences which may vary in speed, length, or time. Euclidean distance isn’t the suitable choice for such a sequence or pattern matching. The distance is exactly calculated between the same index in two sequences, while DTW calculates the distance by mapping one index in a sequence to the nearest index in other sequences. Euclidean distance would measure two time series as totally different series, even if it’s only one shifted at a certain time of two highly correlated series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*urVOl37UfT_-BbOrsBInDw.png" /><figcaption>Conceptualization of the difference between (a) the Euclidean distance and (b) a DTW-based distance (Swanepoel, 2015)</figcaption></figure><p>Read this: <a href="https://towardsdatascience.com/dynamic-time-warping-3933f25fcdd">Dynamic Time Warping</a> for more about DTW.</p><h3><strong>Data Preprocessing</strong></h3><p>I use ERA5 single-level monthly total precipitation data (2001–2010). I would say that it isn’t the best practice of using reanalysis data instead of land observation data (if any). But for the shake of the first trial of classifying meteorological data, I think it’s ok. To represent the whole Indonesian rainfall pattern, I take samples from each region, which are:</p><ul><li>Sumatra</li><li>Java-Bali-Nusa Tenggara</li><li>Borneo</li><li>Sulawesi</li><li>Maluku-Papua</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*lNat6H-MnGNPjUc-r-a2rg.png" /><figcaption>Sample size formula, source: <a href="https://www.surveymonkey.com/mp/sample-size-calculator/">surveymonkey</a></figcaption></figure><p>I use the formula above to get the sample size for each region and turn it to python function code below:</p><pre>import scipy.stats as st<br>import math</pre><pre>def sample_size(n,prop,conf_level,moe):<br> a = ((st.norm.ppf(1-(1-conf_level)/2)**2)*(prop*(1-prop)))/(moe**2)<br> b = 1 + (((st.norm.ppf(1-(1-conf_level)/2)**2)*(prop*(1-<br>     prop)))/((moe**2)*n))<br> <br> return math.ceil(a/b)</pre><p>Time series K-means python library expects a 3-dimensional data input, which consists of a number of samples and a maximum sample length. Given the sample size is 1,423 and since the data is a monthly composite which consists of 12-month data for each sample, the shape of data input is :</p><pre>(1423, 12, 1) </pre><p>Next, rescale the data using MinMaxScaler, so the value range would be between 0 and 1.</p><h3><strong>Clustering using tslearn</strong></h3><p>The complete code of this work is available on my <a href="https://github.com/tiofaizin/Indonesian-Rainfall-Pattern-Classification-using-Time-Series-K-means">github</a>. <a href="https://github.com/tslearn-team/tslearn">Tslearn</a> module provides k-means methods with a variety of distance computation options. The first step of time series clustering is the same like on the regular k-means that the number of K has to be decided first. It’s nice to know the optimum number of K first despite the three different rainfall clusters we already aware of. To do that, we fit the time series k-means with <a href="https://arxiv.org/abs/1703.01541">soft-DTW</a> (a variant of DTW that replaces the non-differentiable min operation with a differentiable soft-min operation), and the number of K ranges from 1 to 15.</p><p>The parameter used is the sum of squared distances between each data point to the nearest cluster’s centroid.</p><pre>from tslearn.clustering import TimeSeriesKMeans</pre><pre>Sum_of_squared_distances = []<br>K = range(1,15)<br>for k in K:<br> km = TimeSeriesKMeans(n_clusters=k,<br> metric=”softdtw”,<br> metric_params={“gamma”: .01},<br> verbose=True,<br> random_state=seed)<br> km = km.fit(data_scaled) #data_scaled = your scaled 3D input data<br> Sum_of_squared_distances.append(km.inertia_)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*gT4UTcguSk3xAdIxCsmuDg.png" /><figcaption>Sum of squared distances per K to decide the optimum number of K</figcaption></figure><p>Using the elbow method, the optimum number of K based on the graph above is K = 3. At K = 3, the green line, which represents the sum of squared distances, is start decreasing in a linear fashion.</p><p>Let classify the rainfall data with setting number of clusters = 3.</p><pre>seed = 0<br>sdtw_km = TimeSeriesKMeans(n_clusters=3,<br>                           metric=”softdtw”,<br>                           metric_params={“gamma”: .01},<br>                           verbose=True,<br>                           random_state=seed)</pre><pre>y_pred = sdtw_km.fit_predict(data_scaled) #data_scaled = your scaled               <br>                                           3D input data</pre><p>The algorithm will assign each time series sample data to the nearest centroid. Each centroid mimics the sequential pattern of its member. In this case, three clusters are displayed and quite represent the previous research about three Indonesian rainfall patterns. Cluster 1 clearly shows the monsoonal pattern. The amount of rain peaked at both the beginning and end of the year, whilst the lowest amount occurs in June-July-August.</p><p>Cluster 2 represents the equatorial pattern, which has two peaks of the rain season (March and October). The third cluster, Cluster 3, represents the region that has unimodal patterns and peaks in the middle of the year (Local pattern, usually peaks in June-July).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9cvibRGKp4CqkPMuR7ibuQ.png" /><figcaption>Indonesian Rainfall Pattern Clustering</figcaption></figure><p>Cluster 1 (monsoonal pattern) has the highest amount of members, 58% of the data belongs to this cluster. Follow by Cluster 3 (local pattern), 24% and Cluster 2 (equatorial pattern), 17%.</p><p>In atmospheric science, time series clustering could be useful for various research topics. Discovering patterns, aggregating the parameters, and distinguish every possible clusters are some of the analysis effort in the series of solving the great meteorological phenomena conundrum.</p><h3><strong>References</strong></h3><ul><li>Tjasyono, Bayong. 1999. Klimatologi Umum. Bandung: ITB</li><li>Aldrian, Edvin. 2001. Pembagian Iklim Indonesia berdasarkan Pola Curah Hujan dengan Metoda “Double Correlation”. Jurnal Sains &amp; Teknologi Modifikasi Cuaca Vol 2. №1, 2001:11–18</li><li>Towards data science: <a href="https://towardsdatascience.com/how-to-apply-k-means-clustering-to-time-series-data-28d04a8f7da3">How to Apply K-means Clustering to Time Series Data</a></li><li><a href="https://github.com/tslearn-team/tslearn#documentation">Tslearn documentation</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6679326b459b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extract seasonality patterns from climate data with Fast Fourier Transform (FFT)]]></title>
            <link>https://tiofaizintio.medium.com/extract-seasonality-patterns-from-climate-data-with-fast-fourier-transform-fft-de479303f01?source=rss-7deed2edc451------2</link>
            <guid isPermaLink="false">https://medium.com/p/de479303f01</guid>
            <category><![CDATA[climate]]></category>
            <category><![CDATA[meteorology]]></category>
            <category><![CDATA[fast-fourier-transform]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Tio Faizin]]></dc:creator>
            <pubDate>Thu, 10 Sep 2020 16:17:43 GMT</pubDate>
            <atom:updated>2021-03-28T14:36:37.080Z</atom:updated>
            <content:encoded><![CDATA[<p>Meteorology students hardly experience smooth and expeditious data analysis. When it comes to results, they oftentimes plunge to nebulous insights and vague conclusions. Despite how clearly the method used, meteorology students shouldn’t take the idea of being creative in handling the data for granted. The quality of results totally depends on how creative they scramble the data and extract its insights. Hence the better result quality comes the more beneficial explanation. For the practical instance, when harnessing the time series meteorological dataset on analysis, many students trivialize the existence of another possible domain on the dataset. Many students don’t treat the time series data as a signal or wave that related to many parameters such as frequency and period. In this post, I’m going to show an uncomplicated example on how we use other possible domain of time series data -which is frequency- on analyzing meteorology phenomenon encompassing its practical step-by-step methods using python programming language.</p><p><strong>Prepare the data</strong></p><p>First things first, prepare the data that going to be analyzed. For example, I use 37-years daily precipitation from <a href="https://www.chc.ucsb.edu/data/chirps">CHIRPS</a> which is rainfall estimates from rain gauge and satellite observations. The data has been cropped at the specific BMKG Station in Bandung, named Cemara Weather Station. Since CHIRPS data more complete than BMKG data, I personally prefer to use CHIRPS rather than use BMKG data despite the considerable discrepancy in the data when compared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*r1sPt53yALYAeKSpggbRCw.png" /><figcaption><strong>Fig 1. </strong>Precipitation 1981–2018 (BMKG Cemara, Bandung)</figcaption></figure><p><strong>Fig 1</strong> shows the daily precipitation (mm) from 1st January of 1981 until 31st December of 2018. We might already have known that Bandung or any other region located on Java island has two seasons (dry and rainy). The peak of rainy season in Bandung normally happens in December-January-February (DJF) and the trough of rainy season -which also called dry season- in Bandung normally happens in June-July-August. Much of research proved that seasonality weather in Bandung (and mostly western Indonesia) is affected by Asia-Australia monsoon. As we know the trend of rain seasonality, we suppose to be able to depict it as a wave or signal since it has the peak and trough. For the better overview, instead of figure the data as a panel fraught of raw points connected to each other, let’s turn it to monthly precipitation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*LwoTY3ZxOcUNYeS-ehfatQ.png" /><figcaption><strong>Fig 2. </strong>Precipitation — Monthly Average (Stasiun Cemara, Bandung)</figcaption></figure><p>Now we have a better overview of rain seasonality in Bandung. This wavy pattern transpires one time a year and some years may have shifted of peak and trough of the rainy season. Notwithstanding, the pattern remains.</p><p>How if there were any else possibly periodically pattern occur in a year? Semiannual pattern or quarter-annually pattern? It could be and it should have been known by meteorology students as they recognize that rain pattern in Indonesia is very complex and affected by up to global-scale events and influenced by various topographic features.</p><p><strong>Use FFT!</strong></p><p>Fast Fourier Transform (FFT) is one of the most useful tools and widely used in signal processing. FFT has contributed to many problems solving observations in astronomy, physics, and chemistry. In meteorology, FFT has been utilized for many kinds of research and most of it is related to climate data analysis. Climate data tend to have a long period of observation which reflects scientist’s definition that climate normal as an average over a recent 30-year period.</p><p>FFT is a very complicated mathematical equation, and to be honest, I’ve never fully understood how’s the FFT equation works. To see more about FFT and how it works, check this out (<a href="https://www.earlevel.com/main/2002/08/31/a-gentle-introduction-to-the-fft/#:~:text=The%20FFT%20works%20by%20requiring,and%20multiplication%20is%20not%20needed.">A gentle introduction to the FFT</a>). In this article, I want to introduce how to use scipy.fft library in python to decompose seasonality patterns in 37-year precipitation data and get yourself (and myself) to gradually adept with python data analysis library.</p><pre><em>import matplotlib<br>import matplotlib.pyplot as plt<br>from pylab import *<br>from math import *<br>import warnings<br>warnings.simplefilter(‘ignore’)<br>import numpy as np<br>from numpy.fft import fftfreq<br>from scipy.fftpack import *<br>from scipy.signal import butter, filtfilt , freqz<br>import pandas as pd</em></pre><p>Import all the libraries needed. Scipy is the main library use in this analysis. It contains many of FFT formulas and filtering methods. Then, read the data.</p><pre><em>prec = pd.read_csv(‘prec_chirps.csv’)</em></pre><p>Use pandas library to read csv to see the data as data frame like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*L5gVuiJJ-i0jamCcRvgCzg.png" /><figcaption><strong>Fig 3. </strong>Data frame</figcaption></figure><p>The data has 13,879 rows represents daily precipitation (mm) from 1981–2018 and has no null values. The annual seasonality in <strong>Fig. 1</strong> can be seen by a naked eye. However, it’s not enough to present the existence of seasonality only by subjective plain sight towards a graph, thus we need more palpable images that could indicate the seasonality by exact number.</p><pre><em>dt = 1<br>n = prec.shape[0]<br>F = fft(prec[‘prec’])<br>w = fftfreq(n, dt)<br>t=np.linspace(1, n, n)<br>T = n/t[0:6939]<br>indices = where(w &gt; 0)<br>w_pos = abs(w[indices])<br>F_pos = abs(F[indices])</em></pre><p>In this step, we start to use FFT to transform the precipitation data which only has time domain to frequency domain. Declare dt = 1 as long as we want to analyze the data on daily basis over a 37-year period of time. The FFT result represents by F.</p><p>Bear in mind that the time series precipitation data is a combination of many frequency waves which has each wave parameters and amplify one another. By transforming the data to frequency domain, we could get each set of waves with certain frequencies that build-up the data.</p><p>Next, assign data length to n and calculate sample frequency with <em>fftfreq </em>function in which requires n and dt as arguments. It returns float array w contains the frequency bin centers in cycles per unit of the sample spacing (with zero at the start). Don’t forget to set synthetic data variable which represents the time array with an increasing value from 1 until n (data length). Then, set a new variable that portrays the number of periodicity types of the signal whereby the length is half of the original data. After that, select only indices for elements that correspond to positive frequencies. To know the details about why we do this step, check this thread: <a href="https://dsp.stackexchange.com/questions/4825/why-is-the-fft-mirrored">Why is FFT “mirrored”?</a></p><p>Now, we’re all set to figure the desirable of time-domain transformation to the frequency domain.</p><pre><em>fig1 = plt.figure()<br>ax = fig1.add_axes([0, 0, 2, 0.8])<br>axF = fig1.add_axes([0, 1.2, 2, 0.8])<br>axF.plot(w_pos, abs(F_pos))<br>axF.set_xlabel(‘Frequency’, fontsize = 13)<br>axF.set_ylabel(‘magnitude’, fontsize = 13)<br>axF.set_title(‘Periodogram (FFT Result)’, fontsize = 15)<br>axF.tick_params(labelsize = 13)<br>ax.plot(T, abs(F_pos))<br>ax.set_xlabel(‘Period’, fontsize = 13)<br>ax.set_ylabel(‘magnitude’, fontsize = 13)<br>ax.set_title(‘Periodogram (FFT Result)’, fontsize = 15)<br>ax.tick_params(labelsize = 13)</em></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*OuUv4XzfYhY2DLkfEk7k_w.png" /><figcaption><strong>Fig 4. Periodogram (FFT Result)</strong></figcaption></figure><p>The graph called periodogram. The difference between the two graphs above is on the x-axis. The upper graph shows periodogram with frequency as an x-axis, on the contrary, the lower graph uses 1/frequency (period) as x-axis. I found that the lower graph is way more intuitive and comprehensible since the period’s unit is the same as the data time unit which is a day. The y-axis is the amplitude of each periodicity/frequency that build-up the data. From the lower graph, it can be seen that from the 37-years length of data, the highest contributions are ranging between lower period sub-signal for exact &lt; 1000 days of a period. Let’s point out that range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*ZlMmwPyb-W4qlSr2gpT3aQ.png" /><figcaption><strong>Fig 5. </strong>Highlighted Periodogram</figcaption></figure><p>By limiting the x-axis range, we get the clear-cut of the periodicity ranges which have a significant amplitude in forming the original data. Without being examined, 365-days periodicity has the highest amplitude as I mentioned earlier. It clearly represents the most common and well-known of Bandung rain seasonality (annual seasonality). The second highest amplitude is on 183-days (~6-month, semi-annual seasonality) and the third is on 122-days (~4-month, quarter-annual seasonality). It turns out that Bandung rain seasonality is not only transpired annually, but it also has semi-annual and quarter-annual patterns, nevertheless, the amplitude is not quite high which means that the patterns are less frequent to exist over the time scope of the data.</p><p>Meteorologically, these patterns could happen inflicted by various events such as local disturbances until global variabilities like El Nino-La Nina or Madden-Julian Oscillation (MJO) effects. We should need more researches to be able to answer the cause of these available patterns of Bandung rainfall seasonality. Python programming language with its user-friendly scientific package has been bringing us to advance the data analysis regarding many sectors. This simple use case in meteorology maybe not as complex as other use cases, but it worth knowing and worth sharing. After using FFT and knowing the hidden patterns of the data, there are so many analysis tools which also practical to meteorological science use cases, like filtering (low-pass, band-pass, high-pass filtering) and many more. Hope this article is pertinent to your study field and could help you to get more profound data analysis.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de479303f01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to visualize spatial point-based data and its density with python Basemap?]]></title>
            <link>https://tiofaizintio.medium.com/how-to-visualize-spatial-point-based-data-and-its-density-with-python-basemap-bfe6d9da76df?source=rss-7deed2edc451------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfe6d9da76df</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[meteorology]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[basemap]]></category>
            <dc:creator><![CDATA[Tio Faizin]]></dc:creator>
            <pubDate>Tue, 14 Jul 2020 17:10:29 GMT</pubDate>
            <atom:updated>2021-03-28T14:48:09.758Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Intermezzo</em></p><p>Hi folks! This is my very first post on Medium since I’ve been realized that blogspot isn’t so-called popular anymore. In the past few months, I’ve got several messages from my college peers who have read my thesis and felt kind of amazed by my satellite data visualization <em>(unbelievable). </em>So I tried to just give them some raw scripts and succinctly deciphered how’re the scripts work. It was a struggle for me to recall those meteorological terms and such. Right after that, I felt why don’t I try to recollect and enshrine my college meteorological-related works on Medium? Because I think, it’ll be like an atonement for myself to do so since I’ve “abandoned” my meteorology diploma and let the knowledge evaporated from my brain offhand for my dream job.</p><p>Let’s start the study!</p><ol><li><strong>What data is used?</strong></li></ol><p>Mine was output from <a href="https://github.com/kwhitehall/grab-tag-graph">GTG <em>(Grab ’Em Tag ’Em Graph ’Em)</em></a><em> </em>data. It contains a specific location of cloud centroid which is detected by several weather satellites as black body temperature (source: <a href="https://disc.gsfc.nasa.gov/datasets/GPM_MERGIR_1/summary">NASA</a>). The location is specified by its coordinates (latitude and longitude).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NOj3oWtEa3iW8Dxt8ejLZA.png" /><figcaption>Fig 1. The Data</figcaption></figure><p>Actually, it isn’t an ordinary detected cloud, it was MCC <em>(Mesoscale Convective Complex), </em>which<em> </em>is a cloud organization that has an area of more than 50,000 km2, eccentricity of more than 0.7, and a life span of more than 6 hours (Maddox, 1980). The GTG algorithm yielded the MCC characteristics such as start time, end time, duration, average area, maximum area, a time when the cloud reaches its maximum area, eccentricity, latitude, and longitude.</p><p>As long we aim to focus on plotting spatial-based data, let’s just see to the latitude and longitude columns. The columns aren’t sorted by anything or dependent on any other columns, they were merely a simple coordinate.</p><p><strong>2. Import library and read data</strong></p><pre>import matplotlib.pyplot as plt<br>import numpy as np<br>from scipy import stats<br>from mpl_toolkits.basemap import Basemap<br>from mpl_toolkits.basemap import cm<br>import xlrd</pre><p>I use <em>xlrd</em> library instead of <em>pandas</em> because back to the time I first created the script, I wasn’t acquainted with <em>pandas</em> yet. I suggest using <em>pandas</em> instead of <em>xlrd</em> because <em>pandas</em> has way more powerful features and the data will be more legible because <em>pandas</em> works with daraframe.</p><p>Installing Basemap library is a bit tricky. Sometimes it couldn’t simply as type <em>pip install -package name- . </em>It was intricate so I’m not elaborate it here, I assumed you have successfully installed all the required libraries as shown above.</p><pre>data = xlrd.open_workbook(‘dataMCC.xlsx’)<br>Sheet = data.sheet_by_index(0)</pre><pre>Lat = np.array(Sheet.col_values(11,1))<br>Lon = np.array(Sheet.col_values(12,1))</pre><p>My excel file name is <em>dataMCC.xlsx</em> and I only use the first sheet, so it’s indexed by 0. Lat and Lon array variables stand for latitude and longitude which located in the 11th and 12th columns of the sheet.</p><p><strong>3. Create 2D array of density</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gh_d-WAjDmlhZDHvegWWCA.png" /><figcaption>Fig. 2. Point to Density Illustration</figcaption></figure><p>As the aforementioned statement in point 1, the Lat and Lon variables aren’t sorted by anything or dependent on any other columns. So if we plotted it to the map directly, we’d still get a rightly plotted point. But how if we want to get the density of it?</p><p>In this case, density is the number of points (MCC’s centroid) per region of desired resolution (Lat x Lon). First, calculate the desired resolution.</p><pre>nx,ny = 24,12<br>lon_bins = np.linspace(90,150,nx+1)<br>lat_bins = np.linspace(-15,15,ny+1)</pre><p>This part is strictly dependent on the region of the map that we want to show. My case study is in the Maritime Continent which located between 90E–150E and 15S-15N. I want to map my data in 2.5 x 2.5-degree resolution, so nx = 24 (150–90/24 = 2.5), and ny = 12 ((15-(-15)/12)=2.5). (Note: if you didn’t know the region that you want to show on the map, you could define it by each maximum and minimum value of latitude and longitude).</p><pre>density, _, _ = np.histogram2d(Lon,Lat,[lon_bins,lat_bins])</pre><p>I use numpy.histogram2d for density calculation. It simply calculated the number of samples in each bin <a href="https://numpy.org/doc/stable/reference/generated/numpy.histogram2d.html">(read: numpy.histogram2d)</a>. So now we have a density matrix and make sure it has the same dimension as Lat x Lon matrix.</p><p><strong>4. Declare Basemap parameters</strong></p><pre>map = Basemap(projection=’merc’,llcrnrlon=90,llcrnrlat=- 15, urcrnrlon=150,urcrnrlat=15,resolution=’f’)</pre><p>It must be the simplest one, I use Mercator as my map projection and I declare max and min of latitude and longitude. For the best map resolution, you can set ‘f’ (full resolution) on the resolution argument. See Basemap tutorial <a href="https://basemaptutorial.readthedocs.io/en/latest/basemap.html">here</a>.</p><p><strong>5. Draw the map!</strong></p><pre>fig=plt.figure(figsize=(20,15))<br>map.drawcoastlines(linewidth=1)<br>map.drawstates()<br>map.drawcountries()<br>parallels = np.arange(-15,15,10)<br>map.drawparallels(parallels,labels=[False,True,True,False],fontsize=16)<br>meridians = np.arange(90,150,10)<br>map.drawmeridians(meridians,labels=[True,False,False,True],fontsize=16)</pre><p>Standard Basemap map settings are required before the map is drawn. <em>Parallels</em> and <em>meridians</em> are variables that use to determine the scale of the grid line to be drawn.</p><pre>a = map.imshow(density.T, interpolation=’spline36&#39;, alpha=1, cmap=’YlOrBr’,vmin=0,vmax=34)</pre><pre>cbar = map.colorbar(a,’bottom’, pad=’7%’,extend=’both’)<br><br>for lons, ats in zip(Lon, Lat):<br> x, y = map.projtran(lons,lats)<br> map.plot(x,y,’ro’,markersize=5)</pre><p>I use <em>imshow</em> because it has many interpolation methods as an argument. <em>Imshow</em> displays data on a 2D regular raster image. Since I wanted to contour fill the density with a color, I had to make the 2D matrix of density smooth without diminishing any data so I picked <em>‘spline36’</em> as the best interpolation method to interpret the density (read: <a href="https://matplotlib.org/3.2.1/gallery/images_contours_and_fields/interpolation_methods.html#references">Imshow documentation</a>).</p><p>Vmin and Vmax are the minimum and maximum value of density matrix, it is important for ranging the color gradation within the map and the color bar. The MCC’s centroids (which is what the spatial point-based means) displayed as red dots.</p><p>And here we go, the final result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjJZdRsnB5Bh0lSSvItadQ.png" /><figcaption>Fig 3. Final Visualization Result</figcaption></figure><p>I know for some people, it might be a piece of cake. However, in Meteorological Science, visualization technique is an important key for interpreting meteorological phenomena and elaborating their impact to people. It can’t be erroneously displayed. Meteorologists should understand the data from the get-go, where’s the data stem from? what’s in the data? what are we gonna show?</p><p>Hope it useful!</p><p>Thanks</p><p>References:</p><ul><li>Maddox, R. A., 1980. Mesoscale Convective Complexes. Bull. Amer. Meteor. Soc., 61, 1374–1387.</li><li><a href="https://github.com/kwhitehall/grab-tag-graph">GTG <em>(Grab ’Em Tag ’Em Graph ’Em)</em></a></li><li>GES-DISC <a href="https://disc.gsfc.nasa.gov/datasets/GPM_MERGIR_1/summary">NASA</a></li><li><a href="https://matplotlib.org/3.2.1/gallery/images_contours_and_fields/interpolation_methods.html#references">Imshow documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfe6d9da76df" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>