<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Python | Bruno Messias</title><link>/category/python/</link><atom:link href="/category/python/index.xml" rel="self" type="application/rss+xml"/><description>Python</description><generator>Source Themes Academic (https://sourcethemes.com/academic/)</generator><language>en</language><copyright>Bruno Messias</copyright><lastBuildDate>Mon, 18 Apr 2022 00:00:00 +0000</lastBuildDate><image><url>/images/icon_hucd6a3d413e7b81060a1d462b35f64cf9_5018_512x512_fill_lanczos_center_3.png</url><title>Python</title><link>/category/python/</link></image><item><title>Correlation matrix analysis with the nested stochastic block model:the graph structure of stock market.</title><link>/post/nsbm_sp500_stock_market_disparity_filter/</link><pubDate>Mon, 18 Apr 2022 00:00:00 +0000</pubDate><guid>/post/nsbm_sp500_stock_market_disparity_filter/</guid><description>&lt;details
class="toc-inpage d-print-none d-none d-sm-block d-md-none " open>
&lt;summary class="font-weight-bold">Table of Contents&lt;/summary>
&lt;nav id="TableOfContents">
&lt;ul>
&lt;li>
&lt;ul>
&lt;li>&lt;a href="#introduction">Introduction&lt;/a>
&lt;ul>
&lt;li>&lt;a href="#graphs">Graphs&lt;/a>&lt;/li>
&lt;li>&lt;a href="#correlation-matrices">Correlation matrices&lt;/a>&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;a href="#downloading-and-preprocessing-the-data">Downloading and preprocessing the data&lt;/a>
&lt;ul>
&lt;li>&lt;a href="#closing-prices-of-the-sp-500">Closing prices of the S&amp;amp;P 500&lt;/a>&lt;/li>
&lt;li>&lt;a href="#returns-and-correlation-matrix">Returns and correlation matrix&lt;/a>&lt;/li>
&lt;li>&lt;a href="#removing-irrelevant-correlations-with-the-edgeseraser-library">Removing irrelevant correlations with the edgeseraser library&lt;/a>&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;a href="#nsbm-fiding-the-hierarquical-structure">nSBM: fiding the hierarquical structure&lt;/a>
&lt;ul>
&lt;li>&lt;a href="#converting-from-igraph-to-graph-tool">Converting from igraph to graph-tool&lt;/a>&lt;/li>
&lt;li>&lt;a href="#how-to-use-the-graph-tool-nsbm">How to use the graph-tool nSBM?&lt;/a>&lt;/li>
&lt;li>&lt;a href="#how-to-analyze">How to analyze?&lt;/a>&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;a href="#conclusion">Conclusion&lt;/a>&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ul>
&lt;/nav>
&lt;/details>
&lt;p>In this post, I’ll show you how the nested stochastic block model (nSBM) can extract insights from correlation matrices using a combination with a filtering edge graph technique called disparity filter. I’ll use as a case study a correlation matrix derived from the stock market data.&lt;/p>
&lt;p>Don’t be afraid, you will reproduce the beautiful plot presented below and understand what it means.&lt;/p>
&lt;figure >
&lt;a data-fancybox="" href="/post/nsbm_sp500_stock_market_disparity_filter/nsbm_final_2018-01-01_2018-06-01_hudcff6362c16284ef400b42c5fe2e1b69_266080_0x500_resize_lanczos_3.png" >
&lt;img data-src="/post/nsbm_sp500_stock_market_disparity_filter/nsbm_final_2018-01-01_2018-06-01_hudcff6362c16284ef400b42c5fe2e1b69_266080_0x500_resize_lanczos_3.png" class="lazyload" alt="" width="100%" height="500px">
&lt;/a>
&lt;/figure>
&lt;p>If you want to reproduce, use a conda environment because of the graph-tool dependency. Besides that, check if you have the following packages installed:&lt;/p>
&lt;pre>&lt;code>
matplotlib, pandas, yfinance
&lt;/code>&lt;/pre>
&lt;p>Probably you will need to install the &lt;code>igraph&lt;/code> package&lt;/p>
&lt;pre>&lt;code>
$ pip install python-igraph
&lt;/code>&lt;/pre>
&lt;p>Now, install the &lt;code>graph-tool&lt;/code> made by
&lt;a href="https://twitter.com/tiagopeixoto" target="_blank" rel="noopener">Tiago Peixoto&lt;/a>.&lt;/p>
&lt;pre>&lt;code>
$ conda install -c conda-forge graph-tool
&lt;/code>&lt;/pre>
&lt;p>No less important, we will need to remove weakling edges from the graph. To do so, we will use my package, &lt;code>edgeseraser&lt;/code>. The repository of the project is available here:
&lt;a href="https://github.com/devmessias/edgeseraser" target="_blank" rel="noopener">devmessias/edgeseraser&lt;/a>. To install the &lt;code>edgeseraser&lt;/code> run the following command:&lt;/p>
&lt;pre>&lt;code>
$ pip install edgeseraser
&lt;/code>&lt;/pre>
&lt;h2 id="introduction">Introduction&lt;/h2>
&lt;p>Exploratory data analysis allows us to gain insights or improve our choices of the next steps in the data science process. In some cases, we can explore the data assuming that all the entities are independent of each other. What happens when it’s not the case?&lt;/p>
&lt;h3 id="graphs">Graphs&lt;/h3>
&lt;p>A graph is a data structure used to store objects (vertexes) with binary relationships. Those relationships are called edges.&lt;/p>
&lt;p>Each edge can have generic data associated with it. Like a numeric value.&lt;/p>
&lt;p>Maybe you can think that this data structure is rare in the world of data. But&lt;/p>
&lt;p>if you look carefully at the data spread on the internet, graphs are everywhere: social networks, economic transactions, correlation matrices and many more.&lt;/p>
&lt;h3 id="correlation-matrices">Correlation matrices&lt;/h3>
&lt;p>A correlation matrix is a storing mechanism that quantifies relationships between pairs of random variables.&lt;/p>
&lt;p>Thus, a correlation matrix is at least a weighted graph. The main point of this post is to show how we can use tools of network science to analyze the correlation matrix. Ok, but maybe you’re asking: Why do we need to do this?&lt;/p>
&lt;p>Correlation matrices are commonly used to discover and segment the universe of possible random variables. With this segmentation into groups (clustering) we can analyze the dataset in a granular way. Therefore, improving our efficiency in discarding unnecessary information.&lt;/p>
&lt;p>A widely spread way to analyze correlation matrices using graph analytics is through the use of minimum spanning trees. I won’t go into details about this method (check the following posts
&lt;a href="https://hudsonthames.org/networks-with-mlfinlab-minimum-spanning-tree-mst/#:~:text=A%20Minimum%20Spanning%20Tree%20%28MST%29%20is%20a%20graph%20consisting%20of,a%20stock%20crisis%20%5B2%5D." target="_blank" rel="noopener">Networks with MlFinLab: Minimum Spanning &lt;/a> and [Dynamic spanning trees in stock market networks:&lt;/p>
&lt;p>The case of Asia-Pacific](
&lt;a href="https://www.bcb.gov.br/pec/wps/ingl/wps351.pdf" target="_blank" rel="noopener">https://www.bcb.gov.br/pec/wps/ingl/wps351.pdf&lt;/a>)) because I want to show how we can use a different technique that at the same time is more flexible and powerful when we want to understand the hidden group structure of a correlation matrix.&lt;/p>
&lt;p>This technique is called the nested stochastic block model (nSBM) and it’s a probabilistic model that allows us to infer the hidden group structure of a graph. The nSBM is a generalization of the stochastic block model (SBM) that assumes that the graph is composed of a set of communities (groups) that are connected by a set of edges. The SBM is a generative model that allows us to generate graphs with several communities. This generative model also creates those communities using parameters that describe the probability of a connection between vertices living in the same or different communities. Although the SBM is a powerful tool to analyze the structure of a graph, it’s not enough to infer the small communities (small groups of stocks) in our graph. To do so, we need to use the nSBM.&lt;/p>
&lt;p>Ok, let’s go to the actual stuff and code.&lt;/p>
&lt;h2 id="downloading-and-preprocessing-the-data">Downloading and preprocessing the data&lt;/h2>
&lt;h3 id="closing-prices-of-the-sp-500">Closing prices of the S&amp;amp;P 500&lt;/h3>
&lt;p>Let’s import what we need&lt;/p>
&lt;pre>&lt;code class="language-python">
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import igraph as ig
from edgeseraser.disparity import filter_ig_graph
&lt;/code>&lt;/pre>
&lt;p>To keep things simple, I choose to use the following data available
&lt;a href="https://raw.githubusercontent.com/datasets/s-and-p-500-companies/master/data/constituents.csv" target="_blank" rel="noopener">here&lt;/a>. This data encompasses the S&amp;amp;P500 from a specific time with symbols and sectors like this:&lt;/p>
&lt;p>| Symbol | Name | Sector |&lt;/p>
&lt;p>| &amp;mdash;&amp;mdash; | &amp;mdash;&amp;mdash;&amp;mdash;&amp;mdash;&amp;mdash;&amp;mdash;- | &amp;mdash;&amp;mdash;&amp;mdash;&amp;ndash; |&lt;/p>
&lt;p>| MMM | 3M | Industrials |&lt;/p>
&lt;p>| AOS | A. O. Smith | Industrials |&lt;/p>
&lt;p>| ABT | Abbott Laboratories | Health Care |&lt;/p>
&lt;p>| ABBV | AbbVie | Health Care |&lt;/p>
&lt;pre>&lt;code class="language-python">
!wget https://raw.githubusercontent.com/datasets/s-and-p-500-companies/master/data/constituents.csv
&lt;/code>&lt;/pre>
&lt;p>After downloading the data we just need to load it into a pandas dataframe.&lt;/p>
&lt;pre>&lt;code class="language-python">
df = pd.read_csv(“constituents.csv”)
all_symbols = df[‘Symbol’].values
all_sectors = df[‘Sector’].values
all_names = df[‘Name’].values
&lt;/code>&lt;/pre>
&lt;p>The following dictionaries will map the symbols to sectors and names later on&lt;/p>
&lt;pre>&lt;code>
symbol2sector = dict(zip(all_symbols, all_sectors))
symbol2name = dict(zip(all_symbols, all_names))
&lt;/code>&lt;/pre>
&lt;p>Time to download the information about each symbol. Let’s request one semester&lt;/p>
&lt;p>of data from yahoo finance API&lt;/p>
&lt;pre>&lt;code class="language-python">
start_date = ‘2018-01-01’
end_date = ‘2018-06-01’
try:
prices = pd.read_csv(
f&amp;quot;sp500_prices_{start_date}_{end_date}.csv&amp;quot;, index_col=&amp;quot;Date&amp;quot;)
tickers_available = prices.columns.values
except FileNotFoundError:
df = yf.download(
list(all_symbols),
start=start_date,
end=end_date,
interval=&amp;quot;1d&amp;quot;,
group_by=’ticker’,
progress=True
)
tickers_available = list(
set([ticket for ticket, _ in df.columns.T.to_numpy()]))
prices = pd.DataFrame.from_dict(
{
ticker: df[ticker][“Adj Close”].to_numpy()
for ticker in tickers_available
}
)
prices.index = df.index
prices = prices.iloc[:-1]
del df
prices.to_csv(
f&amp;quot;sp500_prices_{start_date}_{end_date}.csv&amp;quot;)
&lt;/code>&lt;/pre>
&lt;h3 id="returns-and-correlation-matrix">Returns and correlation matrix&lt;/h3>
&lt;p>We first start by computing the percentage of price changes for each stock, the return of each stock.&lt;/p>
&lt;pre>&lt;code class="language-python">
returns_all = prices.pct_change()
# a primeira linha não faz sentido, não existe retorno no primeiro dia
returns_all = returns_all.iloc[1:, :]
returns_all.dropna(axis=1, thresh=len(returns_all.index)//2., inplace=True)
returns_all.dropna(axis=0, inplace=True)
symbols = returns_all.columns.values
&lt;/code>&lt;/pre>
&lt;p>Now, we compute the correlation matrix using the returns&lt;/p>
&lt;pre>&lt;code class="language-python">
# plot the correlation matrix with ticks at each item
correlation_matrix = returns_all.corr()
plt.title(f&amp;quot;Correlation matrix from {start_date} to {end_date}&amp;quot;)
plt.imshow(correlation_matrix)
plt.colorbar()
plt.savefig(“correlation.png”, dpi=150)
plt.clf()
&lt;/code>&lt;/pre>
&lt;figure id="figure-correlation-matrix-for-sp500-off-the-first-2018-semester-yes-its-a-mess">
&lt;a data-fancybox="" href="/post/nsbm_sp500_stock_market_disparity_filter/correlation_hu6c68fc9d1aa2b5f7307017b57ffa4d90_521823_0x500_resize_lanczos_3.png" data-caption="Correlation matrix for S&amp;amp;amp;P500 off the first 2018 semester. Yes, it’s a mess!">
&lt;img data-src="/post/nsbm_sp500_stock_market_disparity_filter/correlation_hu6c68fc9d1aa2b5f7307017b57ffa4d90_521823_0x500_resize_lanczos_3.png" class="lazyload" alt="" width="100%" height="500px">
&lt;/a>
&lt;figcaption>
Correlation matrix for S&amp;amp;P500 off the first 2018 semester. Yes, it’s a mess!
&lt;/figcaption>
&lt;/figure>
&lt;p>Ok, look into the image above. If you try to find groups of stocks that are less correlated just using visual inspection, you will have a hard time. This works just for a small set of stocks. Obviously, that is another approach like using linked cluster algorithms, but they are still hard to analyze when the number of stocks increases.&lt;/p>
&lt;h3 id="removing-irrelevant-correlations-with-the-edgeseraser-library">Removing irrelevant correlations with the edgeseraser library&lt;/h3>
&lt;p>Our goal here is to understand the structure of the stock market communities,&lt;/p>
&lt;p>so we will keep just the matrix elements with positive values.&lt;/p>
&lt;pre>&lt;code class="language-python">
pos_correlation = correlation_matrix.copy()
# vamos considerar apenas as correlações positivas pois queremos
# apenas as comunidade&amp;gt;
pos_correlation[pos_correlation &amp;lt; 0.] = 0
# diagonal principal é setada a 0 para evitar auto-arestas
np.fill_diagonal(pos_correlation.values, 0)
&lt;/code>&lt;/pre>
&lt;p>Now, we create a weighted graph where each vertex is a stock and each positive correlation is a weight associated to the edge between two stocks.&lt;/p>
&lt;pre>&lt;code class="language-python">
g = ig.Graph.Weighted_Adjacency(pos_correlation.values, mode=’undirected’)
# criamos uma feature symbol para cada vértice
g.vs[“symbol”] = returns_all.columns
# o grafo pode estar desconectado. Portanto, extraímos a componente gigante
cl = g.clusters()
g = cl.giant()
n_edges_before = g.ecount()
&lt;/code>&lt;/pre>
&lt;p>The graph above has too much information, which is problematic for graph analysis. So, we must first identify and keep only the relevant edges. To do so, we use the disparity filter.&lt;/p>
&lt;p>available in my &lt;code>edgeseraser&lt;/code> package.&lt;/p>
&lt;pre>&lt;code class="language-python">
_ = filter_ig_graph(g, .25, cond=&amp;quot;both&amp;quot;, field=&amp;quot;weight&amp;quot;)
cl = g.clusters()
g = cl.giant()
n_edges_after = g.ecount()
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">
print(f&amp;quot;Percentage of edges removed: {(n_edges_before - n_edges_after)/n_edges_before*100:.2f}%&amp;quot;)
print(f&amp;quot;Number of remained stocks: {len(symbols)}&amp;quot;)
...
Percentage of edges removed: 95.76%
Number of remained stocks: 492
&lt;/code>&lt;/pre>
&lt;p>We have deleted most of the edges and only a backbone remained in our graph. This backbone structure can now be used to extract.&lt;/p>
&lt;p>insights from the stock market.&lt;/p>
&lt;h2 id="nsbm-fiding-the-hierarquical-structure">nSBM: fiding the hierarquical structure&lt;/h2>
&lt;h3 id="converting-from-igraph-to-graph-tool">Converting from igraph to graph-tool&lt;/h3>
&lt;p>Here, we will use the graph-tool lib to infer the hierarchical structure of the graph. Thus, we must first convert the graph from &lt;code>igraph&lt;/code> to &lt;code>graph-tool&lt;/code>. We can convert that using the following code&lt;/p>
&lt;pre>&lt;code class="language-python">
import graph_tool.all as gt
gnsbm = gt.Graph(directed=False)
# iremos adicionar os vértices
for v in g.vs:
gnsbm.add_vertex()
# e as arestas
for e in g.es:
gnsbm.add_edge(e.source, e.target)
&lt;/code>&lt;/pre>
&lt;h3 id="how-to-use-the-graph-tool-nsbm">How to use the graph-tool nSBM?&lt;/h3>
&lt;p>With the sparsified correlation graph that encompasses the stock relationships, we can ask ourselves how those relationships ties stocks together. Here, we will use the nSBM to answer this.&lt;/p>
&lt;p>The
&lt;a href="https://dx.doi.org/10.1103/PhysRevX.4.011047" target="_blank" rel="noopener">nSBM&lt;/a>&lt;/p>
&lt;p>is an inference method that optimizes a set of parameters that defines a generative graph model for our data. In our case, to find this model for the sparsified s&amp;amp;p500 correlation graph, we will cal the method &lt;code>minimize_nested_blockmodel_dl&lt;/code>&lt;/p>
&lt;pre>&lt;code class="language-python">
state = gt.minimize_nested_blockmodel_dl(gnsbm)
&lt;/code>&lt;/pre>
&lt;p>We can use the code below to define the colors for our plot.&lt;/p>
&lt;pre>&lt;code class="language-python">
symbols = g.vs[“symbol”]
sectors = [symbol2sector[symbol] for symbol in symbols]
u_sectors = np.sort(np.unique(sectors))
u_colors = [plt.cm.tab10(i/len(u_sectors))
for i in range(len(u_sectors))]
# a primeira cor da lista era muito similar a segunda,
u_colors[0] = [0, 1, 0, 1]
sector2color = {sector: color for sector, color in zip(u_sectors, u_colors)}
rgba = gnsbm.new_vertex_property(“vector&amp;lt;double&amp;gt;“)
gnsbm.vertex_properties[‘rgba’] = rgba
for i, symbol in enumerate(symbols):
c = sector2color[symbol2sector[symbol]]
rgba[i] = [c[0], c[1], c[2], .5]
&lt;/code>&lt;/pre>
&lt;p>Calling the &lt;code>draw&lt;/code> method, we create a plot with the nSBM result. You can play a little, changing the `$\beta \in (0, 1)$ parameter to see how the things change. This parameter controls the strength of the &lt;strong>edge-bundling&lt;/strong> algorithm.&lt;/p>
&lt;pre>&lt;code class="language-python">
options = {
‘output’: f’nsbm_{start_date}_{end_date}.png’,
‘beta’: .9,
‘bg_color’: ‘w’,
#’output_size’: (1500, 1500),
‘vertex_color’: gnsbm.vertex_properties[‘rgba’],
‘vertex_fill_color’: gnsbm.vertex_properties[‘rgba’],
‘hedge_pen_width’: 2,
‘hvertex_fill_color’: np.array([0., 0., 0., .5]),
‘hedge_color’: np.array([0., 0., 0., .5]),
‘hedge_marker_size’: 20,
‘hvertex_size’:20
}
state.draw(**options)
&lt;/code>&lt;/pre>
&lt;p>Finally, we can see the hierarchical structure got from our filtered graph using&lt;/p>
&lt;p>the nSBM algorithm.&lt;/p>
&lt;pre>&lt;code class="language-python">
plt.figure(dpi=150)
plt.title(f”Sectors of the S&amp;amp;P 500 from {start_date} to {end_date}&amp;quot;)
legend = plt.legend(
[plt.Line2D([0], [0], color=c, lw=10)
for c in list(sector2color.values())],
list(sector2color.keys()),
bbox_to_anchor=(1.05, 1),
loc=2,
borderaxespad=0.)
plt.imshow(plt.imread(f’nsbm_{start_date}_{end_date}.png’))
plt.xticks([])
plt.yticks([])
plt.axis(‘off’)
plt.savefig(f’nsbm_final_{start_date}_{end_date}.png’, bbox_inches=’tight’,
dpi=150, bbox_extra_artists=(legend,), facecolor=’w’, edgecolor=’w’)
plt.show()
&lt;/code>&lt;/pre>
&lt;figure id="figure-nsbm-result-for-the-correlation-matrix-of-sp500-returns">
&lt;a data-fancybox="" href="/post/nsbm_sp500_stock_market_disparity_filter/nsbm_final_2018-01-01_2018-06-01_hudcff6362c16284ef400b42c5fe2e1b69_266080_0x500_resize_lanczos_3.png" data-caption="nSBM result for the correlation matrix of S&amp;amp;amp;P500 returns.">
&lt;img data-src="/post/nsbm_sp500_stock_market_disparity_filter/nsbm_final_2018-01-01_2018-06-01_hudcff6362c16284ef400b42c5fe2e1b69_266080_0x500_resize_lanczos_3.png" class="lazyload" alt="" width="100%" height="500px">
&lt;/a>
&lt;figcaption>
nSBM result for the correlation matrix of S&amp;amp;P500 returns.
&lt;/figcaption>
&lt;/figure>
&lt;p>Wow, beautiful, isn’t it? But maybe you can only see a beautiful picture and not be&lt;/p>
&lt;p>able to understand what is happening. So, let’s try to understand what this plot is&lt;/p>
&lt;p>telling us.&lt;/p>
&lt;h3 id="how-to-analyze">How to analyze?&lt;/h3>
&lt;figure >
&lt;a data-fancybox="" href="/post/nsbm_sp500_stock_market_disparity_filter/descripition_nsbm_sp500_eng_hubc8bd3aa9dee5e4b9544c9c74b387fed_1482556_0x400_resize_lanczos_3.png" >
&lt;img data-src="/post/nsbm_sp500_stock_market_disparity_filter/descripition_nsbm_sp500_eng_hubc8bd3aa9dee5e4b9544c9c74b387fed_1482556_0x400_resize_lanczos_3.png" class="lazyload" alt="" width="80%" height="400px">
&lt;/a>
&lt;/figure>
&lt;ul>
&lt;li>
&lt;p>Each circle (leaf) represents a stock. A vertex in the original graph.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>Each group of leafs which resembles a broom is a community detected by the nSBM.&lt;/p>
&lt;/li>
&lt;/ul>
&lt;p>Navigating backwards through the arrows, we can see the hierarchical community structure. The image above shows three communities that belong to the same grandfather community.&lt;/p>
&lt;p>We can see interesting stuff in the community structure. For example, most stocks related to &lt;strong>Consumer staples&lt;/strong>, &lt;strong>Real state&lt;/strong>, and &lt;strong>Utilities&lt;/strong> belongs to the same community.&lt;/p>
&lt;p>What is the meaning of the edges?&lt;/p>
&lt;ul>
&lt;li>A larger number of edges between &lt;strong>Financials&lt;/strong>, &lt;strong>Industrials&lt;/strong> and &lt;strong>Information technology&lt;/strong> survive the filtering technique, which shows a strong relationship between these sectors.&lt;/li>
&lt;/ul>
&lt;p>The visual inspection of the edges relationships is meaningful only because of the use of edge bundling algorithm. Let’s see how a weak bundling turns our job into a hard one, setting $\beta = 0.5$&lt;/p>
&lt;figure id="figure-can-you-understand-what-is-happening-me-neither">
&lt;a data-fancybox="" href="/post/nsbm_sp500_stock_market_disparity_filter/nsbm_2018-01-01_2018-06-01_beta_0.5_hu63a031e361e4cd7a15f51f9db9995b63_1589031_0x400_resize_lanczos_3.png" data-caption="Can you understand what is happening? Me neither.">
&lt;img src="/post/nsbm_sp500_stock_market_disparity_filter/nsbm_2018-01-01_2018-06-01_beta_0.5_hu63a031e361e4cd7a15f51f9db9995b63_1589031_0x400_resize_lanczos_3.png" alt="" height="4200px">
&lt;/a>
&lt;figcaption>
Can you understand what is happening? Me neither.
&lt;/figcaption>
&lt;/figure>
&lt;p>A visual inspection is sometimes not enough, and maybe you need to create an automatic analysis, which is easy to do with the graph-tool. For example, to get a summary of the hierarchical community structure got by the nSBM algorithm, we can call the &lt;code>print_summary&lt;/code> method.&lt;/p>
&lt;pre>&lt;code class="language-python">
state.print_summary()
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>l: 0, N: 483, B: 25
l: 1, N: 25, B: 6
l: 2, N: 6, B: 2
l: 3, N: 2, B: 1
l: 4, N: 1, B: 1
&lt;/code>&lt;/pre>
&lt;p>In the first level, we have &lt;strong>21&lt;/strong> communities for all the &lt;strong>11&lt;/strong> sectors.&lt;/p>
&lt;p>If we want to know which communities the &lt;strong>TSLA&lt;/strong> stock belongs to, we go through&lt;/p>
&lt;p>the hierarchy in the reverse order,&lt;/p>
&lt;pre>&lt;code class="language-python">
# esse é o indice da TSLA no nosso grafo original
symbol = “TSLA”
index_tesla = symbols.index(symbol)
print(symbol, symbol2sector[symbol], symbol2name[symbol])
r0 = state.levels[0].get_blocks()[index_tesla]
r1 = state.levels[1].get_blocks()[r0]
r2 = state.levels[2].get_blocks()[r1]
r3 = state.levels[3].get_blocks()[r2]
(r1, r2, r3)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>
(‘TSLA’, ‘Consumer Discretionary’, ‘Tesla’)
(19, 0, 0)
&lt;/code>&lt;/pre>
&lt;h2 id="conclusion">Conclusion&lt;/h2>
&lt;p>The aim of this post was to give you a first impression of a method that combines the use of nSBM and edge filtering techniques to enhance our understanding of the correlation structure of the data, especially with financial data. However, we can also use this method in different scenarios, as&lt;/p>
&lt;p>
&lt;a href="https://www.science.org/doi/10.1126/sciadv.aaq1360" target="_blank" rel="noopener">topic modeling in NLP&lt;/a> and
&lt;a href="https://arxiv.org/abs/2110.01421" target="_blank" rel="noopener">survey analysis&lt;/a>.&lt;/p></description></item><item><title>Going meta with python: manipulating ASTs to create an introspective decorator at runtime</title><link>/post/python_ast_metaprogramming_with_introspection_and_decorators/</link><pubDate>Fri, 08 Apr 2022 00:00:00 +0000</pubDate><guid>/post/python_ast_metaprogramming_with_introspection_and_decorators/</guid><description>&lt;details
class="toc-inpage d-print-none d-none d-sm-block d-md-none " open>
&lt;summary class="font-weight-bold">Table of Contents&lt;/summary>
&lt;nav id="TableOfContents">
&lt;ul>
&lt;li>
&lt;ul>
&lt;li>&lt;a href="#intro-our-previous-problem">Intro: our previous problem&lt;/a>&lt;/li>
&lt;li>&lt;a href="#asts-what-are-they">ASTs: What are they?&lt;/a>&lt;/li>
&lt;li>&lt;a href="#python-interpreted-or-compiled">Python: interpreted or compiled?&lt;/a>&lt;/li>
&lt;li>&lt;a href="#extracting-asts-and-interpreting-them">Extracting ASTs and interpreting them&lt;/a>&lt;/li>
&lt;li>&lt;a href="#how-can-i-be-efficient-in-metaprogramming">How can I be efficient in metaprogramming?&lt;/a>
&lt;ul>
&lt;li>&lt;a href="#the-6-simple-steps">The 6 simple steps&lt;/a>&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;a href="#creating-our-metaprogramming-function">Creating our metaprogramming function&lt;/a>
&lt;ul>
&lt;li>&lt;a href="#first-six-steps-interaction">First six-steps interaction&lt;/a>&lt;/li>
&lt;li>&lt;a href="#the-nodetransformer-class">The NodeTransformer class&lt;/a>&lt;/li>
&lt;li>&lt;a href="#the-second-six-steps-interaction">The second six-steps interaction&lt;/a>&lt;/li>
&lt;li>&lt;a href="#creating-a-new-function-at-runtime">Creating a new function at runtime&lt;/a>&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;a href="#integrating-the-ast-manipulation-with-a-decorator">Integrating the AST manipulation with a decorator&lt;/a>&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ul>
&lt;/nav>
&lt;/details>
&lt;p>Don&amp;rsquo;t be afraid of the names on the title. Although they can seem scary or strange probably you already have been in touch with tools that work with this kind of stuff. For example, pytest and numba.&lt;/p>
&lt;h2 id="intro-our-previous-problem">Intro: our previous problem&lt;/h2>
&lt;p>
&lt;a href="/post/python_decorator_that_exposes_locals/" title="An introspective python decorator using stack frames and the inspect module">In the previous post&lt;/a>,
I talked about python frames and inspection module. I started showing how we can use the &lt;code>inspect.signature&lt;/code> to construct a decorator that validates arguments:&lt;/p>
&lt;pre>&lt;code class="language-python">@math_validator()
def simple_method(x: &amp;quot;\in R&amp;quot;, y: &amp;quot;\in R_+&amp;quot;, z: float = 2) -&amp;gt; float:
...
simple_method(1, 0)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>simple_method((1, 2)) -&amp;gt; 1.5
---&amp;gt; 19 simple_method(1, 0)
...
&amp;lt;locals&amp;gt;.decorate.&amp;lt;locals&amp;gt;.decorated(*_args)
11 continue
13 if not MATH_SPACES[annotation][&amp;quot;validator&amp;quot;](_args[i]):
---&amp;gt; 14 raise ValueError(f&amp;quot;{k} doesn't belong to the {MATH_SPACES[annotation]['name']}&amp;quot;)
15 result = func(*_args)
16 print(f&amp;quot;{func.__name__}({_args}) -&amp;gt; {result}&amp;quot;)
ValueError: y doesn't belong to the space of real numbers greater than zero
&lt;/code>&lt;/pre>
&lt;p>And after that, I combined the &lt;code>inspect.singature&lt;/code>+&lt;code>sys.trace&lt;/code> to construct a decorator that exposes the local variables of a decorated function. All this stuff allows us to do cool things like creating a generic report decorator that has access to the local variables of the decorated method&lt;/p>
&lt;pre>&lt;code class="language-python">@report('{arg.n_bananas} Monkey {gluttonous_monkey} ate too much bananas. Num monkeys {num_monkeys}')
def feed_monkeys(n_bananas):
num_monkeys = 3
monkeys = {
f&amp;quot;monkey_{i}&amp;quot;: {&amp;quot;bananas&amp;quot;: 0}
for i in range(num_monkeys)
}
while n_bananas &amp;gt; 0:
if np.random.uniform() &amp;lt; 0.4:
continue
monkey = monkeys[np.random.choice(list(monkeys.keys()))]
if n_bananas &amp;gt; 0:
monkey[&amp;quot;bananas&amp;quot;] += 1
n_bananas -= 1
gluttonous_monkey = max(monkeys, key=lambda k: monkeys[k][&amp;quot;bananas&amp;quot;])
&lt;/code>&lt;/pre>
&lt;p>These two examples can be found in real application scenarios. But at the end of my previous post I told you some issues regarding the use of &lt;code>sys.trace&lt;/code>. I&amp;rsquo;ll put the code here of the previous solution:
&lt;div class="spoiler " >
&lt;p>
&lt;a class="btn btn-primary" data-toggle="collapse" href="#spoiler-2" role="button" aria-expanded="false" aria-controls="spoiler-2">
Click here to see the solution
&lt;/a>
&lt;/p>
&lt;div class="collapse card " id="spoiler-2">
&lt;div class="card-body">
&lt;pre>&lt;code class="language-python">import sys
import inspect
from types import SimpleNamespace
def call_and_extract_frame(func, *args, **kwargs):
frame_var = None
trace = sys.gettrace()
def update_frame_var(stack_frame, event_name, arg_frame):
&amp;quot;&amp;quot;&amp;quot;
Args:
stack_frame: (frame)
The current stack frame.
event_name: (str)
The name of the event that triggered the call.
Can be 'call', 'line', 'return' and 'exception'.
arg_frame:
Depends on the event. Can be a None type
&amp;quot;&amp;quot;&amp;quot;
nonlocal frame_var # nonlocal is a keyword which allows us to modify the outisde scope variable
if event_name != 'call':
return trace
frame_var = stack_frame
sys.settrace(trace)
return trace
sys.settrace(update_frame_var)
try:
func_result = func(*args, **kwargs)
finally:
sys.settrace(trace)
return frame_var, func_result
def report(formater):
def decorate(func):
def decorated(*_args):
sig = inspect.signature(func)
named_args = {}
num_args = len(_args)
for i, (k, v) in enumerate(sig.parameters.items()):
if i &amp;lt; num_args:
named_args[k] = repr(_args[i])
else:
named_args[k] = repr(v.default)
frame_func, _result = call_and_extract_frame(func, *_args)
name = func.__name__
result = repr(_result)
args_dict = {
&amp;quot;args&amp;quot;: SimpleNamespace(**named_args),
&amp;quot;args_repr&amp;quot;: repr(SimpleNamespace(**named_args)),
**locals(),
**frame_func.f_locals,
}
print(formater.format(**args_dict))
# do other stuff here
return _result
return decorated
return decorate
&lt;/code>&lt;/pre>
&lt;/div>
&lt;/div>
&lt;/div>&lt;/p>
&lt;p>What are the problems with this solution?&lt;/p>
&lt;ul>
&lt;li>A tracing always creates a cost. Thus, it is expected that we will reduce the performance of our system. If you use this just for debugging purposes, it&amp;rsquo;s ok.&lt;/li>
&lt;li>It can create conflicts with other tools and libs that are also trying to use the trace tool&lt;/li>
&lt;li>Seems dirty!&lt;/li>
&lt;/ul>
&lt;p>Ok, maybe you&amp;rsquo;re asking yourself &lt;em>&amp;ldquo;This guy is overthinking. Why didn&amp;rsquo;t he just do this?&amp;quot;&lt;/em>&lt;/p>
&lt;pre>&lt;code class="language-python">@report('stuff goes here')
def func(x, y):
random_var = np.random.uniform()
... #more local vars
result = (x+y)**random_var
return result, locals
&lt;/code>&lt;/pre>
&lt;p>The reason is:&lt;/p>
&lt;ul>
&lt;li>The main point of using this decorator is to avoid any change in other parts of the codebase. For example,
if in any part of the codebase &lt;code>func&lt;/code> has been called you will have to change to&lt;/li>
&lt;/ul>
&lt;pre>&lt;code class="language-python">result = func(x, y) # to
result = func(x, y)[0]
&lt;/code>&lt;/pre>
&lt;p>If after you choose to remove the decorator from a function, you will need to roll back all the above changes.&lt;/p>
&lt;ul>
&lt;li>You will increase the cognitive load in all members of the team who don&amp;rsquo;t care about what your decorator needs to do.&lt;/li>
&lt;li>If you propose this a solution you&amp;rsquo;d better just create another function and face the consequences of this increase in complexity in the original codebase.&lt;/li>
&lt;/ul>
&lt;p>Ok, maybe you&amp;rsquo;re now thinking: &amp;ldquo;&lt;em>Right, this makes sense, but you&amp;rsquo;re avoiding these issues creating other issues in performance and debugging. It doesn&amp;rsquo;t sound good except for some special cases&lt;/em>&amp;rdquo;. And I need to agree with you, &lt;strong>it&amp;rsquo;s not a good solution for most of the cases!&lt;/strong>&lt;/p>
&lt;p>The problem we&amp;rsquo;re facing is that python doesn&amp;rsquo;t have context managers that can deal with namespaces, although there is an active discussion about this
&lt;a href="https://mail.python.org/archives/list/python-ideas@python.org/thread/TAVHEKDZVYKJUGZKWSVZVAOGBPLZVKQG/" target="_blank" rel="noopener">https://mail.python.org/archives/list/python-ideas@python.org/&lt;/a>. But don&amp;rsquo;t worry about this big name. The important point here is that:&lt;/p>
&lt;div class="alert alert-note">
&lt;div>
&lt;strong>If a language doesn&amp;rsquo;t have a feature that I need, what can I do?&lt;/strong>
&lt;/div>
&lt;/div>
&lt;p>In python we are fine with this because it&amp;rsquo;s a language that turns to be easy to manipulate the &lt;strong>A&lt;/strong>bstract &lt;strong>S&lt;/strong>yntax &lt;strong>T&lt;/strong>ree and recompile a function with the manipulated tree. &lt;strong>Doing that way we&amp;rsquo;re in the realm of metaprogramming. Writing code which writes code.&lt;/strong> If t&amp;rsquo;s not clear I&amp;rsquo;ll try to be more clear now.&lt;/p>
&lt;h2 id="asts-what-are-they">ASTs: What are they?&lt;/h2>
&lt;p>A programming language obviously is at least a language. OK, &lt;strong>but what is a language?
Do all the human languages share the same building blocks? How can we compare different sentences?&lt;/strong>
These questions seem more proper to be answered by philosophers. Well, maybe this is true, but these questions can also be answered by mathematicians and computer scientists. However, mathematicians and CS people usually prefer to talk using mathematical formalism rather than long debates about the meaning of the stuff. In essence, an &lt;strong>AST&lt;/strong> is a mathematical formalism that allows us to represent a sentence using a well-defined set of rules and structures represented by a tree.&lt;/p>
&lt;h3>How do you know that a sentence is grammatically correct?&lt;/h3>
&lt;p>Intuitively, probably you remember a set of rules that you learned during your life about how to organize and compose verbs, nouns, adjectives, adverbs, etc. This set of rules and guidelines is the &lt;em>Syntax&lt;/em> of a language. A &lt;strong>S&lt;/strong>yntax &lt;strong>T&lt;/strong>ree is a structure that helps us to understand a sentence.&lt;/p>
&lt;div class="alert alert-note">
&lt;div>
After constructing the syntax tree we can look in the guidelines book of our language and check if this tree has a valid structure.
&lt;/div>
&lt;/div>
&lt;p>Take for example
the sentence: &lt;em>&amp;ldquo;I drive a car to my college&amp;rdquo;&lt;/em>, the syntax tree is the following:&lt;/p>
&lt;figure id="figure-a-syntax-tree-for-the-sentence-i-drive-a-car-to-my-college-source-geeks-for-geekssyntax-tree--natural-language-processinghttpswwwgeeksforgeeksorgsyntax-tree-natural-language-processing">
&lt;a data-fancybox="" href="/post/python_ast_metaprogramming_with_introspection_and_decorators/ast_english_sentence_hue5b8d52ce962721ee6d0acb19268cb10_239788_0x400_resize_lanczos_3.png" data-caption="A &amp;lt;strong&amp;gt;S&amp;lt;/strong&amp;gt;yntax &amp;lt;strong&amp;gt;T&amp;lt;/strong&amp;gt;ree for the sentence: &amp;lt;em&amp;gt;I drive a car to my college&amp;lt;/em&amp;gt;. &amp;lt;strong&amp;gt;Source&amp;lt;/strong&amp;gt;:&amp;lt;a href=&amp;#34;https://www.geeksforgeeks.org/syntax-tree-natural-language-processing/&amp;#34;&amp;gt; Geeks for Geeks:Syntax Tree – Natural Language Processing.&amp;lt;/a&amp;gt;">
&lt;img src="/post/python_ast_metaprogramming_with_introspection_and_decorators/ast_english_sentence_hue5b8d52ce962721ee6d0acb19268cb10_239788_0x400_resize_lanczos_3.png" alt="" height="400px">
&lt;/a>
&lt;figcaption>
A &lt;strong>S&lt;/strong>yntax &lt;strong>T&lt;/strong>ree for the sentence: &lt;em>I drive a car to my college&lt;/em>. &lt;strong>Source&lt;/strong>:&lt;a href="https://www.geeksforgeeks.org/syntax-tree-natural-language-processing/"> Geeks for Geeks:Syntax Tree – Natural Language Processing.&lt;/a>
&lt;/figcaption>
&lt;/figure>
&lt;p>What is the advantage of using ASTs? Notice that we don&amp;rsquo;t need to talk about how many spaces you&amp;rsquo;re using, we didn&amp;rsquo;t talk about your calligraphy and besides that, &lt;strong>we have a hierarchy structure that allows us to analyze the validity of the sentence per level! If we want to change any element of the sentence we can directly manipulate the node which represents that element for a safe guarantee that the manipulated sentence is still grammatically correct!&lt;/strong>&lt;/p>
&lt;p>It&amp;rsquo;s not a surprise that ASTs are also a common tool used in computer science to analyze the correctness of a piece of code and as a common part of the process of compiling/interpreting a code. Here we will extend the behavior of a Python decorator manipulating the AST. But before that, I would like to ask you a question:&lt;/p>
&lt;h2 id="python-interpreted-or-compiled">Python: interpreted or compiled?&lt;/h2>
&lt;p>Usually, when I meet a Python hater (or even an enthusiast) they say statements like that&lt;/p>
&lt;ul>
&lt;li>&lt;em>&amp;ldquo;Python is slow because it&amp;rsquo;s an interpreted language!&amp;quot;&lt;/em>&lt;/li>
&lt;li>&lt;em>&amp;ldquo;Python sucks because it doesn&amp;rsquo;t have a compiler!&amp;quot;&lt;/em>&lt;/li>
&lt;/ul>
&lt;p>Well, these assertions are not true. The important point is that: &lt;em>when people refer to Python commonly they are actually talking about the language Python and the CPython virtual machine&lt;/em>. Let&amp;rsquo;s talk more about these misconceptions.&lt;/p>
&lt;p>First, the distinction between interpreted and compiled languages is very blurry today.
Second, let&amp;rsquo;s see something&lt;/p>
&lt;pre>&lt;code class="language-python">hello_world = &amp;quot;print('Hello, world!')&amp;quot;
hello_world_obj = compile(hello_world, '&amp;lt;string&amp;gt;', 'single')
&lt;/code>&lt;/pre>
&lt;p>Yeah, if you&amp;rsquo;re trying to defend that Python is interpreted the things start to get harder for you. &lt;strong>Why is there a &lt;strong>compile&lt;/strong> available?&lt;/strong>&lt;/p>
&lt;pre>&lt;code class="language-python">exec(hello_world_obj)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>Hello, world!
&lt;/code>&lt;/pre>
&lt;p>I&amp;rsquo;m executing a thing that has been compiled??? What is this hello_world_obj?&lt;/p>
&lt;pre>&lt;code class="language-python">print(f&amp;quot;Bad news for you:\n\tContent: {hello_world_obj.co_code}\n\tType: {type(hello_world_obj.co_code)}&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>Bad news for you:
Content: b'e\x00d\x00\x83\x01F\x00d\x01S\x00'
Type: &amp;lt;class 'bytes'&amp;gt;
&lt;/code>&lt;/pre>
&lt;p>But what is this stuff?&lt;/p>
&lt;p>It is important to understand what happens behind the scenes.&lt;/p>
&lt;p>After you write a code and call the python command, Python starts a compiling phase creating the ASTs; generating the bytecotes that will be attached to &lt;strong>code objects&lt;/strong>, and then, these code objects will be interpreted by the CPython virtual machine. The diagram below is a simple representation of this process with some details hidden&lt;/p>
&lt;div class="mermaid mermaidContainer">
graph LR;
A[Source Code]-->|parsing|B[Parse Tree];
B-->C[AST];
C-->E[Bytecode];
E-->F[Code Object];
F-->|execution by|G[CPython Virtual Machine];
&lt;/div>
&lt;p>The compilation phase are the firts steps of the above diagram&lt;/p>
&lt;div class="mermaid mermaidContainer">
graph LR;
A[Source Code]-->|parsing|B[Parse Tree];
B-->C[AST];
C-->E[Bytecode];
E-->F[Code Object];
&lt;/div>
&lt;p>But don&amp;rsquo;t worry about most of the big names above. The only concepts that will matter to us are the AST, bytecodes, and Code object.
&lt;strong>Bytecodes are just a compact way to tell the interpreter what we want to do.
The code object is just a way to encapsulate the bytecodes extracted from the AST.&lt;/strong>&lt;/p>
&lt;p>But how does this help us?&lt;/p>
&lt;div class="alert alert-note">
&lt;div>
Our solution will involve the manipulation of the AST and after that generating a new code object with the related manipulated AST!
&lt;/div>
&lt;/div>
&lt;!-- > A funny history from Luciano Ramalho:
> -->
&lt;h2 id="extracting-asts-and-interpreting-them">Extracting ASTs and interpreting them&lt;/h2>
&lt;p>Let&amp;rsquo;s see a simple example of a function and the extracted AST.&lt;/p>
&lt;pre>&lt;code class="language-python">import inspect
import ast
import astor # install this for pretty printing
def example(a: float, b:float = 2) -&amp;gt; float:
s = a+b
return s
tree = ast.parse(inspect.getsource(example))
print(astor.dump(tree))
astor.to_source(tree)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>Module(
body=[
FunctionDef(name='example',
args=arguments(posonlyargs=[],
args=[arg(arg='a', annotation=Name(id='float'), type_comment=None),
arg(arg='b', annotation=Name(id='float'), type_comment=None)],
vararg=None,
kwonlyargs=[],
kw_defaults=[],
kwarg=None,
defaults=[Constant(value=2, kind=None)]),
body=[
Assign(targets=[Name(id='s')],
value=BinOp(left=Name(id='a'), op=Add, right=Name(id='b')),
type_comment=None),
Return(value=Name(id='s'))],
decorator_list=[],
returns=Name(id='float'),
type_comment=None)],
type_ignores=[])
&lt;/code>&lt;/pre>
&lt;p>The above output is our AST and the below image show its graph representation. Take some time looking into it to see how all our code stuff is organized.&lt;/p>
&lt;figure >
&lt;a data-fancybox="" href="/post/python_ast_metaprogramming_with_introspection_and_decorators/simple_ast_hudca446749283cbe6d28b67a245474890_120568_0x1000_resize_lanczos_3.png" >
&lt;img src="/post/python_ast_metaprogramming_with_introspection_and_decorators/simple_ast_hudca446749283cbe6d28b67a245474890_120568_0x1000_resize_lanczos_3.png" alt="" height="400px">
&lt;/a>
&lt;/figure>
&lt;p>Each element in the above output with an upper case letter is a &lt;strong>node&lt;/strong> (Name, BinOp, FunctionDef, etc) from the base class &lt;code>ast.Node&lt;/code>. One of the most important node types is the &lt;code>ast.Name&lt;/code>.
For example,&lt;/p>
&lt;pre>&lt;code>value=BinOp(left=Name(id='a'), op=Add, right=Name(id='b')),
&lt;/code>&lt;/pre>
&lt;p>the &lt;code>ast.Name&lt;/code> is used to refer to variable by the name, &lt;code>id&lt;/code>.&lt;/p>
&lt;p>Now let&amp;rsquo;s come back to our problem. Remember that one bad solution was rewriting every function&lt;/p>
&lt;pre>&lt;code class="language-python">def func(x, y):
random_var = np.random.uniform()
... #more local vars
result = (x+y)**random_var
return result
&lt;/code>&lt;/pre>
&lt;p>as&lt;/p>
&lt;pre>&lt;code class="language-python">def func_transformed(x, y):
random_var = np.random.uniform()
... #more local vars
result = (x+y)**random_var
return result, locals
&lt;/code>&lt;/pre>
&lt;p>The big stuff that we will do is to &lt;strong>write a function that codes new functions for us! This is metaprogramming!&lt;/strong> And at same time we will write a decorator that will avoid any change in our codebase!&lt;/p>
&lt;h2 id="how-can-i-be-efficient-in-metaprogramming">How can I be efficient in metaprogramming?&lt;/h2>
&lt;p>We must create a function that generates a new one similar to &lt;code>func_transformed&lt;/code>. How to get an idea of what we need to do?&lt;/p>
&lt;h3 id="the-6-simple-steps">The 6 simple steps&lt;/h3>
&lt;ol>
&lt;li>Create an example function&lt;/li>
&lt;li>Code the transformed function from the example function&lt;/li>
&lt;li>Code a simple test to check if the transformed function is correct&lt;/li>
&lt;li>Extract the AST from the example and the transformed function&lt;/li>
&lt;li>Compare the ASTs. What is the difference? Annotate this difference somewhere
&lt;ul>
&lt;li>You can use the &lt;code>difflib&lt;/code> module that comes with Python to diff strings&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>Create a new and more complex example function and repeat the process until you get a good idea of what you need to do.&lt;/li>
&lt;/ol>
&lt;p>After you have a good idea of what you need to do, you can start writing your metaprogramming function.&lt;/p>
&lt;h2 id="creating-our-metaprogramming-function">Creating our metaprogramming function&lt;/h2>
&lt;h3 id="first-six-steps-interaction">First six-steps interaction&lt;/h3>
&lt;p>Let&amp;rsquo;s start our first interaction writing one function, the expected transformed function and the test to check if it is correct.&lt;/p>
&lt;pre>&lt;code class="language-python">def example_1(x, y):
internal_var = 222
result = (x+y)**internal_var
return result
def example_1_expected(x, y):
internal_var = 222
result = (x+y)**internal_var
return result, locals()
def test_meta_example_1(meta_func, x, y):
expected_result, expected_locals = example_1_expected(x, y)
result, locals_dict = meta_func(x, y)
assert result == expected_result
assert expected_locals == locals_dict
&lt;/code>&lt;/pre>
&lt;p>Everything looks fine. Now we will use the &lt;code>difflib&lt;/code> to see the differences between the two ASTs.&lt;/p>
&lt;pre>&lt;code class="language-python">import difflib
from pprint import pprint
example_1_ast_str = astor.dump_tree(ast.parse(inspect.getsource(example_1)))
example_1_expected_str = astor.dump_tree(ast.parse(inspect.getsource(example_1_expected)))
pprint(
list(
difflib.unified_diff(example_1_ast_str.splitlines(), example_1_expected_str.splitlines(), n=0)
)
)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>['--- \n',
'+++ \n',
'@@ -3 +3 @@\n',
&amp;quot;- FunctionDef(name='example_1',&amp;quot;,
&amp;quot;+ FunctionDef(name='example_1_expected',&amp;quot;,
'@@ -19 +19 @@\n',
&amp;quot;- Return(value=Name(id='result'))],&amp;quot;,
&amp;quot;+ Return(value=Tuple(elts=[Name(id='result'), &amp;quot;
&amp;quot;Call(func=Name(id='locals'), args=[], keywords=[])]))],&amp;quot;]
&lt;/code>&lt;/pre>
&lt;p>Now we know that we must change this Node in the AST&lt;/p>
&lt;pre>&lt;code>Return(value=Name(id='result'))],
&lt;/code>&lt;/pre>
&lt;p>To this&lt;/p>
&lt;pre>&lt;code>Return(value=Tuple(elts=[Name(id='result'), Call(func=Name(id='locals'), args=[], keywords=[])]))],
&lt;/code>&lt;/pre>
&lt;p>How we can do this? With the help of &lt;code>NodeTransformer&lt;/code> class&lt;/p>
&lt;h3 id="the-nodetransformer-class">The NodeTransformer class&lt;/h3>
&lt;p>The &lt;code>ast.NodeTransformer&lt;/code> allows us to create objects with a walker-like interface. The walker will visit each node in the AST and during each visit, the walker can remove, replace, modify or add nodes, and after that, he can continue to walk to the children of the node or stop there.&lt;/p>
&lt;p>How can we use this?
First, we start by creating a new class derived from &lt;code>ast.NodeTransformer&lt;/code>&lt;/p>
&lt;pre>&lt;code class="language-python">class ASTTransformer(ast.NodeTransformer):
def visit_Return(self, node):
&lt;/code>&lt;/pre>
&lt;p>If you want to interact/change/delete a node of type &lt;code>Something&lt;/code> you must override the &lt;code>visit_Something&lt;/code> method. Thus, because we need to change the &lt;code>Return&lt;/code> node we override the &lt;code>visit_Return&lt;/code>. If we do just the following, our walker will not change our AST,&lt;/p>
&lt;pre>&lt;code class="language-python">class ASTTransformer(ast.NodeTransformer):
...
&lt;/code>&lt;/pre>
&lt;p>Let&amp;rsquo;s start the modifications. We need to create a new node responsible for calling the &lt;code>locals&lt;/code>&lt;/p>
&lt;pre>&lt;code class="language-python">class ASTTransformer(ast.NodeTransformer):
def visit_Return(self, node):
node_locals = ast.Call(
func=ast.Name(id='locals', ctx=ast.Load()),
args=[], keywords=[]
)
self.generic_visit(node)
return node
&lt;/code>&lt;/pre>
&lt;p>We used a &lt;code>Name&lt;/code> node to identify the &lt;code>locals&lt;/code> function. Now, according to the diff result our &lt;code>Return&lt;/code> node must be transformed into a &lt;code>Return&lt;/code> of a Tuple node&lt;/p>
&lt;pre>&lt;code class="language-python">class ASTTransformer(ast.NodeTransformer):
def visit_Return(self, node):
node_locals = ast.Call(
func=ast.Name(id='locals', ctx=ast.Load()),
args=[], keywords=[]
)
new_node.value = ast.Tuple(
elts=[
node.value,
node_locals
],
ctx=ast.Load()
)
self.generic_visit(new_node)
return new_node
&lt;/code>&lt;/pre>
&lt;p>A new thing appeared. The &lt;code>elts&lt;/code> argument. But don&amp;rsquo;t worry, this is just an argument which tells us what the list of other nodes &lt;code>Tuple&lt;/code> has. Whenever you have some doubt about AST stuff, you can check the &lt;code>ast&lt;/code> documentation
&lt;a href="https://docs.python.org/3/library/ast.html" target="_blank" rel="noopener">here&lt;/a>. The documentation is simple to understand because python is simple!&lt;/p>
&lt;p>Everything is almost done. The last thing is to fix our AST. Because when we change the Node we need to fill missing information like the line_number and column_offset. Thanks to python we just need to call &lt;code>fix_missing_locations&lt;/code> to fill this for us.&lt;/p>
&lt;pre>&lt;code class="language-python">
class ASTTransformer(ast.NodeTransformer):
def visit_Return(self, node):
new_node = node
node_locals = ast.Call(
func=ast.Name(id='locals', ctx=ast.Load()),
args=[], keywords=[]
)
new_node.value = ast.Tuple(
elts=[
node.value,
node_locals
],
ctx=ast.Load()
)
ast.copy_location(new_node, node)
ast.fix_missing_locations(new_node)
self.generic_visit(new_node)
return new_node
&lt;/code>&lt;/pre>
&lt;p>Ok, let&amp;rsquo;s see if it is working. We must instantiate our transformer and call the &lt;code>visit&lt;/code> method that tells the walker to walk in the AST and do all the modification we&amp;rsquo;re asking&lt;/p>
&lt;pre>&lt;code class="language-python">tree_meta = ast.parse(inspect.getsource(example_1))
transformer = ASTTransformer()
transformer.visit(tree_meta)
example_1_meta_ast_str = astor.dump_tree(tree_meta)
example_1_expected_str = astor.dump_tree(ast.parse(inspect.getsource(example_1_expected)))
pprint(
list(
difflib.unified_diff(example_1_meta_ast_str.splitlines(), example_1_expected_str.splitlines(), n=0)
)
)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>['--- \n',
'+++ \n',
'@@ -3 +3 @@\n',
&amp;quot;- FunctionDef(name='example_1',&amp;quot;,
&amp;quot;+ FunctionDef(name='example_1_expected',&amp;quot;]
&lt;/code>&lt;/pre>
&lt;p>Our first iteration was successful! Let&amp;rsquo;s try a more complex example.&lt;/p>
&lt;h3 id="the-second-six-steps-interaction">The second six-steps interaction&lt;/h3>
&lt;p>We&amp;rsquo;ll just add more complexity without any particular meaning, we can be creative!&lt;/p>
&lt;pre>&lt;code class="language-python">def example_2(x, y):
internal_var = 222
def sub(x, y):
ommit_this_var = 1
return x - y
result = sub(x,y)**internal_var
return (result, False)
def example_2_expected(x, y):
internal_var = 222
def sub(x, y):
ommit_this_var = 1
return x - y
result = sub(x,y)**internal_var
return ((result, False), locals())
def test_meta_example_2(meta_func, x, y):
expected_result, expected_locals = example_2_expected(x, y)
result, locals_dict = meta_func(x, y)
del locals_dict[&amp;quot;sub&amp;quot;]
del expected_locals[&amp;quot;sub&amp;quot;]
assert result == expected_result
assert expected_locals == locals_dict
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">example_2_ast_str = astor.dump_tree(ast.parse(inspect.getsource(example_2)))
example_2_expected_str = astor.dump_tree(ast.parse(inspect.getsource(example_2_expected)))
pprint(
list(
difflib.unified_diff(example_2_ast_str.splitlines(), example_2_expected_str.splitlines(), n=0)
)
)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>['--- \n',
'+++ \n',
'@@ -3 +3 @@\n',
&amp;quot;- FunctionDef(name='example_2',&amp;quot;,
&amp;quot;+ FunctionDef(name='example_2_expected',&amp;quot;,
'@@ -37 +37,4 @@\n',
&amp;quot;- Return(value=Tuple(elts=[Name(id='result'), &amp;quot;
'Constant(value=False, kind=None)]))],',
'+ Return(',
'+ value=Tuple(',
&amp;quot;+ elts=[Tuple(elts=[Name(id='result'), &amp;quot;
'Constant(value=False, kind=None)]),',
&amp;quot;+ Call(func=Name(id='locals'), args=[], &amp;quot;
'keywords=[])]))],']
&lt;/code>&lt;/pre>
&lt;p>Now, it&amp;rsquo;s time to cross the fingers and see if we need to work more&lt;/p>
&lt;pre>&lt;code class="language-python">tree_meta = ast.parse(inspect.getsource(example_2))
transformer = ASTTransformer()
transformer.visit(tree_meta)
example_2_meta_ast_str = astor.dump_tree(tree_meta)
example_2_expected_str = astor.dump_tree(ast.parse(inspect.getsource(example_2_expected)))
pprint(
list(
difflib.unified_diff(example_2_meta_ast_str.splitlines(), example_2_expected_str.splitlines(), n=0)
)
)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>['--- \n',
'+++ \n',
'@@ -3 +3 @@\n',
&amp;quot;- FunctionDef(name='example_2',&amp;quot;,
&amp;quot;+ FunctionDef(name='example_2_expected',&amp;quot;,
'@@ -27,4 +27 @@\n',
'- Return(',
'- value=Tuple(',
&amp;quot;- elts=[BinOp(left=Name(id='x'), op=Sub, &amp;quot;
&amp;quot;right=Name(id='y')),&amp;quot;,
&amp;quot;- Call(func=Name(id='locals'), args=[], &amp;quot;
'keywords=[])]))],',
&amp;quot;+ Return(value=BinOp(left=Name(id='x'), op=Sub, &amp;quot;
&amp;quot;right=Name(id='y')))],&amp;quot;]
&lt;/code>&lt;/pre>
&lt;p>Unfortunately, our &lt;code>ASTTransformer&lt;/code> was not able to deal with this crazy guy. What is the problem? If you check carefully you will notice that the inner function &lt;code>def sub&lt;/code> is the problem. We don&amp;rsquo;t want to change any &amp;ldquo;sub&amp;rdquo; function, so we need to tell our walker to avoid changing this kind of stuff. To do so, we will create a flag to tell if the walker is in a sub-function, and we will just override the &lt;code>visit_FunctionDef&lt;/code> method to check this flag&lt;/p>
&lt;pre>&lt;code class="language-python">class ASTTransformer(ast.NodeTransformer):
def visit_FunctionDef(self, node):
if self._sub:
return node
self._sub = True
self.generic_visit(node)
return node
def visit_Module(self, node):
self._sub = 0
self.generic_visit(node)
def visit_Return(self, node):
new_node = node
node_locals = ast.Call(
func=ast.Name(id='locals', ctx=ast.Load()),
args=[], keywords=[]
)
new_node.value = ast.Tuple(
elts=[
node.value,
node_locals
],
ctx=ast.Load()
)
ast.copy_location(new_node, node)
ast.fix_missing_locations(new_node)
self.generic_visit(new_node)
return new_node
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">tree_meta = ast.parse(inspect.getsource(example_2))
transformer = ASTTransformer()
transformer.visit(tree_meta)
example_2_meta_ast_str = astor.dump_tree(tree_meta)
example_2_expected_str = astor.dump_tree(ast.parse(inspect.getsource(example_2_expected)))
pprint(
list(
difflib.unified_diff(example_2_meta_ast_str.splitlines(), example_2_expected_str.splitlines(), n=0)
)
)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>['--- \n',
'+++ \n',
'@@ -3 +3 @@\n',
&amp;quot;- FunctionDef(name='example_2',&amp;quot;,
&amp;quot;+ FunctionDef(name='example_2_expected',&amp;quot;]
&lt;/code>&lt;/pre>
&lt;p>Our new &lt;code>ASTTransformer&lt;/code> was able to deal with our new complicated example!&lt;/p>
&lt;h3 id="creating-a-new-function-at-runtime">Creating a new function at runtime&lt;/h3>
&lt;p>We have an &lt;code>ASTTransformer&lt;/code> , now we must compile the transformed &lt;code>AST&lt;/code> into a new function. In python, we can create a new function using the &lt;code>FunctionType&lt;/code>, see below&lt;/p>
&lt;pre>&lt;code class="language-python">from types import FunctionType, CodeType
def transform_and_compile(func: FunctionType)-&amp;gt;FunctionType:
source = inspect.getsource(func)
# we put this to remove the line from source code with the decorator
source = &amp;quot;\n&amp;quot;.join([l for l in source.splitlines() if not l.startswith(&amp;quot;@&amp;quot;)])
tree = ast.parse(source)
transformer = ASTTransformer()
transformer.visit(tree)
code_obj = compile(tree, func.__code__.co_filename, 'exec')
function_code = [c for c in code_obj.co_consts if isinstance(c, CodeType)][0]
# we must to pass the globals context to the function
transformed_func = FunctionType(function_code, func.__globals__)
return transformed_func
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">test_meta_example_1(transform_and_compile(example_1), 4, 2)
test_meta_example_2(transform_and_compile(example_2), 1, 2)
&lt;/code>&lt;/pre>
&lt;p>The &lt;code>transform_and_compile&lt;/code> was able to create new functions that passed all the tests! We can now move further to the final and easy step which is just to integrate this function with our decorator!&lt;/p>
&lt;h2 id="integrating-the-ast-manipulation-with-a-decorator">Integrating the AST manipulation with a decorator&lt;/h2>
&lt;p>We will call the &lt;code>transform_and_compile&lt;/code> right after the &lt;code>def decorate&lt;/code> to avoid unnecessary compilations every time that the decorated function is called.&lt;/p>
&lt;pre>&lt;code class="language-python">def report(fmt):
def decorate(func):
meta_func = transform_and_compile(func)
....
&lt;/code>&lt;/pre>
&lt;p>Inside &lt;code>def decorated&lt;/code> we call the &lt;code>meta_func&lt;/code> and return just the result because we don&amp;rsquo;t want to change our codebase.&lt;/p>
&lt;pre>&lt;code class="language-python">def report(fmt):
def decorate(func):
meta_func = transform_and_compile(func)
...
def decorated(*_args):
_result, internal_locals = meta_func(*_args)
....
return _result
&lt;/code>&lt;/pre>
&lt;p>With all the stuff we learned in the previous post our &lt;code>report&lt;/code> decorator with the above changes will be&lt;/p>
&lt;pre>&lt;code class="language-python">
def report(fmt):
def decorate(func):
meta_func = transform_and_compile(func)
sig = inspect.signature(func)
def decorated(*_args):
_result, internal_locals = meta_func(*_args)
named_args = {}
num_args = len(_args)
for i, (k, v) in enumerate(sig.parameters.items()):
if i &amp;lt; num_args:
named_args[k] = repr(_args[i])
else:
named_args[k] = repr(v.default)
name = func.__name__
result = repr(_result)
args_dict = {
**internal_locals,
**locals(),
**named_args
}
print(fmt.format(**args_dict))
# store the information in some place
return result
return decorated
return decorate
&lt;/code>&lt;/pre>
&lt;p>Let&amp;rsquo;s see the result with a dummy function&lt;/p>
&lt;pre>&lt;code class="language-python">@report(fmt='{name}(a={a}, b={b}, c={c}); sum_ab {sum_ab}, diff_ab {dif_ab}; r={result}')
def dummy_example(a, b, c=2):
sum_ab = a + b
dif_ab = a - b
r = sum_ab**c + dif_ab**c
return r
r = dummy_example(2, 3, 1)
print(&amp;quot;r:&amp;quot;, r)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>dummy_example(a=2, b=3, c=1); sum_ab 5, diff_ab -1; r=4
r: 4
&lt;/code>&lt;/pre>
&lt;p>I know this post is quite hard to read, but I think it&amp;rsquo;s worth sharing it. I hope you enjoyed it!&lt;/p></description></item><item><title>An introspective python decorator using stack frames and the inspect module</title><link>/post/python_decorator_that_exposes_locals/</link><pubDate>Mon, 04 Apr 2022 00:00:00 +0000</pubDate><guid>/post/python_decorator_that_exposes_locals/</guid><description>&lt;details
class="toc-inpage d-print-none d-none d-sm-block d-md-none " open>
&lt;summary class="font-weight-bold">Table of Contents&lt;/summary>
&lt;nav id="TableOfContents">
&lt;ul>
&lt;li>
&lt;ul>
&lt;li>&lt;a href="#gaining-a-deeper-understanding-about-the-execution-context-of-a-function">Gaining a deeper understanding about the execution context of a function&lt;/a>
&lt;ul>
&lt;li>&lt;a href="#the-fluent-python-book-example">The Fluent Python Book example&lt;/a>&lt;/li>
&lt;li>&lt;a href="#current-issues-and-limitations">Current issues and limitations&lt;/a>&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;a href="#creating-an-introspective-code-with-the-inspect-module">Creating an introspective code with the inspect module&lt;/a>
&lt;ul>
&lt;li>&lt;a href="#a-decorator-that-validates-arguments-using-mathematical-notation">A decorator that validates arguments using mathematical notation&lt;/a>&lt;/li>
&lt;li>&lt;a href="#going-back-to-the-fluent-python-example">Going back to the Fluent python example&lt;/a>&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;a href="#how-to-expose-the-locals-inside-of-a-decorator">How to expose the locals() inside of a decorator?&lt;/a>
&lt;ul>
&lt;li>&lt;a href="#call-stack-and-frames-in-python">Call stack and frames in python&lt;/a>&lt;/li>
&lt;li>&lt;a href="#using-systrace-to-track-our-frames">Using sys.trace to track our frames&lt;/a>&lt;/li>
&lt;li>&lt;a href="#lets-solve-our-problem">Let&amp;rsquo;s solve our problem&lt;/a>&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;a href="#conclusion-and-next-steps">Conclusion and next steps&lt;/a>
&lt;ul>
&lt;li>&lt;a href="#it-depends">&amp;ldquo;&amp;hellip;it depends&amp;rdquo;&lt;/a>&lt;/li>
&lt;li>&lt;a href="#the-next-step-we-dont-need-a-trace-we-can-do-better-using-ast-manipulation">The next step: we don&amp;rsquo;t need a trace! We can do better using AST manipulation&lt;/a>&lt;/li>
&lt;li>&lt;a href="#simplenamespace-for-dictkey-instead-of-dictkey">SimpleNamespace for dict.key instead of dict[&amp;ldquo;key]&lt;/a>&lt;/li>
&lt;li>&lt;a href="#want-to-know-more-about-call-stack--inspect-and-trace">Want to know more about call stack , inspect and trace?&lt;/a>&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ul>
&lt;/nav>
&lt;/details>
&lt;p>
&lt;a href="https://www.amazon.com.br/Fluent-Python-Luciano-Ramalho/dp/1491946008" target="_blank" rel="noopener">Fluent Python&lt;/a> is the best resource to learn to use and love python. Some days ago I was reading a section of the chapter 7: &lt;em>&amp;ldquo;Function Decorators and Closures&lt;/em>&amp;rdquo;. This chapter has a lot of interesting and cool examples. Here I&amp;rsquo;ll discuss one of them and how I tried to put more shiny stuff in it.&lt;/p>
&lt;figure id="figure-a-book-that-every-python-programmer-should-read">
&lt;a data-fancybox="" href="/post/python_decorator_that_exposes_locals/fluent_python_huae514437a1dc47e163345635da95e061_41082_0x200_resize_lanczos_3.png" data-caption="A book that every python programmer should read.">
&lt;img src="/post/python_decorator_that_exposes_locals/fluent_python_huae514437a1dc47e163345635da95e061_41082_0x200_resize_lanczos_3.png" alt="" height="200px">
&lt;/a>
&lt;figcaption>
A book that every python programmer should read.
&lt;/figcaption>
&lt;/figure>
&lt;h2 id="gaining-a-deeper-understanding-about-the-execution-context-of-a-function">Gaining a deeper understanding about the execution context of a function&lt;/h2>
&lt;h3 id="the-fluent-python-book-example">The Fluent Python Book example&lt;/h3>
&lt;p>Ramalho’s book presents us with a &lt;code>@clock&lt;/code> decorator that can be used to decorate a method, measure the time it takes to execute, and print in a human-readable format the arguments and name of the method. The example is shown below:&lt;/p>
&lt;pre>&lt;code class="language-python">import time
DEFAULT_FMT = '[{elapsed:0.8f}s] {name}({args}) -&amp;gt; {result}'
def clock(fmt=DEFAULT_FMT):
def decorate(func):
def clocked(*_args):
t0 = time.time()
_result = func(*_args)
elapsed = time.time() - t0
name = func.__name__
args = ', '.join(repr(arg) for arg in _args)
result = repr(_result)
log_string = fmt.format(**locals())
# send to somewhere
# csv, ELK, etc
print(log_string)
return result
return clocked
return decorate
@clock('[{elapsed:0.8f}s] {name}({args})')
def snooze(seconds):
time.sleep(seconds)
return time.time()
for _ in range(3):
snooze(.123)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>[0.12315798s] snooze(0.123)
[0.12315822s] snooze(0.123)
[0.12317085s] snooze(0.123)
&lt;/code>&lt;/pre>
&lt;p>If you don&amp;rsquo;t understand something in the above code I recommend that you take some time searching and reading about each aspect. There are many cool things being used there, for example:&lt;/p>
&lt;ul>
&lt;li>&lt;code>repr&lt;/code> which is a function that returns a string representation of an object.
&lt;ul>
&lt;li>This is essential because the &lt;code>DEFAULT_FMT&lt;/code> is a string, not a &lt;code>f-string&lt;/code>, we can&amp;rsquo;t just put a generic object to be printed in &lt;code>DEFAULT_FMT&lt;/code>.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;code>log_string = fmt.format(**locals())&lt;/code>: instead of creating a repetitive code like &lt;code>fmt.format(**{&amp;quot;result&amp;quot;:result, &amp;quot;args&amp;quot;:args, ...})&lt;/code> we can just use the &lt;code>locals()&lt;/code> which is a dictionary that contains all the local variables of the current scope.&lt;/li>
&lt;/ul>
&lt;p>When I study something I always like to create a fresh problem with the stuff that I&amp;rsquo;ve learned and try to solve it. Sometimes there is no solution. But even if there is no solution, we still learn other stuff.&lt;/p>
&lt;p>I&amp;rsquo;ve started by creating the following example:&lt;/p>
&lt;pre>&lt;code class="language-python">import numpy as np
@clock('[{elapsed:0.8f}s] {name}({args})')
def snooze_and_snore(seconds, snore_loud, min_prob_to_snore=0.4):
time.sleep(seconds)
to_snore = np.random.uniform() &amp;gt; min_prob_to_snore
if to_snore:
if snore_loud:
pass
# r.requets(wake_up_everyone)
pass
return time.time()
for _ in range(3):
snooze_and_snore(.4, True, .1)
snooze_and_snore(.4, False, .1)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>[0.40229130s] snooze_and_snore(0.4, True, 0.1)
[0.40049720s] snooze_and_snore(0.4, False, 0.1)
[0.40058565s] snooze_and_snore(0.4, True, 0.1)
[0.40013075s] snooze_and_snore(0.4, False, 0.1)
[0.40052223s] snooze_and_snore(0.4, True, 0.1)
[0.40057564s] snooze_and_snore(0.4, False, 0.1)
&lt;/code>&lt;/pre>
&lt;p>Ok, what are the problems/issues/limitations that the above code showed me?&lt;/p>
&lt;h3 id="current-issues-and-limitations">Current issues and limitations&lt;/h3>
&lt;ol>
&lt;li>We don&amp;rsquo;t have information about the names of the arguments passed to the method.
&lt;ul>
&lt;li>If the list of arguments is long, trying to understand what is happening becomes a hard task. Because we are increasing the amount of stuff that we must keep in our mind. We are increasing the &lt;strong>cognitive load&lt;/strong> in the terms presented in the excelsior book:
&lt;a href="https://linghao.io/notes/a-philosophy-of-software-design" target="_blank" rel="noopener">A Philosophy of Software Design&lt;/a>.&lt;/li>
&lt;li>A person who is not familiar with the codebase cannot understand what is happening by analyzing the outputs of the decorator. If these outputs are being stored in the ELK stack, this will be unproductive.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>We have the &lt;code>locals()&lt;/code> information from the decorator which is fed by the result of the decorated method. However, we can&amp;rsquo;t get any information about the &lt;code>locals()&lt;/code> of the decorated method. Why is this bad?
&lt;ul>
&lt;li>The final internal state of the method is commonly used to understand the execution of a method.&lt;/li>
&lt;li>Sometimes a method depends on random variables defined in the local context. Thus, the same set of arguments can give different executions. Until now, we don&amp;rsquo;t have a way to get the &lt;code>locals()&lt;/code> of the decorated method. For example, in the &lt;code>snooze_and_snore&lt;/code> we can&amp;rsquo;t know if the person snored or not.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ol>
&lt;p>We will attack the first issue using the inspect module. As I&amp;rsquo;ll show you, we can do cool things with this module.&lt;/p>
&lt;div class="alert alert-note">
&lt;div>
If you know about &lt;code>sys.trace&lt;/code>, &lt;code>call stack&lt;/code> and &lt;code>inspect.signatures&lt;/code> I recommend
you go directly to the section &lt;a href="#lets_solve_our_problem">Let&amp;rsquo;s solve our problem&lt;/a>
&lt;/div>
&lt;/div>
&lt;h2 id="creating-an-introspective-code-with-the-inspect-module">Creating an introspective code with the inspect module&lt;/h2>
&lt;p>The
&lt;a href="https://docs.python.org/3/library/inspect.html" target="_blank" rel="noopener">inspect&lt;/a> module is a Python standard library that provides several tools to help you to introspect and consequently learn about live objects like functions, modules, classes, instances, frame objects (I&amp;rsquo;ll talk about frames later in this post), etc. Well, what can you do with this? Really, a lot of things. You can use it to automatically create documentation, parse the docstrings, manipulate the AST, etc.&lt;/p>
&lt;h3 id="a-decorator-that-validates-arguments-using-mathematical-notation">A decorator that validates arguments using mathematical notation&lt;/h3>
&lt;p>In the last years, we have seen the development of the &lt;code>typing&lt;/code> module and the &lt;code>mypy&lt;/code> static analysis tool for python. This module and tool can be very useful sometimes. However, it doesn&amp;rsquo;t provide some features that are essential for proper validation. But at least in my experience creating code for my Ph.D., I usually don&amp;rsquo;t need so much sophisticated type theory and validation to be able to write a good code for a mathematical modeling tool. Most of the mathematical validation that I need is just checking if an argument still satisfies some constraints or lives in a proper subspace. If not, I need to raise an exception or perform some kind of regularization.&lt;/p>
&lt;p>Let&amp;rsquo;s create a decorator that will validate arguments using simple mathematical notation.&lt;/p>
&lt;p>We will create a dictionary that will contain the annotation as a key and the value will be a human-readable
description of the annotation and a method responsible for check if everything is right.&lt;/p>
&lt;pre>&lt;code class="language-python">import inspect
MATH_SPACES = {
&amp;quot;\in R&amp;quot;: {&amp;quot;name&amp;quot; : &amp;quot;real space&amp;quot;, &amp;quot;validator&amp;quot;: lambda x: isinstance(x, (int, float))},
&amp;quot;\in R_+&amp;quot;: {&amp;quot;name&amp;quot;: &amp;quot;space of real numbers greater than zero&amp;quot;, &amp;quot;validator&amp;quot;: lambda x: isinstance(x, (int, float)) and x &amp;gt; 0},
}
&lt;/code>&lt;/pre>
&lt;p>We will use the &lt;code>inspect.signature&lt;/code> to get the annotations of each argument of the decorated method.
For example, if the decorated method is &lt;code>def foo(a: '\in R', b)&lt;/code> the &lt;code>inspect.signature(foo)&lt;/code> will return an object which we can use to extract an ordered dictionary with the arguments and the annotations. Like this&lt;/p>
&lt;pre>&lt;code class="language-python">def foo(a: &amp;quot;\in R&amp;quot;, b, c:int, d= 2):
pass
for k, v in inspect.signature(foo).parameters.items():
print(k, v, type(v._annotation), v.default)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>a a: '\\in R' &amp;lt;class 'str'&amp;gt; &amp;lt;class 'inspect._empty'&amp;gt;
b b &amp;lt;class 'type'&amp;gt; &amp;lt;class 'inspect._empty'&amp;gt;
c c: int &amp;lt;class 'type'&amp;gt; &amp;lt;class 'inspect._empty'&amp;gt;
d d=2 &amp;lt;class 'type'&amp;gt; 2
&lt;/code>&lt;/pre>
&lt;p>Let&amp;rsquo;s create our decorator. It should be really simple. Just check if we should verify the argument and if so, check if the value respects the annotated mathematical space.&lt;/p>
&lt;pre>&lt;code class="language-python">def math_validator():
def decorate(func):
def decorated(*_args):
sig = inspect.signature(func)
# sig parameters is an ordered dict
for i, (k, v) in enumerate(sig.parameters.items()):
annotation = v._annotation
if not isinstance(annotation, str):
continue
if not annotation in MATH_SPACES:
print(f&amp;quot;{annotation} is not implemented in Math Spaces&amp;quot;)
continue # skip if we didn't implement this space validation
if not MATH_SPACES[annotation][&amp;quot;validator&amp;quot;](_args[i]):
raise ValueError(f&amp;quot;{k} doesn't belong to the {MATH_SPACES[annotation]['name']}&amp;quot;)
result = func(*_args)
print(f&amp;quot;{func.__name__}({_args}) -&amp;gt; {result}&amp;quot;)
return result
return decorated
return decorate
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">@math_validator()
def simple_method(x: &amp;quot;\in R&amp;quot;, y: &amp;quot;\in R_+&amp;quot;, z: float = 2) -&amp;gt; float:
&amp;quot;&amp;quot;&amp;quot;Simple method to add two numbers together and
divide by the last number
Args:
x: The first number to add.
y: The second number to add.
z: it is a float number that will be the power of the result.
This will not be checked for math spaces.
Returns:
float: result
&amp;quot;&amp;quot;&amp;quot;
result = (x+y)/y
return result**z
simple_method(1, 2)
simple_method(1, 0)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>simple_method((1, 2)) -&amp;gt; 1.5
---&amp;gt; 19 simple_method(1, 0)
...
&amp;lt;locals&amp;gt;.decorate.&amp;lt;locals&amp;gt;.decorated(*_args)
11 continue
13 if not MATH_SPACES[annotation][&amp;quot;validator&amp;quot;](_args[i]):
---&amp;gt; 14 raise ValueError(f&amp;quot;{k} doesn't belong to the {MATH_SPACES[annotation]['name']}&amp;quot;)
15 result = func(*_args)
16 print(f&amp;quot;{func.__name__}({_args}) -&amp;gt; {result}&amp;quot;)
ValueError: y doesn't belong to the space of real numbers greater than zero
&lt;/code>&lt;/pre>
&lt;p>Our decorator is quite simple but does the job. You can go deeper into this and use a more sophisticated mathematical notation, printing using latex, etc. But now, let&amp;rsquo;s go back to the Python Fluent example because the &lt;code>inspect.signature&lt;/code> already provides us with a way to solve the first limitation!&lt;/p>
&lt;h3 id="going-back-to-the-fluent-python-example">Going back to the Fluent python example&lt;/h3>
&lt;p>Let&amp;rsquo;s remember one thing that I&amp;rsquo;ve pointed out:&lt;/p>
&lt;blockquote>
&lt;p>A person who is not familiar with the code base will not be able to understand what is happening just by analyzing the outputs of the decorator.&lt;/p>
&lt;/blockquote>
&lt;p>It&amp;rsquo;s obvious that we can overcome this issue by using the &lt;code>inspect&lt;/code> module. Let&amp;rsquo;s create a more elaborated example using monkeys and a zookeeper that must record and report the information about how the life of the monkeys are going.&lt;/p>
&lt;pre>&lt;code class="language-python">NUM_MONKEYS = 20
def feed_monkeys(n_bananas, n_apples=0):
monkeys = {
f&amp;quot;monkey_{i}&amp;quot;: {&amp;quot;bananas&amp;quot;: 0, &amp;quot;apples&amp;quot;: 0}
for i in range(NUM_MONKEYS)
}
while n_bananas &amp;gt; 0 and n_apples &amp;gt; 0:
if np.random.uniform() &amp;lt; 0.4:
continue
monkey = monkey[np.random.choice(list(monkeys.keys()))]
if n_bananas &amp;gt; 0:
monkey[&amp;quot;bananas&amp;quot;] += 1
n_bananas -= 1
if n_apples &amp;gt; 0:
monkey[&amp;quot;apples&amp;quot;] += 1
n_apples -= 1
if n_apples == 0 and n_bananas == 0:
break
&lt;/code>&lt;/pre>
&lt;p>My solution is the &lt;code>@report&lt;/code> decorator presented below.&lt;/p>
&lt;pre>&lt;code class="language-python">def report(fmt=DEFAULT_FMT):
def decorate(func):
def decorated(*_args):
sig = inspect.signature(func)
named_args = {}
num_args = len(_args)
for i, (k, v) in enumerate(sig.parameters.items()):
if i &amp;lt; num_args:
named_args[k] = repr(_args[i])
else:
named_args[k] = repr(v.default)
t0 = time.time()
_result = func(*_args)
elapsed = time.time() - t0
name = func.__name__
result = repr(_result)
args_dict = {
**locals(),
**named_args}
del args_dict['_args']
print(fmt.format(**args_dict))
# store the information in some place
return result
return decorated
return decorate
&lt;/code>&lt;/pre>
&lt;p>What is important here are the following statements:&lt;/p>
&lt;pre>&lt;code class="language-python">sig = inspect.signature(func)
named_args = {}
num_args = len(_args)
for i, (k, v) in enumerate(sig.parameters.items()):
if i &amp;lt; num_args:
named_args[k] = repr(_args[i])
else:
named_args[k] = repr(v.default)
&lt;/code>&lt;/pre>
&lt;p>We are iterating over the signature parameters and checking if it passed the value to &lt;code>func&lt;/code>. If not, we extract the default value from the signature.&lt;/p>
&lt;p>Using the &lt;code>@report&lt;/code> decorator in the &lt;code>feed_monkeys&lt;/code> we have this output:&lt;/p>
&lt;pre>&lt;code class="language-python">NUM_MONKEYS = 20
@report('The zookeeper feeds the monkeys with {n_bananas} bananas and {n_apples} apples. Time to feed: {elapsed:0.4f}s')
def feed_monkeys(n_bananas, n_apples=0):
monkeys = {
f&amp;quot;monkey_{i}&amp;quot;: {&amp;quot;bananas&amp;quot;: 0, &amp;quot;apples&amp;quot;: 0}
for i in range(NUM_MONKEYS)
}
while n_bananas &amp;gt; 0 and n_apples &amp;gt; 0:
if np.random.uniform() &amp;lt; 0.4:
continue
monkey = monkeys[np.random.choice(list(monkeys.keys()))]
if n_bananas &amp;gt; 0:
monkey[&amp;quot;bananas&amp;quot;] += 1
n_bananas -= 1
if n_apples &amp;gt; 0:
monkey[&amp;quot;apples&amp;quot;] += 1
n_apples -= 1
if n_apples == 0 and n_bananas == 0:
break
for _ in range(3):
feed_monkeys(np.random.randint(10, 100))
feed_monkeys(np.random.randint(10, 100), 10)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>The zookeeper feeds the monkeys with 69 bananas and 0 apples. Time to feed: 0.0000s
The zookeeper feeds the monkeys with 92 bananas and 10 apples. Time to feed: 0.0011s
The zookeeper feeds the monkeys with 58 bananas and 0 apples. Time to feed: 0.0000s
The zookeeper feeds the monkeys with 53 bananas and 10 apples. Time to feed: 0.0048s
The zookeeper feeds the monkeys with 42 bananas and 0 apples. Time to feed: 0.0000s
The zookeeper feeds the monkeys with 51 bananas and 10 apples. Time to feed: 0.0025s
&lt;/code>&lt;/pre>
&lt;p>First issue solved! But our decorator is still not useful to the zookeeper and managers. We can’t know how good any monkey is doing or if there is any monkey that eats too much. You could already know that somehow we must have a way to access the monkeys' dictionary inside our &lt;code>def decorated&lt;/code> method. Unfortunately, this is not a trivial task in python because it lacks namespaces decorators. But we also can overcome this with a little trick using a trace tool.&lt;/p>
&lt;h2 id="how-to-expose-the-locals-inside-of-a-decorator">How to expose the locals() inside of a decorator?&lt;/h2>
&lt;p>Now we just need to access the local variables of the decorated method. Let&amp;rsquo;s think more deeply about this:&lt;/p>
&lt;ul>
&lt;li>After the execution of the decorated method, all the information about the local variables is lost. Fortunately, we don&amp;rsquo;t want irrelevant information occupying our system memory.&lt;/li>
&lt;li>The decorator will call the decorated method and will receive the return value. Thus, &lt;strong>there is no way to extract the local variables because now there are no more local variables!&lt;/strong>&lt;/li>
&lt;/ul>
&lt;p>How to solve it? Well, think first about where the local variables have been stored before being erased.&lt;/p>
&lt;h3 id="call-stack-and-frames-in-python">Call stack and frames in python&lt;/h3>
&lt;p>If you came from a non-CS background, maybe you don&amp;rsquo;t know about an important concept called the
&lt;a href="https://en.wikipedia.org/wiki/Call_stack" target="_blank" rel="noopener">&lt;strong>call stack&lt;/strong>&lt;/a>. A call stack is a data structure that stores information related to living things in our program.&lt;/p>
&lt;p>If you call a function in python, a new block of information (&lt;strong>frame&lt;/strong>) is pushed to the top of the call stack. After the function returns the value, this block of information is popped off the call stack. This comprehension can give insights into how to do things in python and how to create good or strange behaviors.&lt;/p>
&lt;p>Well, you can think. If the elements of the call stack are always added on the top if a function (inner) is called by another function (outer) &lt;strong>can I access the values of the local variables from the outer function inside of the inner? Yes, you can!&lt;/strong> Obviously, this is not always a good idea, but it&amp;rsquo;s good to understand this concept. Because this approach can be useful to deal with rigid frameworks like Django.&lt;/p>
&lt;pre>&lt;code class="language-python">%%writefile test_stack.py
import inspect
N_BANANAS = 12
def outer_call(n_bananas):
var_inside_outer_call = 2
n_bananas += 1
inner_call(n_bananas)
def inner_call(n_bananas):
var_inside_inner_call = {&amp;quot;monkey&amp;quot;: 0}
frame_infos = inspect.stack()
n_frames = len(frame_infos)
frames_var_values = {
f.function: [(k, v) for k, v in f.frame.f_locals.items()] for f in frame_infos
}
for i, (function, frame_local) in enumerate(frames_var_values.items()):
print(f'\n\t {function} stack position: {n_frames - i}')
for var_name, value in frame_local:
print(f'\t\t Name: {var_name:25s}Type: {type(value)}')
if var_name in ('n_bananas', 'N_BANANAS', 'var_inside_outer_call'):
print(f'\t\t\t Value: {value}')
print(&amp;quot;\n Before outer_call() call&amp;quot;)
outer_call(N_BANANAS)
print(&amp;quot;\n After outer_call() call&amp;quot;)
frames = [
[(k, v) for k, v in f.frame.f_locals.items()]
for f in inspect.stack()
]
for frame_local in frames:
for var_name, value in frame_local:
print(f'\t\t Name: {var_name:25s}Type: {type(value)}')
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>Overwriting test_stack.py
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">!python test_stack.py
&lt;/code>&lt;/pre>
&lt;pre>&lt;code> Before outer_call() call
inner_call stack position: 3
Name: n_bananas Type: &amp;lt;class 'int'&amp;gt;
Value: 13
Name: var_inside_inner_call Type: &amp;lt;class 'dict'&amp;gt;
Name: frame_infos Type: &amp;lt;class 'list'&amp;gt;
Name: n_frames Type: &amp;lt;class 'int'&amp;gt;
outer_call stack position: 2
Name: n_bananas Type: &amp;lt;class 'int'&amp;gt;
Value: 13
Name: var_inside_outer_call Type: &amp;lt;class 'int'&amp;gt;
Value: 2
&amp;lt;module&amp;gt; stack position: 1
Name: __name__ Type: &amp;lt;class 'str'&amp;gt;
Name: __doc__ Type: &amp;lt;class 'NoneType'&amp;gt;
Name: __package__ Type: &amp;lt;class 'NoneType'&amp;gt;
Name: __loader__ Type: &amp;lt;class '_frozen_importlib_external.SourceFileLoader'&amp;gt;
Name: __spec__ Type: &amp;lt;class 'NoneType'&amp;gt;
Name: __annotations__ Type: &amp;lt;class 'dict'&amp;gt;
Name: __builtins__ Type: &amp;lt;class 'module'&amp;gt;
Name: __file__ Type: &amp;lt;class 'str'&amp;gt;
Name: __cached__ Type: &amp;lt;class 'NoneType'&amp;gt;
Name: inspect Type: &amp;lt;class 'module'&amp;gt;
Name: N_BANANAS Type: &amp;lt;class 'int'&amp;gt;
Value: 12
Name: outer_call Type: &amp;lt;class 'function'&amp;gt;
Name: inner_call Type: &amp;lt;class 'function'&amp;gt;
After outer_call() call
Name: __name__ Type: &amp;lt;class 'str'&amp;gt;
Name: __doc__ Type: &amp;lt;class 'NoneType'&amp;gt;
Name: __package__ Type: &amp;lt;class 'NoneType'&amp;gt;
Name: __loader__ Type: &amp;lt;class '_frozen_importlib_external.SourceFileLoader'&amp;gt;
Name: __spec__ Type: &amp;lt;class 'NoneType'&amp;gt;
Name: __annotations__ Type: &amp;lt;class 'dict'&amp;gt;
Name: __builtins__ Type: &amp;lt;class 'module'&amp;gt;
Name: __file__ Type: &amp;lt;class 'str'&amp;gt;
Name: __cached__ Type: &amp;lt;class 'NoneType'&amp;gt;
Name: inspect Type: &amp;lt;class 'module'&amp;gt;
Name: N_BANANAS Type: &amp;lt;class 'int'&amp;gt;
Name: outer_call Type: &amp;lt;class 'function'&amp;gt;
Name: inner_call Type: &amp;lt;class 'function'&amp;gt;
&lt;/code>&lt;/pre>
&lt;p>First, draw your attention here&lt;/p>
&lt;pre>&lt;code>outer_call stack position: 2
Name: n_bananas Type: &amp;lt;class 'int'&amp;gt;
Value: 13
Name: var_inside_outer_call Type: &amp;lt;class 'int'&amp;gt;
Value: 2
&lt;/code>&lt;/pre>
&lt;p>&lt;strong>Even if we don&amp;rsquo;t pass a variable as an argument to the &lt;code>inner_call&lt;/code> function, this variable can be accessed because still lives in the call stack!&lt;/strong> As I’ve told you, after the execution of &lt;code>outer_call&lt;/code> the call stack doesn&amp;rsquo;t have any information about what happened inside our functions. This discussion will help us to understand the limitations of our solution. Because &lt;strong>our solution is just to watch the call stack and keep the frame before being popped off!&lt;/strong>&lt;/p>
&lt;h3 id="using-systrace-to-track-our-frames">Using sys.trace to track our frames&lt;/h3>
&lt;p>Some time ago I&amp;rsquo;ve talked about how to dissect a process using &lt;code>lsof&lt;/code> and &lt;code>strace&lt;/code>:
&lt;a href="https://medium.com/@devmessias/dissecting-process-and-failures-in-linux-with-lsof-and-strace-cases-for-mlops-d7755b2ce6ca" target="_blank" rel="noopener">Dissecting processes and failures in Linux with lsof and strace&lt;/a>. The &lt;code>strace&lt;/code> is a tracing tool that intercepts and records in someplace any system call made by a process. Python has a built-in tool to do this kind of stuff. Thus, let&amp;rsquo;s use it to track our frames.&lt;/p>
&lt;h3 id="lets-solve-our-problem">Let&amp;rsquo;s solve our problem&lt;/h3>
&lt;p>We will ask our code to monitor any call made with the decorated function. To do so, we will create a new function that will do this and release the trace after the execution of the decorated function.&lt;/p>
&lt;pre>&lt;code class="language-python">import sys
def call_and_extract_frame(func, *args, **kwargs):
frame_var = None
trace = sys.gettrace()
def update_frame_var(stack_frame, event_name, arg_frame):
&amp;quot;&amp;quot;&amp;quot;
Args:
stack_frame: (frame)
The current stack frame.
event_name: (str)
The name of the event that triggered the call.
Can be 'call', 'line', 'return' and 'exception'.
arg_frame:
Depends on the event. Can be a None type
&amp;quot;&amp;quot;&amp;quot;
nonlocal frame_var # nonlocal is a keyword which allows us to change the variable in the outer scope
if event_name != 'call':
return trace
frame_var = stack_frame
sys.settrace(trace)
return trace
sys.settrace(update_frame_var)
try:
func_result = func(*args, **kwargs)
finally:
sys.settrace(trace)
return frame_var, func_result
&lt;/code>&lt;/pre>
&lt;p>Now to use this trick, we just need to call the above function in our &lt;code>@report&lt;/code> decorator. Like this:&lt;/p>
&lt;pre>&lt;code class="language-python">def report(formater):
def decorate(func):
def decorated(*_args):
sig = inspect.signature(func)
named_args = {}
num_args = len(_args)
for i, (k, v) in enumerate(sig.parameters.items()):
if i &amp;lt; num_args:
named_args[k] = repr(_args[i])
else:
named_args[k] = repr(v.default)
### Our modifications
frame_func, _result = call_and_extract_frame(func, *_args)
name = func.__name__
result = repr(_result)
args_dict = {
**named_args,
**locals(),
**frame_func.f_locals,
}
###
print(formater.format(**args_dict))
# do other stuff here
return _result
return decorated
return decorate
&lt;/code>&lt;/pre>
&lt;p>Let&amp;rsquo;s see the results:&lt;/p>
&lt;pre>&lt;code class="language-python">@report(' Monkey {gluttonous_monkey} ate too much bananas. Num monkeys {num_monkeys}')
def feed_monkeys(n_bananas):
num_monkeys = 3
monkeys = {
f&amp;quot;monkey_{i}&amp;quot;: {&amp;quot;bananas&amp;quot;: 0}
for i in range(num_monkeys)
}
while n_bananas &amp;gt; 0:
if np.random.uniform() &amp;lt; 0.4:
continue
monkey = monkeys[np.random.choice(list(monkeys.keys()))]
if n_bananas &amp;gt; 0:
monkey[&amp;quot;bananas&amp;quot;] += 1
n_bananas -= 1
gluttonous_monkey = max(monkeys, key=lambda k: monkeys[k][&amp;quot;bananas&amp;quot;])
for _ in range(3):
feed_monkeys(np.random.randint(10, 100))
&lt;/code>&lt;/pre>
&lt;pre>&lt;code> The monkey monkey_0 eat too much bananas. Num monkeys 3
The monkey monkey_1 eat too much bananas. Num monkeys 3
The monkey monkey_2 eat too much bananas. Num monkeys 3
&lt;/code>&lt;/pre>
&lt;h2 id="conclusion-and-next-steps">Conclusion and next steps&lt;/h2>
&lt;h3 id="it-depends">&amp;ldquo;&amp;hellip;it depends&amp;rdquo;&lt;/h3>
&lt;p>Nice! It worked. But should you use it?&lt;/p>
&lt;figure >
&lt;a data-fancybox="" href="/post/python_decorator_that_exposes_locals/depends_hue4832d1f9bd8c3212ee44b9859787ce4_80720_0x400_resize_q90_lanczos.jpg" >
&lt;img src="/post/python_decorator_that_exposes_locals/depends_hue4832d1f9bd8c3212ee44b9859787ce4_80720_0x400_resize_q90_lanczos.jpg" alt="" height="400px">
&lt;/a>
&lt;/figure>
&lt;ul>
&lt;li>We have drawbacks in our approach:
&lt;ul>
&lt;li>a tracing always creates a cost. Thus, is expected that we will reduce the performance of our system. If you use this just for debugging purposes, it&amp;rsquo;s ok.&lt;/li>
&lt;li>can have conflicts with other tools and libs that also trying to use the trace tool&lt;/li>
&lt;li>it seems dirty!&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ul>
&lt;h3 id="the-next-step-we-dont-need-a-trace-we-can-do-better-using-ast-manipulation">The next step: we don&amp;rsquo;t need a trace! We can do better using AST manipulation&lt;/h3>
&lt;ul>
&lt;li>Using the inspect module to get the argument names it&amp;rsquo;s ok but I&amp;rsquo;ve told you the trace tool can be problematic. But we can replace the trace with another approach. Although, it&amp;rsquo;s more conceptually complex don&amp;rsquo;t require dirty tricks and I believe it&amp;rsquo;s far more beautiful. &lt;strong>The next post it&amp;rsquo;s about this!&lt;/strong>&lt;/li>
&lt;/ul>
&lt;h3 id="simplenamespace-for-dictkey-instead-of-dictkey">SimpleNamespace for dict.key instead of dict[&amp;ldquo;key]&lt;/h3>
&lt;p>We have a minor issue and point of improvement. If you&amp;rsquo;re an cautious developer, probably you notice a flaw here&lt;/p>
&lt;pre>&lt;code class="language-python">args_dict = {
**named_args,
**locals(),
**frame_func.f_locals,
}
&lt;/code>&lt;/pre>
&lt;p>if any of the dicts have common keys, one of them will overwrite the other. This is not what we want. You can use a simple solution like this:&lt;/p>
&lt;pre>&lt;code class="language-python">args_dict = {
&amp;quot;args&amp;quot;: **named_args,
**locals(),
&amp;quot;func_locals&amp;quot;: **frame_func.f_locals,
}
&lt;/code>&lt;/pre>
&lt;p>But this is still annoying because we can do this with a format string:&lt;/p>
&lt;pre>&lt;code>@report(fmt=&amp;quot;{args['n_bananas']} ...&amp;quot;)
&lt;/code>&lt;/pre>
&lt;p>Well, how to solve it? Just use a SimpleNamespace to construct an object!&lt;/p>
&lt;pre>&lt;code class="language-python">from types import SimpleNamespace
def report(formater):
def decorate(func):
def decorated(*_args):
sig = inspect.signature(func)
named_args = {}
num_args = len(_args)
for i, (k, v) in enumerate(sig.parameters.items()):
if i &amp;lt; num_args:
named_args[k] = repr(_args[i])
else:
named_args[k] = repr(v.default)
### Our modifications
frame_func, _result = call_and_extract_frame(func, *_args)
name = func.__name__
result = repr(_result)
args_dict = {
&amp;quot;args&amp;quot;: SimpleNamespace(**named_args),
&amp;quot;args_repr&amp;quot;: repr(SimpleNamespace(**named_args)),
**locals(),
**frame_func.f_locals,
}
###
print(formater.format(**args_dict))
# do other stuff here
return _result
return decorated
return decorate
@report(
&amp;quot;&amp;quot;.join((
'The zookeeper feeds the monkeys with {args.n_bananas},',
'bananas. We loost {n_bananas} bananas. Args {args_repr}'
))
)
def feed_monkeys(n_bananas):
num_monkeys = 3
monkeys = {
f&amp;quot;monkey_{i}&amp;quot;: {&amp;quot;bananas&amp;quot;: 0}
for i in range(num_monkeys)
}
while n_bananas &amp;gt; 0:
if np.random.uniform() &amp;gt; .8:
# &amp;quot;bananas rotted . Monkeys will not eat any banana any more&amp;quot;)
break
if np.random.uniform() &amp;lt; 0.4:
continue
monkey = monkeys[np.random.choice(list(monkeys.keys()))]
if n_bananas &amp;gt; 0:
monkey[&amp;quot;bananas&amp;quot;] += 1
n_bananas -= 1
gluttonous_monkey = max(monkeys, key=lambda k: monkeys[k][&amp;quot;bananas&amp;quot;])
for _ in range(3):
feed_monkeys(np.random.randint(10, 100))
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>The zookeeper feeds the monkeys with 15,bananas. We loost 15 bananas. Args namespace(n_bananas='15')
The zookeeper feeds the monkeys with 80,bananas. We loost 77 bananas. Args namespace(n_bananas='80')
The zookeeper feeds the monkeys with 95,bananas. We loost 92 bananas. Args namespace(n_bananas='95')
&lt;/code>&lt;/pre>
&lt;h3 id="want-to-know-more-about-call-stack--inspect-and-trace">Want to know more about call stack , inspect and trace?&lt;/h3>
&lt;ul>
&lt;li>Call stack and frames:
&lt;a href="https://www.linkedin.com/in/reza-bagheri-71882a76/" target="_blank" rel="noopener">Reza Bagheri&lt;/a> explained
&lt;a href="https://reza-bagheri79.medium.com/python-stack-frames-and-tail-call-optimization-4d0ea55b0542" target="_blank" rel="noopener">here&lt;/a> how to add a tail-call optimization in python using python stack frames.&lt;/li>
&lt;li>Fluent Python book by Luciano Ramalho&lt;/li>
&lt;li>Python documentation:
&lt;a href="https://docs.python.org/3/library/traceback.html" target="_blank" rel="noopener">tracebak&lt;/a>,
&lt;a href="https://docs.python.org/3/library/inspect.html" target="_blank" rel="noopener">inspect and stack&lt;/a>.&lt;/li>
&lt;li>
&lt;a href="https://stackoverflow.com/questions/4214936/how-can-i-get-the-values-of-the-locals-of-a-function-after-it-has-been-executed/4249347#4249347" target="_blank" rel="noopener">Stackoverflow discussion&lt;/a>&lt;/li>
&lt;/ul></description></item><item><title>Grafos e filtragem de arestas I: conceitos e confusões</title><link>/post/edge_graph_filtering/</link><pubDate>Tue, 15 Feb 2022 00:00:00 +0000</pubDate><guid>/post/edge_graph_filtering/</guid><description>&lt;h1 id="introdução">Introdução&lt;/h1>
&lt;div class="alert alert-note">
&lt;div>
Esse post é bem informal e foi feito para o grupo de estudos de MlOps. O conteúdo pode mudar significativamente com o passar do tempo.
&lt;/div>
&lt;/div>
&lt;p>Quando olhamos uma imagem temos a tendência de procurar padrões o que reduz o esforço e tempo necessário para identificar do que se trata. Em análise de dados filtros podem ser aplicados com a mesma motivação.&lt;/p>
&lt;p>Enquanto o processo de filtragem em um conjunto de pontos é apresentado em cursos acadêmicos e tutoriais, existe pouco material em relação a grafos. Portanto, criei esse post para discutir o conceito de filtragem e padrões em grafos e as diferentes maneiras de se obter tal filtragem. Tentei ser didático o suficiente para que uma pessoa fora da computação ou exatas (que esteja iniciando em dados) consiga compreender o texto. Sinta-se à vontade para pular qualquer seção do post :)&lt;/p>
&lt;div class="alert alert-note">
&lt;div>
Grafos, redes e redes complexas são praticamente o mesmo conceito. Portanto, você pode encontrar termos como &lt;em>filtering edges on complex networks&lt;/em>.
&lt;/div>
&lt;/div>
&lt;p>Os exemplos desse post usam python e as seguintes bibliotecas:&lt;/p>
&lt;pre>&lt;code class="language-bash">$ python3 -m pip install numpy matplotlib networkx
&lt;/code>&lt;/pre>
&lt;details
class="toc-inpage d-print-none d-none d-sm-block d-md-none " open>
&lt;summary class="font-weight-bold">Table of Contents&lt;/summary>
&lt;nav id="TableOfContents">
&lt;ul>
&lt;li>&lt;a href="#introdução">Introdução&lt;/a>&lt;/li>
&lt;li>&lt;a href="#o-que-é-um-grafo">O que é um grafo?&lt;/a>&lt;/li>
&lt;li>&lt;a href="#o-que-é-filtragem">O que é filtragem?&lt;/a>&lt;/li>
&lt;li>&lt;a href="#confusões-sobre-o-que-é-filtragem-em-grafos">Confusões sobre o que é filtragem em grafos&lt;/a>&lt;/li>
&lt;li>&lt;a href="#algumas-propriedades-de-grafos">Algumas propriedades de grafos&lt;/a>
&lt;ul>
&lt;li>&lt;a href="#componentes">Componentes&lt;/a>&lt;/li>
&lt;li>&lt;a href="#comunidades">Comunidades&lt;/a>
&lt;ul>
&lt;li>&lt;a href="#caminho-1-inferir">Caminho 1: &lt;strong>Inferir&lt;/strong>&lt;/a>&lt;/li>
&lt;li>&lt;a href="#caminho-2-quantificardescrever">Caminho 2: &lt;strong>Quantificar/Descrever&lt;/strong>&lt;/a>&lt;/li>
&lt;li>&lt;a href="#caminho-3-visualizar">Caminho 3: &lt;strong>Visualizar&lt;/strong>&lt;/a>&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;a href="#filtros">Filtros&lt;/a>
&lt;ul>
&lt;li>&lt;a href="#estrutural-threshold">Estrutural: threshold&lt;/a>
&lt;ul>
&lt;li>&lt;a href="#pontos-positivos">Pontos positivos&lt;/a>&lt;/li>
&lt;li>&lt;a href="#pontos-negativos">Pontos negativos&lt;/a>&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;a href="#estatistico">Estatístico: quebrando a varinha, processo de Dirichlet&lt;/a>
&lt;ul>
&lt;li>&lt;a href="#pontos-positivos-1">Pontos positivos&lt;/a>&lt;/li>
&lt;li>&lt;a href="#pontos-negativos-1">Pontos negativos&lt;/a>&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ul>
&lt;/nav>
&lt;/details>
&lt;h1 id="o-que-é-um-grafo">O que é um grafo?&lt;/h1>
&lt;p>Um grafo é uma estrutura de dados que você constantemente está em contato. Alguns exemplos: sua rede de seguidores e seguidores no twitter, as transações financeiras associadas a sua chave PIX, as relações de repositório e contribuições no github, etc.&lt;/p>
&lt;p>Um grafo armazena objetos que têm relações pares a pares entre si. Sendo que é possível associar a cada objeto ou relação um outro tipo de dado genérico tais como um número real, um vetor, uma imagem ou mesmo outro grafo.&lt;/p>
&lt;p>A imagem abaixo representa um grafo dirigido formado por 4 vértices.&lt;/p>
&lt;pre>&lt;code class="language-mermaid">graph TD;
A--&amp;gt;B;
B--&amp;gt;A;
A--&amp;gt;C;
B--&amp;gt;D;
C--&amp;gt;D;
&lt;/code>&lt;/pre>
&lt;p>Vamos usar a letra $G$ para representar um grafo. A letra $V$ para o conjunto de vértices (objetos) e $E$ para o conjunto de arestas (relações). Na imagem acima nosso grafo seria dado então pelo conjunto $V=\{A,B,C,D\}$ e $E=\{(A,B), (B,A), (A,C), (B,D), (C,D)\}$.&lt;/p>
&lt;p>Como disse no início desta seção é possível associar &lt;em>coisas&lt;/em> tanto as arestas quanto os vértices. Por exemplo, o grafo abaixo poderia representar transações financeiras entre 3 pessoas e o valor que cada uma tem em sua conta corrente&lt;/p>
&lt;pre class="mermaid ignoreTex mermaidContainer">
graph TD;
A[A R$100,00]-->|R$1|B;
B[B R$3,00]-->|R$2|A;
C[C R$0]-->|R$0,50|A;
&lt;/pre>
&lt;p>Tais grafos de transações financeiras são usados, por exemplo, para detectar crimes de lavagem de dinheiro, formação de quadrilhas e fraudes quando o comportamento de um dado cliente é anómalo. Os valores nas arestas são os &lt;strong>pesos&lt;/strong> do grafo.&lt;/p>
&lt;h1 id="o-que-é-filtragem">O que é filtragem?&lt;/h1>
&lt;p>&lt;strong>Filtro tem origem na palavra feltro. O feltro era o material feito principalmente de lã usado antigamente para separar um líquido de suas impurezas.&lt;/strong> Um filtro em análise de dados é a mesma coisa: uma ferramenta que separa um conjunto de dados de uma sujeira, ruído. Portanto, assim como para filtrar uma bebida temos que decidir antes algumas coisas:&lt;/p>
&lt;ul>
&lt;li>O que queremos que seja removido?&lt;/li>
&lt;li>O quão eficiente é nosso filtro?&lt;/li>
&lt;li>Qual é o resultado esperado?&lt;/li>
&lt;/ul>
&lt;h2 href="ruidos">
Filtragem para remover ruídos&lt;/h2>
&lt;p>Talvez a primeira coisa que vem à sua cabeça quando ouve a palavra filtro é Instagram. Alguns filtros de fotos feitos para embelezar nada mais são que um filtro para remoção de ruídos.&lt;/p>
&lt;figure id="figure-imagem-original-e-imagem-com-contaminação-de-um-ruído">
&lt;a data-fancybox="" href="/post/edge_graph_filtering/photo_noisy_hu82d76e04dbaf989091cb8bf76c11c929_737197_0x200_resize_lanczos_3.png" data-caption="Imagem original e imagem com contaminação de um ruído.">
&lt;img data-src="/post/edge_graph_filtering/photo_noisy_hu82d76e04dbaf989091cb8bf76c11c929_737197_0x200_resize_lanczos_3.png" class="lazyload" alt="" width="100%" height="200px">
&lt;/a>
&lt;figcaption>
Imagem original e imagem com contaminação de um ruído.
&lt;/figcaption>
&lt;/figure>
&lt;p>O que consideramos ruído depende das respostas das perguntas que levantei anteriormente. Um ruído em uma imagem pode ser uma contribuição espúria devido ao sensor de uma câmera ser ruim. Um ruído pode ser também algo intrínseco, por exemplo os poros e rugas na sua pele.&lt;/p>
&lt;h2 href="gestalt">
Filtragem para ressaltar características e Gestalt
&lt;/h2>
&lt;p>Os princípios de &lt;em>Gestalt&lt;/em> são suposições de certas leis sobre como a mente humana processa imagens através do reconhecimento de padrões. Em resumo, tal princípio estabelece que a percepção não é baseada em elementos individuais, mas em padrões em que os elementos são arranjados ou têm contrastes entre si. &lt;strong>Você não compreende uma imagem analisando cada pixel individualmente, mas como os pixels se organizam e diferem entre si!&lt;/strong>&lt;/p>
&lt;figure id="figure-os-principios-da-gestalt-são-apresentados-nessa-figura--">
&lt;a data-fancybox="" href="/post/edge_graph_filtering/gestalt_principles_hu63f5cabf0d008b5b0b2fbf74c03a67fd_175876_0x400_resize_q90_lanczos.jpg" data-caption="Os principios da &amp;lt;em&amp;gt;Gestalt&amp;lt;/em&amp;gt; são apresentados nessa figura. [].">
&lt;img data-src="/post/edge_graph_filtering/gestalt_principles_hu63f5cabf0d008b5b0b2fbf74c03a67fd_175876_0x400_resize_q90_lanczos.jpg" class="lazyload" alt="" width="100%" height="200px">
&lt;/a>
&lt;figcaption>
Os principios da &lt;em>Gestalt&lt;/em> são apresentados nessa figura. [].
&lt;/figcaption>
&lt;/figure>
&lt;p>Como se relaciona com os grafos? Um dos porquês para realizar a filtragem de um grafo consiste em remover relações (arestas) espúrias para ressaltar um dado padrão que queremos analisar. Comumente, esse padrão são estruturas de comunidades e/ou agrupamentos obtidos via métodos de visualização.&lt;/p>
&lt;figure id="figure-os-princípios-da-gestalt-são-usados-para-desenvolver-métodos-de-processamento-de-imagens-imagem-retirada-de-">
&lt;a data-fancybox="" href="/post/edge_graph_filtering/gestalt_cv_example_hu5510a9064a332f07be8be12a15f3553e_77088_0x300_resize_lanczos_3.png" data-caption="Os princípios da &amp;lt;em&amp;gt;Gestalt&amp;lt;/em&amp;gt; são usados para desenvolver métodos de processamento de imagens. Imagem retirada de []">
&lt;img data-src="/post/edge_graph_filtering/gestalt_cv_example_hu5510a9064a332f07be8be12a15f3553e_77088_0x300_resize_lanczos_3.png" class="lazyload" alt="" width="100%" height="200px">
&lt;/a>
&lt;figcaption>
Os princípios da &lt;em>Gestalt&lt;/em> são usados para desenvolver métodos de processamento de imagens. Imagem retirada de []
&lt;/figcaption>
&lt;/figure>
&lt;p>Na imagem acima é mostrado o resultado de um método baseado na &lt;em>Gestalt&lt;/em> para simplificar uma imagem. Em que um algoritmo extrair um padrão de linhas de uma imagem. Em redes complexas temos o conceito de &lt;em>backbones&lt;/em> que são uma espécie de espinha dorsal, esqueleto, que representa as relações mais importantes entres os vértices (ficará mais claro na seção sobre
&lt;a href="#estatistico">backbones&lt;/a> . Nesse ponto não necessariamente estamos removendo relações assumindo que elas são um ruído da nossa medida, mas apenas queremos ressaltar esse backbone.&lt;/p>
&lt;h2 href="comutacional">
Filtragem para reduzir o custo computacional&lt;/h2>
&lt;p>Embora a filtragem possa ser usada para remover uma contaminação em um dado e/ou facilitar termos &lt;em>insights&lt;/em> Conseguimos também reduzir o custo computacional de algoritmos que atuam nesses dados. Um exemplo simples é mostrado no código abaixo:&lt;/p>
&lt;pre>&lt;code class="language-python">import numpy as np
import io
X, Y = np.meshgrid(
np.linspace(-5, 5, 100), np.linspace(-5, 5, 100))
z = np.exp(-0.1*(X**2 + Y**2))
z_noise = z + np.random.normal(0, 0.1, z.shape)
z = (z / z.max()*255).astype(np.uint8)
z_noise = (z_noise / z_noise.max()*255).astype(np.uint8)
data_noisy = io.BytesIO()
data = io.BytesIO()
np.savez_compressed(data_noisy, z_noise)
np.savez_compressed(data, z)
print(f&amp;quot;Noisy {data_noisy.getbuffer().nbytes/10**6:.1f} MB&amp;quot;)
print(f&amp;quot;Original {data.getbuffer().nbytes/10**6:.1f} MB&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>Noisy 3.6 MB
Original 0.2 MB
&lt;/code>&lt;/pre>
&lt;p>O output indica que &lt;strong>o resultado de contaminação por ruído aumenta o custo de armazenamento de um mesmo padrão de dados.&lt;/strong>&lt;/p>
&lt;p>Em grafos, filtrar para reduzir custo computacional costuma ser essencial. Por exemplo, muitos algoritmos escalam com o número de arestas. Portanto, um grafo em que cada par de vértices tem uma aresta teria custo computacional $O(número\ \ de\ \ vértices^2)$ &lt;strong>o que é impraticável para apenas algumas dezenas de milhares de vértices. Portanto, tornando a análise de dados impossível.&lt;/strong>&lt;/p>
&lt;h1 id="confusões-sobre-o-que-é-filtragem-em-grafos">Confusões sobre o que é filtragem em grafos&lt;/h1>
&lt;p>Antes de entrar mais a fundo na filtragem de grafos é melhor você ler com calma a seguinte desambiguação para você não ficar perdido na literatura.&lt;/p>
&lt;div class="alert alert-warning">
&lt;div>
&lt;p>&lt;strong>Desambiguação.&lt;/strong>&lt;/p>
&lt;p>A área de grafos/redes foi/é é meio bagunçada pois cada campo de estudos (engenharia, computação, matemática, física, sociologia, etc) costuma reinventar o mesmo método com outro nome ou usar nomes iguais para coisas diferentes.&lt;/p>
&lt;ul>
&lt;li>
&lt;p>Graph coarsening&lt;/p>
&lt;p>Em ciência da computação: o processo de obter uma representação mais grosseira de um grafo removendo arestas e/ou vértices.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>Edge filtering:&lt;/p>
&lt;p>Em ciência da computação: o processo de aplicar um filtro (processamento de sinais) em valores definidos nas arestas. &lt;strong>Uma filtragem nos valores associados às arestas!&lt;/strong>&lt;/p>
&lt;p>Outras disciplinas: o processo de remover arestas que não se adequam a um dado padrão.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>Graph sparsification&lt;/p>
&lt;p>Termo usado para representar tanto a remoção de vértices quanto arestas (no mesmo sentido de graph coarsening). Por exemplo: “spectral edge sparsification”. Contudo, é mais utilizado quando você parte de um grafo vazio (sem relações) e vai adicionando tentando preservar as propriedades espectrais do grafo original.&lt;/p>
&lt;/li>
&lt;/ul>
&lt;p>Você pode encontrar trabalhos com o termo &lt;em>spectral filtering&lt;/em> ou &lt;em>spectral coarsening&lt;/em> , ambos significando a mesma coisa. Contudo, spectral filters costuma ser usado mais em trabalhos de processamento de sinal em grafos.&lt;/p>
&lt;/div>
&lt;/div>
&lt;p>Quando você aplica um filtro em uma foto para te deixar mais bonito você obviamente objetiva que as pessoas ainda te reconheçam. Isto é, as formas e aspectos mais importantes do seu rosto devem ser preservadas ou pouco alteradas. Vamos representar essas considerações por:
$$
\begin{eqnarray}
\mathcal P_{forma}(foto\ \ original) \sim \mathcal P_{forma}(foto\ \ filtrada)\newline
\mathcal P_{cor}(foto\ \ original) \sim \mathcal P_{cor}(foto\ \ filtrada)\newline
&amp;hellip;etc
\end{eqnarray}
$$
Também espera-se que o ruído da câmera, rugas e imperfeições sejam reduzidas $\mathcal P_{rugas}(foto\ \ original) \neq \mathcal P_{rugas}(foto\ \ filtrada)$ e $|rugas\ \ foto \ \ filtrada|\ll|rugas\ \ foto \ \ original| $. O símbolo $|.|$ significa que estamos contando o número de rugas da foto, do conjunto de rugas, e $\ll$ significa muito menor.&lt;/p>
&lt;p>Da mesma maneira que no caso de fotos, se temos um grafo, $G$, queremos que sua versão filtrada, $\tilde G$, tenha uma ou mais propriedades (definido de antemão) preservadas após efetuar a filtragem, isto é
$$
\mathcal P_{algo} (G) \sim \mathcal P_{algo} (\tilde G)
$$&lt;/p>
&lt;p>Sendo que o objetivo principal costuma ser uma redução drástica no número de relações (arestas), $|\tilde E| \le |E|$. OK, então antes de entrar nos métodos de filtragem precisamos discorrer sobre quais seriam essas propriedades que queremos preservar.&lt;/p>
&lt;div class="alert alert-note">
&lt;div>
&lt;p>Diferente de uma imagem em que filtros só ocorrem nos valores definidos na posição dos pixels em um grafo, podemos filtrar tanto os valores definidos nos vértices/arestas quanto a própria estrutura do grafo em si.&lt;/p>
&lt;ul>
&lt;li>Novamente: filtrar a estrutura de um grafo $\neq$ filtrar valores definidos na estrutura de um grafo&lt;/li>
&lt;/ul>
&lt;/div>
&lt;/div>
&lt;h1 id="algumas-propriedades-de-grafos">Algumas propriedades de grafos&lt;/h1>
&lt;h2 id="componentes">Componentes&lt;/h2>
&lt;p>Uma propriedade importante de um grafo é o número de componentes. Um grafo é fortemente conectado quando é possível sair de qualquer vértice e chegar em qualquer outro. &lt;strong>Um grafo fortemente conectado tem apenas uma componente&lt;/strong>.&lt;/p>
&lt;p>Por exemplo, abaixo é apresentado um grafo fortemente conectado&lt;/p>
&lt;pre>&lt;code class="language-mermaid">graph LR;
A---B;
D---A;
B---C
A---C;
D---E;
&lt;/code>&lt;/pre>
&lt;p>Ao remover a aresta $(D , A)$ obtemos o seguinte grafo&lt;/p>
&lt;pre>&lt;code class="language-mermaid">graph LR;
A---B;
B---C
A---C;
D---E;
&lt;/code>&lt;/pre>
&lt;p>Como é impossível sair de $D$ ou $E$ e chegar em $A$, $B$ ou $C$ após a remoção, o grafo não é mais fortemente conectado e tem duas componentes. Qual a relação disso com filtragem?&lt;/p>
&lt;div class="alert alert-note">
&lt;div>
&lt;p>Para muitos problemas, espera-se que métodos de filtragem sejam bons em preservar o número de componentes. Pois isso afeta em muito as dinâmicas ocorrendo no grafo. Assim como algoritmos de análise de dados. x'&lt;/p>
&lt;p>Imagina se ao realizar uma filtragem você remova uma aresta que impede a contaminação por um vírus entre duas cidades no seu modelo?&lt;/p>
&lt;/div>
&lt;/div>
&lt;h2 id="comunidades">Comunidades&lt;/h2>
&lt;p>Dentro de cada componente de um grafo temos o conceito de comunidade. Intuitivamente, quando pensamos em comunidade no âmbito das relações pessoais imaginamos um grupo de pessoas que tem fortes relações entre si, muito mais fortes que as relações com outras pessoas fora do grupo. Por exemplo, família, colegas de trabalho etc. Nesse contexto, qual é a tarefa de detecção de comunidades? Como efetuar tal tarefa?&lt;/p>
&lt;div class="alert alert-note">
&lt;div>
Em certos casos queremos que a filtragem não altere a identificação das estruturas de comunidade no nosso grafo.
&lt;/div>
&lt;/div>
&lt;p>Suponha que você queira modelar o grupo de pessoas pertencentes a dois partidos políticos, opostos na ideologia. Você pode representar as relações entre as pessoas usando grafos. Colocando uma aresta entre uma pessoa e outra com o peso representado um grau de &lt;em>concordância&lt;/em> entre certos assuntos. O que seria um algoritmo de detecção de comunidade em tal caso? Se temos o &lt;em>ground truth&lt;/em>, isto é, o partido que cada pessoa se identifica, o algoritmo é uma função, $f$, que recebendo as relações , $E$, cospe um indíce que associa cada pessoa um partido $f: (Pessoa, E) \mapsto \{Esquerda,Direita\}$. Mas como construir essa $f$? &lt;strong>Na minha opinião existem três caminhos principais:&lt;/strong>&lt;/p>
&lt;div class="alert alert-note">
&lt;div>
Não existe uma única definição formal para comunidade. Esse conceito muda dependendo da abordagem que você escolheu para encontrar as comunidades dentro de cada componente.
&lt;/div>
&lt;/div>
&lt;h3 id="caminho-1-inferir">Caminho 1: &lt;strong>Inferir&lt;/strong>&lt;/h3>
&lt;ul>
&lt;li>Pegue por exemplo a distribuição normal. Quando trabalhamos com dados que acreditamos que podem ser modelados por tal distribuição realizamos um processo de ajuste de parâmetros, tentando estimar a média e o desvio padrão da população. A ideia aqui é similar. Propõe-se um modelo capaz de gerar grafos tendo como restrições um conjunto de parâmetros.. O objetivo é otimizar tais parâmetros tal que o modelo generativo seja um bom candidato para &lt;em>gerador&lt;/em> do grafo original.&lt;/li>
&lt;/ul>
&lt;p>O modelo generativo mais famoso é conhecido como &lt;strong>S&lt;/strong>tocahastic &lt;strong>B&lt;/strong>lock &lt;strong>M&lt;/strong>odel (&lt;strong>SBM&lt;/strong>). Em português, Modelo de Bloco Estocástico. Usando o networkx você pode gerar uma amostra de um grafo através desse modelo usando o seguinte código&lt;/p>
&lt;pre>&lt;code class="language-python">import networkx as nx
import matplotlib.pyplot as plt
# esses são os parâmetros que definiram o número de indivíduos
# dentro de cada comunidade
n1, n2, n3 = 30, 40, 60
# esses são os parâmetros que definem a probabilidade
# de conexão entre indivíduos da mesma comunidade
p11, p22, p33 = 0.4, 0.3, 0.7
# esses são os parâmetros que definem a probabilidade
# de conexão entre indivíduos de comunidades distintas
p12 = .01
p13 = .1
p23 = .01
sizes = [n1, n2, n3]
probs = [[p11, p12, p13], [p12, p22, p23], [p13, p23, p33]]
g_sbm = nx.stochastic_block_model(sizes, probs, seed=0)
W = nx.adjacency_matrix(g_sbm).todense()
plt.imshow(W)
plt.show()
&lt;/code>&lt;/pre>
&lt;figure id="figure-a-matriz-de-adjacência-todos-os-pesos-são-1-do-grafo-gerado-por-nosso-modelo">
&lt;a data-fancybox="" href="/post/edge_graph_filtering/adj_sbm_hueb053748435c7d9559526a97c502365f_19313_400x0_resize_lanczos_3.png" data-caption="A matriz de adjacência (todos os pesos são 1) do grafo gerado por nosso modelo.">
&lt;img data-src="/post/edge_graph_filtering/adj_sbm_hueb053748435c7d9559526a97c502365f_19313_400x0_resize_lanczos_3.png" class="lazyload" alt="" width="400px" height="100%">
&lt;/a>
&lt;figcaption>
A matriz de adjacência (todos os pesos são 1) do grafo gerado por nosso modelo.
&lt;/figcaption>
&lt;/figure>
&lt;p>A ideia de inferência de métodos que usam SBM de forma geral é a seguinte:&lt;/p>
&lt;ol>
&lt;li>Extraia o conjunto de arestas, $E$, de um grafo qualquer: uma rede social, uma rede de transações financeiras, etc.&lt;/li>
&lt;li>Pegue um SBM, tente estimar o número de partições, probabilidade de conexões intra e entre grupos e em qual bloco cada vértice pertence tal que os grafos gerados pelo SBM melhor represente o seu grafo original. No final, você tem uma maneira de identificar com cada vértice uma comunidade (partição).&lt;/li>
&lt;/ol>
&lt;p>O SBM é poderoso e ao contrário dos outros métodos te fornece uma maneira de checar a qualidade das comunidades encontradas. Isto é, se fazem sentido ou só são frutos de algo aleatório. Contudo, por ser uma técnica mais recente com uma implementação difícil, não são todas as bibliotecas que fornecem esse recurso. A biblioteca mais famosa para SBM é o
&lt;a href="https://graph-tool.skewed.de/" target="_blank" rel="noopener">Graph Tool&lt;/a> que consegue estimar comunidades para grafos com centenas de milhares de vértices. Não poderei discorrer mais ou mostrar como usar o SBM pois é um tema bem complexo, tema para um post separado. Mas o importante agora é você ter conseguido absorver pelo menos a ideia.&lt;/p>
&lt;h3 id="caminho-2-quantificardescrever">Caminho 2: &lt;strong>Quantificar/Descrever&lt;/strong>&lt;/h3>
&lt;ul>
&lt;li>Você parte de uma função $f$ qualquer. Exemplo, $f$ é uma função que identifica todo mundo como esquerda ou direita, um sorteio aleatório, etc.&lt;/li>
&lt;li>Com tal identificação você estipula uma grandeza que vai mensurar o quão forte é a coesão entre as pessoas de cada grupo e quão fraca é entre os grupos. Um exemplo de grandeza que mensura isso é a &lt;strong>modularidade&lt;/strong>.&lt;/li>
&lt;li>Você irá alterar a sua $f$ tentando maximizar tal grandeza.&lt;/li>
&lt;/ul>
&lt;p>O networkx por exemplo possui um método de maximização de modularidade usando um algoritmo guloso. Vamos usar o grafo gerado pelo sbm para testar esse método usando o seguinte script:&lt;/p>
&lt;pre>&lt;code class="language-python">from networkx.algorithms import community
def find_where(n, p):
return [i for i in range(len(p)) if n in p[i]][0]
def plot(g, community_index, p):
labels = [chr(ord('A') + i) for i in range(len(p))]
plt.scatter(range(len(g.nodes)), community_index)
plt.ylabel('Community')
plt.xlabel('Vertex Id')
plt.yticks(range(len(p)), labels)
plt.show()
p = community.greedy_modularity_communities(g_sbm)
g_sbm_community_index = [find_where(n, p) for n in g_sbm.nodes]
print(f&amp;quot;Found {len(set(g_sbm_community_index))} communities&amp;quot;)
plot(g_sbm, g_sbm_community_index, p)
&lt;/code>&lt;/pre>
&lt;figure id="figure-resultado-da-identificação-de-comunidades-usando-o-algoritmo-guloso-parece-ok">
&lt;a data-fancybox="" href="/post/edge_graph_filtering/modularity_sbm_hu232f725335f418633017afb243ed9c06_2880_400x0_resize_lanczos_3.png" data-caption="Resultado da identificação de comunidades usando o algoritmo guloso. Parece Ok">
&lt;img data-src="/post/edge_graph_filtering/modularity_sbm_hu232f725335f418633017afb243ed9c06_2880_400x0_resize_lanczos_3.png" class="lazyload" alt="" width="400px" height="100%">
&lt;/a>
&lt;figcaption>
Resultado da identificação de comunidades usando o algoritmo guloso. Parece Ok
&lt;/figcaption>
&lt;/figure>
&lt;p>Temos um resultado muito bom. Mas será que podemos empregar isso em qualquer caso? Vejamos o que acontece quando aplicamos o mesmo algoritmo para um grafo aleatório.&lt;/p>
&lt;pre>&lt;code class="language-python"># erdos_reyni é um modelo de grafo aleatório
g = nx.erdos_renyi_graph(150, 0.1, seed=0)
p = community.greedy_modularity_communities(g)
g_community_index = [find_where(n, p) for n in g.nodes]
plot(g, g_community_index, p)
&lt;/code>&lt;/pre>
&lt;figure id="figure-resultado-da-identificação-de-comunidades-usando-o-algoritmo-guloso-para-o-modelo-er">
&lt;a data-fancybox="" href="/post/edge_graph_filtering/modularity_er_hu5a3fc90699528d500dae239de7f4b909_3810_400x0_resize_lanczos_3.png" data-caption="Resultado da identificação de comunidades usando o algoritmo guloso para o modelo ER.">
&lt;img data-src="/post/edge_graph_filtering/modularity_er_hu5a3fc90699528d500dae239de7f4b909_3810_400x0_resize_lanczos_3.png" class="lazyload" alt="" width="400px" height="100%">
&lt;/a>
&lt;figcaption>
Resultado da identificação de comunidades usando o algoritmo guloso para o modelo ER.
&lt;/figcaption>
&lt;/figure>
&lt;p>O algoritmo guloso encontrou 4 comunidades e o ponto ruim é que não temos como saber o quão confiável é essa resposta. Mas podemos dizer que provavelmente ela não deveria ser usada pois partimos de um modelo de grafo aleatório.&lt;/p>
&lt;p>Devemos tomar muito cuidado com métodos de detecção por maximização de modularidade e similares. Recomendo ver alguns trabalhos sobre modelos de bloco estocástico, especialmente os feitos pelo Tiago Peixoto.&lt;/p>
&lt;blockquote class="twitter-tweet">&lt;p lang="en" dir="ltr">New blog post! This time, on something tame and uncontroversial:&lt;br>&lt;br>&amp;quot;Modularity maximization considered harmful&amp;quot;&lt;br>&lt;br>It&amp;#39;s the most popular method used for community detection. It is also one of the most problematic. 1/11&lt;br>&lt;br>(Based on &lt;a href="https://t.co/iCxFjKOIT1">https://t.co/iCxFjKOIT1&lt;/a>)&lt;a href="https://t.co/IRdCFwttQL">https://t.co/IRdCFwttQL&lt;/a>&lt;/p>&amp;mdash; Tiago Peixoto (@tiagopeixoto) &lt;a href="https://twitter.com/tiagopeixoto/status/1467798790346260484?ref_src=twsrc%5Etfw">December 6, 2021&lt;/a>&lt;/blockquote>
&lt;script async src="https://platform.twitter.com/widgets.js" charset="utf-8">&lt;/script>
&lt;div class="alert alert-warning">
&lt;div>
Métodos de detecção de comunidade usando modularidade (Gelphi) são úteis. Contudo, podemos identificar comunidades mesmo no caso de um grafo totalmente aleatório! Tome cuidado.
&lt;/div>
&lt;/div>
&lt;h3 id="caminho-3-visualizar">Caminho 3: &lt;strong>Visualizar&lt;/strong>&lt;/h3>
&lt;ul>
&lt;li>Você utiliza um método que mapeia cada vértice do seu grafo em um espaço vetorial. Por exemplo &lt;strong>t-sne&lt;/strong>, &lt;strong>UMAP&lt;/strong>, &lt;strong>force-directed&lt;/strong>, &lt;strong>spectral embedding&lt;/strong> etc. Com sua visualização você realiza uma inspeção (totalmente subjetiva!) para identificar as comunidades (agrupamentos). Em alguns casos é aceitável realizar um k-means nesse espaço para encontrar os &lt;em>clusters&lt;/em>.&lt;/li>
&lt;/ul>
&lt;p>O script abaixo gera uma visualização dos dois grafos usados nos exemplos anteriores: um obtido do SBM e outro do Erdos-Renyi.&lt;/p>
&lt;pre>&lt;code class="language-python">import numpy as np
pos_sbm = np.array([ v for v in nx.layout.spring_layout(g_sbm, iterations=1000).values()])
pos = np.array([ v for v in nx.layout.spring_layout(g, iterations=1000).values()])
fig, (a1, a2) = plt.subplots(1, 2)
a1.scatter(pos_sbm[:, 0], pos_sbm[:, 1], c=g_sbm_community_index, cmap='tab20')
a2.scatter(pos[:, 0], pos[:, 1], c=g_community_index, cmap='tab20')
for ax in (a1, a2):
ax.set_yticklabels([])
ax.set_xticklabels([])
a1.set_title('SBM')
a2.set_title('ER')
plt.show()
&lt;/code>&lt;/pre>
&lt;figure id="figure-visualização-via-force-directed-para-uma-amostra-de-um-sbm-e-outra-erdos-renyi-cores-representam-as-comunidades-identificadas-pelo-método-guloso-de-maximização-de-modularidade">
&lt;a data-fancybox="" href="/post/edge_graph_filtering/fd_sbm_and_er_hudae8c8a39de2754d2a986f6769de4dd6_25660_400x0_resize_lanczos_3.png" data-caption="Visualização via force-directed para uma amostra de um SBM e outra Erdos-Renyi. Cores representam as comunidades identificadas pelo método guloso de maximização de modularidade">
&lt;img data-src="/post/edge_graph_filtering/fd_sbm_and_er_hudae8c8a39de2754d2a986f6769de4dd6_25660_400x0_resize_lanczos_3.png" class="lazyload" alt="" width="400px" height="100%">
&lt;/a>
&lt;figcaption>
Visualização via force-directed para uma amostra de um SBM e outra Erdos-Renyi. Cores representam as comunidades identificadas pelo método guloso de maximização de modularidade
&lt;/figcaption>
&lt;/figure>
&lt;p>Note que o método de visualização mostrou um agrupamento de vértices para o SBM. Contudo, no caso do grafo aleatório (ER) só parece uma grande confusão. As cores representam as comunidades obtidas via maximização da modularidade. O que podemos tirar desse exemplo? Que você deve tomar cuidado quando falar que encontrou uma comunidade ou que existe uma &lt;em>“bolha”&lt;/em> na rede social que você encontrou. Outra coisa que isso nos mostra é que usar métodos diferentes é uma boa alternativa para evitar ser enganado por seus resultados.&lt;/p>
&lt;div class="alert alert-note">
&lt;div>
No caso de visualizações de grafos, especialmente de force-directed, talvez seja melhor você utilizar algum sistema de visualização iterativo e 3D. Visualizações em 2D obtidas pelo force-directed podem não ser de grande ajuda e ainda ficarem presas em alguma configuração não ótima.
&lt;/div>
&lt;/div>
&lt;div class="alert alert-warning">
&lt;div>
Tome cuidado ao interpretar um grafo usando apenas métodos de visualização como force-directed, force-atlas, etc. Lembre que temos a tendência a reconhecer padrões baseado em agrupamentos, contraste etc. A &lt;a href="#gestalt">Gestalt&lt;/a> também atua para nos enganar. Você pode estar sujeito a &lt;a href="https://en.wikipedia.org/wiki/Pareidolia">pareidolia&lt;/a>.
&lt;/div>
&lt;/div>
&lt;hr/>
&lt;p>O tema de comunidades merece alguns posts separados para cada caminho, pois é um assunto denso e com muitos métodos diferentes.&lt;/p>
&lt;h1 id="filtros">Filtros&lt;/h1>
&lt;h2 id="estrutural-threshold">Estrutural: threshold&lt;/h2>
&lt;p>O método de threshold é um método estrutural, isto é, um método de filtragem que depende apenas dos pesos e das arestas. Com certeza, é o método mais simples e mais rápido, embora o mais controverso. É aplicável somente se cada relação (aresta) possuir um número real associado. O método de threshold consiste em descartar qualquer aresta cuja o peso ultrapasse um dado valor.&lt;/p>
&lt;p>O método de threshold é muito utilizado em neurociência (com críticas) e para análise de dados em geral quando as arestas representam uma medida de correlação (Pearson) entre dois elementos. Como as medidas de correlações podem ser negativas é comum que o threshold seja aplicado no absoluto dos valores associados às arestas.&lt;/p>
&lt;p>Tome o seguinte grafo como exemplo:&lt;/p>
&lt;pre>&lt;code class="language-mermaid">graph LR;
A--&amp;gt;|-0.5|B;
B--&amp;gt;|0.4|C
C--&amp;gt;|2|A;
D--&amp;gt;|-1|C;
&lt;/code>&lt;/pre>
&lt;p>Ao realizar um threshold de $0.5$ iremos remover a relação $(B, C)$ e $(A, B)$. O grafo não é mais fortemente conectado.&lt;/p>
&lt;pre>&lt;code class="language-mermaid">graph LR;
C--&amp;gt;|2|A;
D--&amp;gt;|-1|C;
B;
&lt;/code>&lt;/pre>
&lt;p>É comum que após o threshold todas as arestas que sobraram sejam truncadas em $1$. Ficaríamos com algo assim no final:&lt;/p>
&lt;pre>&lt;code class="language-mermaid">graph LR;
C--&amp;gt;|1|A;
D--&amp;gt;|1|C;
B;
&lt;/code>&lt;/pre>
&lt;p>Uma das maiores limitações/perigo de se usar o método um &lt;em>naive threshold&lt;/em> é que em grafos que modelam situações do mundo real (seja ele direto ou não) a distribuição de pesos costuma seguir uma fat-tail e distorcida tal como essa aqui:&lt;/p>
&lt;figure id="figure-distribuição-de-probabilidade-dos-pesos-das-arestas-em-função-do-peso-note-que-poucas-arestas-tem-um-peso-relevante-fonte-extracting-the-multiscale-backbone-of-complex-weighted-networkshttpsarxivorgabs09042389">
&lt;a data-fancybox="" href="/post/edge_graph_filtering/fat_tail_hua90d0707a945e6e9d352ed2f3ab43782_45362_400x0_resize_lanczos_3.png" data-caption="Distribuição de probabilidade dos pesos das arestas em função do peso. Note que poucas arestas tem um peso relevante. Fonte: &amp;lt;em&amp;gt;&amp;lt;a href=&amp;#34;https://arxiv.org/abs/0904.2389&amp;#34;&amp;gt;Extracting the multiscale backbone of complex weighted networks&amp;lt;/a&amp;gt;&amp;lt;/em&amp;gt;">
&lt;img data-src="/post/edge_graph_filtering/fat_tail_hua90d0707a945e6e9d352ed2f3ab43782_45362_400x0_resize_lanczos_3.png" class="lazyload" alt="" width="400px" height="100%">
&lt;/a>
&lt;figcaption>
Distribuição de probabilidade dos pesos das arestas em função do peso. Note que poucas arestas tem um peso relevante. Fonte: &lt;em>&lt;a href="https://arxiv.org/abs/0904.2389">Extracting the multiscale backbone of complex weighted networks&lt;/a>&lt;/em>
&lt;/figcaption>
&lt;/figure>
&lt;p>Bom, o que acontece se você tentar passar um threshold no grafo que tem uma distribuição parecida com essa na imagem? Vai ser difícil. Qualquer valor um pouco maior criará um monte de componentes desconectados. Além do que, como você justificaria seu valor de threshold ? Não dá para falar um argumento dois desvios padrões a partir da média. Se fosse uma distribuição normal de pesos você poderia estar bem.&lt;/p>
&lt;p>O threshold tem outro problema, ele é local. Isto é, você poderia penalizar muito as arestas de uma comunidade e nada de outra. Para deixar isso mais claro veja o exemplo de grafo com pesos a seguir:&lt;/p>
&lt;div class="mermaid mermaidContainer">
graph LR;
*---|0.4|1;
1---|0.8|2;
3---|0.4|2;
1---|0.6|3;
1---|0.6|4;
4---|0.3|3;
4---|...|...;
1---|...|...;
*---|0.4|a;
a---|1|b;
a---|0.8|c;
a---|0.8|d;
c---|0.7|e;
b---|0.7|f;
d---|0.8|g;
g---|...|?_1;
f---|...|?_2;
e---|...|?_3;
b---|0.3|c;
c---|0.3|d;
&lt;/div>
&lt;p>Se aplicássemos um threshold em $0.5$ teríamos algo do tipo&lt;/p>
&lt;div class="mermaid mermaidContainer">
graph LR;
*;
1---2;
1---3;
1---4;
4---|...|...;
1---|...|...;
a---b;
a---c;
a---d;
c---e;
b---f;
d---g;
g---|...|?_1;
f---|...|?_2;
e---|...|?_3;
&lt;/div>
&lt;p>Produzindo 3 componentes no nosso grafo se alterássemos ligeiramente o threshold produziremos mais componentes ainda. Ele é muito sensível. Qual o problema disso? Se fossemos aplicar um algoritmo de detecção de comunidades teríamos que fazer isso para cada componente. Em uma rede social isso pode ser problemático porque já estaremos analisando “bolhas” isoladas. Então como proceder? Portanto, vocẽ pode até usar o threshold para encontrar as arestas que são a &lt;strong>sustentação&lt;/strong> para o grafo. &lt;em>A espinha dorsal do grafo, backbone&lt;/em>. Contudo, ele costuma falhar.&lt;/p>
&lt;h3 id="pontos-positivos">Pontos positivos&lt;/h3>
&lt;ul>
&lt;li>custo computacional baixo $O(n)$
&lt;ul>
&lt;li>apenas iterar e comparar os valores.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>paralelizável&lt;/li>
&lt;li>trivial de implementar&lt;/li>
&lt;li>apenas um parâmetro&lt;/li>
&lt;/ul>
&lt;h3 id="pontos-negativos">Pontos negativos&lt;/h3>
&lt;ul>
&lt;li>tendência de produzir muitas componentes desconectadas,&lt;/li>
&lt;li>parâmetro arbitrário,
&lt;ul>
&lt;li>cherry-picking.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>A remoção de uma aresta só depende do valor atribuído a ela. Isto é, local.&lt;/li>
&lt;/ul>
&lt;h4 id="considerações-finais">Considerações finais&lt;/h4>
&lt;p>Outros métodos estruturais como o &lt;em>high-salience network&lt;/em> tentam reduzir os problemas do threshold adicionando contribuições não locais. Isto é, uma aresta é mantida/removida dependendo também das outras arestas no grafo. Contudo, como o &lt;em>high-salience network&lt;/em> É um filtro definido pelos menores caminhos no grafo ele costuma ser adequado apenas para grafos que esse conceito de filtragem é útil, por exemplo grafos que modelam infraestrutura de transporte.&lt;/p>
&lt;h2 id="estatistico">Estatístico: quebrando a varinha, processo de Dirichlet&lt;/h2>
&lt;p>Métodos estatísticos têm uma abordagem mais generalista quando comparados aos estruturais. Pois métodos estatísticos não dependem de algum conceito direto como caminhos mínimos usados pelo &lt;em>high-salience network&lt;/em> para redes de infraestrutura.&lt;/p>
&lt;p>Um método estatístico muito usado para filtrar arestas faz uso do
&lt;a href="https://en.wikipedia.org/wiki/Dirichlet_process" target="_blank" rel="noopener">processo estocástico de Dirichlet&lt;/a>. Intuitivamente, podemos usar esse processo para modelar uma situação que temos uma varinha e vamos quebrando ela em $k$ pedaços e queremos descobrir a probabilidade de um pedaço de tamanho $p$ aparecer no processo, &lt;em>
&lt;a href="https://en.wikipedia.org/wiki/Dirichlet_process#The_stick-breaking_process" target="_blank" rel="noopener">stick-breaking process&lt;/a>&lt;/em>.&lt;/p>
&lt;div class="alert alert-note">
&lt;div>
O processo de Dirichlet foi redescoberto em 2009 com o nome de &lt;strong>filtro de disparidade&lt;/strong>. Embora os autores do filtro de disparidade não citem trabalhos prévios ou o próprio processo Dirichlet em si.
&lt;/div>
&lt;/div>
&lt;p>Certo, vamos tentar entender como usar esse processo para filtrar arestas.&lt;/p>
&lt;p>Começamos definindo os pesos efetivos para &lt;strong>cada vértice&lt;/strong> e aresta. Esse peso efetivo para uma aresta entre os vértices &lt;strong>A&lt;/strong> e &lt;strong>B&lt;/strong> é dado pela seguinte expressão:
$$
p_{AB} = \frac{Peso\ da\ aresta\ (A,B)}{Soma\ dos\ pesos\ de\ todas\ as\ arestas\ de\ A}
$$
$$
p_{AB}= \frac{w_{AB}}{\sum\limits_C w_{AC}}
$$&lt;/p>
&lt;p>Pegue o grafo a seguir com os pesos dados nas arestas&lt;/p>
&lt;pre>&lt;code class="language-mermaid">graph LR;
A---|1|B;
B---|1|C;
A---|2|C;
A---|4|D;
D---|1|C;
&lt;/code>&lt;/pre>
&lt;p>Calculando o peso efetivo para todas as arestas relacionadas ao vértice &lt;strong>A&lt;/strong>. É fácil ver que&lt;/p>
&lt;p>$p_{AB} =1/7$, $p_{AC}=2/7$, e $p_{AD}=4/7$ e claro que $\sum_B p_{AB}=1$.&lt;/p>
&lt;pre>&lt;code class="language-mermaid">graph LR;
A---|1/7|B;
B---C;
A---|2/7|C;
A---|4/7|D;
D---C;
&lt;/code>&lt;/pre>
&lt;p>Iremos decidir se removeremos alguma ou mais arestas de &lt;strong>A&lt;/strong>.&lt;/p>
&lt;p>Nossos pesos efetivos somam 1. A ideia do filtro é imaginar que os pesos efetivos são influências do vértice &lt;strong>A&lt;/strong> nos seus vizinhos. O modelo parte da hipótese que os pesos efetivos são distribuídos de forma uniforme entres os vizinhos de &lt;strong>A&lt;/strong>. Portanto, &lt;strong>podemos modelar a distribuição de pesos nas três arestas de A como um
&lt;a href="https://en.wikipedia.org/wiki/Dirichlet_process#The_stick-breaking_process" target="_blank" rel="noopener">stick-breaking process&lt;/a>&lt;/strong>. Desta maneira, podemos escolher remover as arestas cujo os pesos efetivos tenham uma probabilidade maior de ter vindo desse processo. Estamos mantendo os pesos efetivos dispares do processo!&lt;/p>
&lt;p>Ok, como fazer isso? Como os pesos efetivos podem ter qualquer valor entre 0 e 1 precisamos de uma densidade de probabilidade. O stick-breaking deve modelar um processo de quebra de um graveto em $k$ pedacinhos. No nosso caso, os $k$ pedacinhos são as $3$ arestas de &lt;strong>A&lt;/strong>. Então a densidade de probabilidade precisa ter $k$ como parâmetro.&lt;/p>
&lt;figure >
&lt;a data-fancybox="" href="/post/edge_graph_filtering/dirichet_disparity_hu96ca0e2ae94d6035ae4226a77316451b_94065_0x400_resize_q90_lanczos.jpeg" >
&lt;img data-src="/post/edge_graph_filtering/dirichet_disparity_hu96ca0e2ae94d6035ae4226a77316451b_94065_0x400_resize_q90_lanczos.jpeg" class="lazyload" alt="" width="100%" height="200px">
&lt;/a>
&lt;/figure>
&lt;p>Demonstrar a densidade de probabilidade desse processo de quebra é trabalhoso, mas a expressão final é bem simples. São funções decrescentes que caem mais rápido quanto maior o $k$. O que faz sentido, já que quanto mais pedacinhos quebrarmos menos provável é achar um pedacinho com um tamanho próximo do original do graveto.&lt;/p>
&lt;p>A filtragem via stick-breaking (disparidade) baseia-se então em remover somente as arestas cujo os pesos efetivos são mais prováveis (um p-teste) dado um fator $\alpha$ , um número real entre 0 e 1. Isto é, a aresta AB é mantida se a inequação abaixo é verificada:
$$
(1-p_{AB})^{k_A-1} &amp;lt; \alpha
$$&lt;/p>
&lt;p>A tabela abaixo mostra o que acontece com as arestas de $A$ a medida que o parâmetro $\alpha$ é alterado&lt;/p>
&lt;table>
&lt;thead>
&lt;tr>
&lt;th>Aresta/$\alpha$&lt;/th>
&lt;th>0. 19&lt;/th>
&lt;th>0.52&lt;/th>
&lt;th>0.74&lt;/th>
&lt;/tr>
&lt;/thead>
&lt;tbody>
&lt;tr>
&lt;td>A,B&lt;/td>
&lt;td>Removida&lt;/td>
&lt;td>Removida&lt;/td>
&lt;td>Mantida&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>A,C&lt;/td>
&lt;td>Removida&lt;/td>
&lt;td>Mantida&lt;/td>
&lt;td>Mantida&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>A,D&lt;/td>
&lt;td>Mantida&lt;/td>
&lt;td>Mantida&lt;/td>
&lt;td>Mantida&lt;/td>
&lt;/tr>
&lt;/tbody>
&lt;/table>
&lt;p>OK, parece muito bom. Mas veja o seguinte: ressaltei várias vezes &lt;strong>A&lt;/strong> no texto. Isto por que o filtro é definido por vértice. Bom, e o que acontece se olharmos a partir do vértice &lt;strong>B&lt;/strong>?&lt;/p>
&lt;p>Partindo de $B$ teremos $p_{BC}=1/2$ e $p_{BA}=1/2$!&lt;/p>
&lt;pre>&lt;code class="language-mermaid">graph LR;
A---|1/2|B;
B---|1/2|C;
A---C;
A---D;
D---C;
&lt;/code>&lt;/pre>
&lt;p>Então $(1-p_{BA})^{k_b-1} = (1-1/2)^1 = 1/2$. Ok , então se escolhermos $\alpha$ igual 0.52 a tabela anterior (para &lt;strong>A&lt;/strong>) diz para remover a aresta (A,B) enquanto por &lt;strong>B&lt;/strong> o método nos diz que é para manter. Isso causa uma ambiguidade em como decidir se vamos manter ou não as arestas. Você pode escolher manter se os dois concordam ou manter se apenas um passar no teste. &lt;strong>Essa ambiguidade não aparece no caso de grafos direcionados!&lt;/strong>&lt;/p>
&lt;h3 id="pontos-positivos-1">Pontos positivos&lt;/h3>
&lt;ul>
&lt;li>é estabelecido dentro de uma formalização matemática robusta&lt;/li>
&lt;li>tenta evitar que o grafo se desconecte&lt;/li>
&lt;li>custo computacional baixo&lt;/li>
&lt;/ul>
&lt;h3 id="pontos-negativos-1">Pontos negativos&lt;/h3>
&lt;ul>
&lt;li>
&lt;p>podemos argumentar que o teste de hipótese é arbitrário&lt;/p>
&lt;/li>
&lt;li>
&lt;p>parâmetro $\alpha$ precisa ser escolhido, embora mais robusto do que apenas o parâmetro de threshold&lt;/p>
&lt;/li>
&lt;/ul>
&lt;!--
# Extras:
O próximo exemplo é sobre
## Matrizes e espectro
Pegue o seguinte grafo
```mermaid
graph LR;
A---|1|B;
B---|1/2|C;
C---|2|A;
```
Podemos associar com esse grafo uma matriz $3\times 3$ onde as entradas da matriz representam os valores associados às arestas. Essa matriz é conhecida como matriz de pesos,
$$
W=\begin{pmatrix}
\- \&amp; A \&amp; B \&amp; C\\\
A \&amp; 0 \&amp; 1 \&amp; 2\\\
B \&amp; 1 \&amp; 0 \&amp; 1/2\\\
C \&amp; 2 \&amp; 1/2 \&amp; 0
\end{pmatrix}
$$
$$
v=\begin{pmatrix}
x\\\
y\\\
z
\end{pmatrix}
$$
```mermaid
graph LR;
A[y+2z]---|1|B;
B[x+1/2z]---|0.5|C;
C[2x+0.5y]---|2|A;
```
&lt;div class="alert alert-note">
&lt;div>
A matriz pesos de um grafo pode ser pensada como uma generalização para combinar valores numéricos.
&lt;/div>
&lt;/div>
[Variações do teorema do limite central para matrizes aleatórias](/post/random_matrix_portfolio)
## Filtro Espectral (amostragem)
$(1-\epsilon)v^TLv \le v^TLv \le (1+\epsilon)v^T Lv$
### Pontos positivos
- é estabelecido dentro de uma formalização matemática robusta
- dada as restrições garante preservar as propriedades estabelecidas
- muito utilizado para processamento de sinais em grafos
### Pontos negativos
- custo computacional geralmente elevado
- alguns métodos espectrais tem custo $O(n^2)$ para cada iteração
- muitas maneiras distintas de fazer para cada tipo de grafo e objetivo.
- Se o grafo for direcionado ou não, se é livre de escala ou não, se tem um certo padrão específico de conexões, etc.
##
# Conclusão
--></description></item><item><title>Variações do teorema central do limite para matrizes aleatórias.</title><link>/post/random_matrix_portfolio/</link><pubDate>Mon, 06 Dec 2021 00:00:00 +0000</pubDate><guid>/post/random_matrix_portfolio/</guid><description>&lt;blockquote>
&lt;p>Disponível em
&lt;a href="https://opencodecom.net/post/2021-12-14-variacoes-do-teorema-central-do-limite-para-matrizes-aleatorias-de-nucleos-atomicos-a-filtragem-de-matrizes-de-correlaca/" target="_blank" rel="noopener">https://opencodecom.net/&lt;/a>&lt;/p>
&lt;/blockquote>
&lt;p>No célebre trabalho “&lt;em>Can One Hear the Shape of a Drum?&lt;/em>”[1] Kack questiona se conhecendo o espectro (&lt;em>som&lt;/em>) de um certo operador que define as oscilações de uma membrana (&lt;em>tambor&lt;/em>) seria possível identificar o formato de tal membrana de maneira unívoca. Discutiremos aqui como é possível ouvir matrizes de correlação usando seu espectro e como podemos remover o ruído desse som usando resultados da teoria de matrizes aleatórias. Veremos como essa filtragem pode aprimorar algoritmos de construção de carteiras de investimentos.&lt;/p>
&lt;blockquote>
&lt;p>Minhas motivações para escrever esse texto foram o movimento
&lt;a href="https://twitter.com/sseraphini/status/1458169250326142978" target="_blank" rel="noopener">Learn In Public-Sibelius Seraphini&lt;/a> e o Nobel de Física de 2021. Um dos temas de Giorgio Parisi é o estudo de matrizes aleatórias
&lt;a href="https://www.nobelprize.org/uploads/2021/10/sciback_fy_en_21.pdf" target="_blank" rel="noopener">www.nobelprize.org 2021&lt;/a>.&lt;/p>
&lt;/blockquote>
&lt;p>..&lt;/p>
&lt;blockquote>
&lt;p>Jupyter notebook disponível
&lt;a href="https://github.com/devmessias/devmessias.github.io/blob/master/content/post/random_matrix_portfolio/index.ipynb" target="_blank" rel="noopener">aqui&lt;/a>&lt;/p>
&lt;/blockquote>
&lt;h1 id="1-introdução-teorema-central-do-limite">1-Introdução: teorema central do limite&lt;/h1>
&lt;p>O teorema central do limite está no coração da análise estatística. Em poucas palavras o mesmo estabelece o seguinte.&lt;/p>
&lt;blockquote>
&lt;p>Suponha uma amostra $A = (x_1, x_2, \dots, x_n)$ de uma variável aleatória com média $\mu$ e variância $\sigma^2$ finita. Se a amostragem é $i.i.d.$ o teorema central do limite estabelece que a
distribuição de probababilidade da média amostral converge
para uma distribuição normal com variância $\sigma^2/n$ e média $\mu$ a medida que $n$ aumenta.&lt;/p>
&lt;/blockquote>
&lt;p>Note que eu não disse nada a respeito de como tal amostra foi gerada; em nenhum momento citei distribuição de Bernoulli, Gauss, Poisson, etc. Desta maneira podemos dizer que tal convergência é uma propriedade &lt;strong>universal&lt;/strong> de amostras aleatórias $i.i.d.$. Essa universalidade é poderosa, pois garante que é possível estimar a média e variância de uma população através de um conjunto de amostragens.&lt;/p>
&lt;p>Não é difícil fazer um experimento computacional onde a implicação desse teorema apareça&lt;/p>
&lt;pre>&lt;code class="language-python">import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import warnings
from matplotlib import style
warnings.filterwarnings('ignore')
style.use('seaborn-white')
np.random.seed(22)
&lt;/code>&lt;/pre>
&lt;p>Usaremos uma amostragem de uma distribuição exponencial com média $\mu = 4$. Tal distribuição tem uma variância dada por $1/\mu^2$. Faremos $10000$ experimentos com amostras de tamanho $500$. Posteriormente calcularemos a media de cada experimento, &lt;code>mean_by_exp&lt;/code>&lt;/p>
&lt;pre>&lt;code class="language-python">rate = 0.25
mu = 1/rate
sample_size=500
exponential_sample = np.random.exponential(mu, size=(sample_size, 30000))
mean_by_exp = exponential_sample.mean(axis=0)
&lt;/code>&lt;/pre>
&lt;p>Agora basta plotar o histograma em comparação com a distribuição normal dada pelo teorema central do limite&lt;/p>
&lt;pre>&lt;code class="language-python">sns.distplot(mean_by_exp, norm_hist=True, label='sample')
x = np.linspace(2.5, 5.5, 100)
var = mu**2/(sample_size)
y = np.exp(-(x-mu)**2/(2*var))/np.sqrt(2*np.pi*var)
plt.plot(x, y, label=r'$N(\mu, \sigma)$', c='tomato')
plt.legend()
plt.xlim(3., 5)
plt.savefig('exponential_distribution.png', facecolor='w')
plt.close()
&lt;/code>&lt;/pre>
&lt;p>&lt;img src="exponential_distribution.png" alt="&amp;ldquo;exponential_distribution.png&amp;rdquo;">&lt;/p>
&lt;p>Note na figura acima que o plot para a função $\frac{e^{-\frac{(x-\mu)^2}{2\sigma^2}}}{\sqrt(2\pi\sigma^2)}$ e o histograma coincidem. Você pode testar essa coincidência com outras distribuições, o mesmo comportamento se repetira. É isso que quero dizer com &lt;strong>universalidade&lt;/strong>.&lt;/p>
&lt;p>Um questionamento válido é que estamos tratando apenas de uma variável aleatória e sua amostragem. Mas no mundo real existem outras estruturas mais intricadas. Por exemplo
pegue um conjunto de variáveis aleatórias
$\mathcal C=(X_{1 1}, X_{1 2}, \cdots, X_{N N})$, suponha que exista uma certa &lt;strong>simetria&lt;/strong> nesse conjunto, uma possibilidade é $X_{i j} = X_{j i}$.
Não é difícil imaginar situações onde tal conjunto apareça.&lt;/p>
&lt;p>Podemos armazenar uma realização de $\mathcal C$ em uma matriz que nada mais é que um grafo completo com pesos. Ao estudar essas matrizes oriundas desse tipo de amostragem entramos em um novo campo da matemática, o campo das matrizes aleatórias.
Nesse campo de estudos uma amostragem não retorna um número, mas sim uma matriz.&lt;/p>
&lt;p>A função &lt;code>normalRMT&lt;/code> apresentada abaixo é um gerador de matrizes aleatórias conhecidas como Gaussianas ortogonais.&lt;/p>
&lt;pre>&lt;code class="language-python">def normalRMT(n=100):
&amp;quot;&amp;quot;&amp;quot;Generate a random matrix with normal distribution entries
Args:
n : (int) number of rows and columns
Returns:
m : (numpy.ndarray) random matrix
&amp;quot;&amp;quot;&amp;quot;
std = 1/np.sqrt(2)
m = np.random.normal(size=(n,n), scale=std)
m = (m+m.T)
m /= np.sqrt(n)
return m
np.set_printoptions(precision=3)
print(f'{normalRMT(3)},\n\n{normalRMT(3)}')
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>[[-1.441e+00 -2.585e-01 -1.349e-01]
[-2.585e-01 -2.304e-01 1.166e-03]
[-1.349e-01 1.166e-03 -1.272e+00]],
[[-0.742 0.607 -0.34 ]
[ 0.607 0.678 0.277]
[-0.34 0.277 -0.127]]
&lt;/code>&lt;/pre>
&lt;p>Sabemos que quando estamos trantando de variáveis aleatórias o teorema central do limite é importantíssimo. O que você pode se perguntar agora é: &lt;strong>Existe um análogo para o teorema central do limite para matrizes aleatórias?&lt;/strong>&lt;/p>
&lt;h1 id="2-núcleos-atômicos-gás-de-números-primos-e-universalidade">2-Núcleos atômicos, gás de números primos e universalidade&lt;/h1>
&lt;p>Para o bem e para o mal o conhecimento da física atômica foi um dos temas mais importantes desenvolvidos pela humanidade. Portanto, não é de se estranhar que após o ano de 1930 iniciou-se uma grande corrida para compreender núcleos atômicos pesados e a física de nêutrons [13].&lt;/p>
&lt;p>Para compreender essa nova física de nêutrons era necessário conhecer a organização do espectro de ressonância dos núcleos pesados (esse espectro nada mais é que os autovalores de um operador muito especial). Uma maneira de se fazer isso é do jeito que muitas das coisas são estudadas na física: pegando se uma coisa e jogando na direção da coisa a ser estudada. Essa metodologia experimental torna possível amostrar alguns valores possíveis para o espectro. Contudo, acredito que não preciso argumentar que fazer isso naquela época era extremamente difícil e caro. Poucos centros conseguiam realizar alguns experimentos e ainda com uma resolução muito baixa para obter resultados suficientes para uma compreensão adequada dos núcleos. Era preciso uma saída mais barata e ela foi encontrada. Tal saída dependeu apenas de física-matemática e maços de papel.&lt;/p>
&lt;p>&lt;img src="frog.png" alt="">&lt;/p>
&lt;p>Dentre os pioneiros que decidiram atacar o problema de núcleos pesados usando matemática temos Eugene Paul Wigner (Nobel de 1963). A grande sacada de Wigner foi perceber que o fato das interações nucleares serem tão complicadas e a infinitude de graus de liberdade seria possível tentar compreender essas interações como uma amostragem sujeita a certas condições de simetria.[10 , 11]&lt;/p>
&lt;p>&lt;img src="wigner.png" alt="wigner.png">&lt;/p>
&lt;p>Aqui com simetria queremos dizer que as matrizes envolvidas possuem certas restrições tais como&lt;/p>
&lt;pre>&lt;code class="language-python">np.assert_equal(A, A.T)
&lt;/code>&lt;/pre>
&lt;p>Na próxima seção veremos qual o impacto dessas restrições na distribuição de autovalores das matrizes envolvidas.&lt;/p>
&lt;h2 id="2-a-universalidade-e-lei-do---semicírculo">2-a) Universalidade e lei do semicírculo&lt;/h2>
&lt;p>A função &lt;code>normalRMT&lt;/code> gera uma matriz simétrica onde as entradas são extraídas de uma distribuição normal. A função &lt;code>laplaceRMT&lt;/code> gera também uma matriz simétrica, contudo as entradas são amostras de uma distribuição de Laplace.&lt;/p>
&lt;pre>&lt;code class="language-python">
def laplaceRMT(n=100):
&amp;quot;&amp;quot;&amp;quot;Generate a random matrix with Laplace distribution
Args:
n : (int) size of the matrix
Returns:
m : (numpy.ndarray) random matrix with Laplace distribution
&amp;quot;&amp;quot;&amp;quot;
# we know that the variance of the laplace distribution is 2*scale**2
scale = 1/np.sqrt(2)
m = np.zeros((n,n))
values = np.random.laplace(size=n*(n-1)//2, scale=scale)
m[np.triu_indices_from(m, k=1)] = values
# copy the upper diagonal to the lower diagonal
m[np.tril_indices_from(m, k=-1)] = values
np.fill_diagonal(m, np.random.laplace(size=n, scale=scale))
m = m/np.sqrt(n)
return m
&lt;/code>&lt;/pre>
&lt;p>As propriedades &lt;strong>universais&lt;/strong> que iremos explorar aqui estão ligadas aos autovalores das matrizes que foram amostradas. Como nossas matrizes são simétricas esses autovalores são todos reais.&lt;/p>
&lt;p>Como cada matriz é diferente os autovalores também serão, eles também são variáveis aleatórias.&lt;/p>
&lt;pre>&lt;code class="language-python">vals_laplace = np.array([
np.linalg.eigh(laplaceRMT(n=100))[0]
for i in range(100)
])
vals_normal = np.array([
np.linalg.eigh(normalRMT(n=100))[0]
for i in range(100)
])
&lt;/code>&lt;/pre>
&lt;p>Na decáda de 50 não havia poder computacional
suficiente para realizar investigações númericas, mas você pode facilmente investigar como os autovalores se distribuem usando seu computador e gerando os histogramas&lt;/p>
&lt;pre>&lt;code class="language-python">t = 1
x = np.linspace(-2*t, 2*t, 100)
y = np.zeros_like(x)
x0 = x[4*t-x*2&amp;gt;0]
y[4*t-x*2&amp;gt;0] = np.sqrt(4*t-x0**2)/(2*np.pi*t)
plt.figure(facecolor='white')
plt.hist(vals_laplace.flatten(), bins=50,
hatch ='|',
density=True, label='laplace', alpha=.2)
plt.hist(vals_normal.flatten(), bins=50,
hatch ='o',
density=True, label='normal', alpha=.2)
#sns.distplot(vals_laplace, norm_hist=True, label='Laplace')
#sns.distplot(vals_normal, norm_hist=True, label='Normal')
#sns.distplot(vals2, norm_hist=True, label='sample2')
plt.plot(x, y, label='analytical')
plt.xlabel(r'$\lambda$')
plt.ylabel(r'$\rho(\lambda)$')
plt.legend()
plt.savefig('RMT_distribution.png', facecolor='w')
plt.close()
&lt;/code>&lt;/pre>
&lt;p>&lt;img src="RMT_distribution.png" alt="">&lt;/p>
&lt;p>Veja na figura acima que a distribuição de autovalores de matrizes simétricas relacionadas com a distribuição normal e de Laplace coincidem. O que estamos vendo aqui é uma propriedade &lt;strong>universal&lt;/strong>! Espero que você acredite em mim, mas dado que você tenha uma matriz aleatória simétrica, quadrada e se as entradas são $i.i.d.$ a distribuição de autovalores seguem o que é conhecido como lei de semicírculo de Wigner. Se a média e variância das entradas da matriz são $0$ e $1$ respectivamente, então tal lei tem a seguinte expressão para a distribuição de probabilidade dos autovalores
$$
\rho(\lambda) = \begin{cases}
\frac{\sqrt{4-\lambda^2}}{(2\pi)} \textrm{ se } 4-\lambda^2 \leq 0\newline
0 \textrm{ caso contrário.}
\end{cases}
$$&lt;/p>
&lt;p>Se trocarmos as simetrias, restrições ou formato (&lt;code>array.shape[0]!=array.shape[1]&lt;/code>) das matrizes podemos encontrar variações da distribuição apresentada acima. Exemplo se a matriz é complexa mas Hermitiana, ou se é &amp;ldquo;retangular&amp;rdquo; e real tal como algums matrizes que são usadas para otimizar carteiras de investimento. A próxima seção mostrará um caso com outro formato para universalidade.&lt;/p>
&lt;h2 id="2-b-repulsão-entre-números-primos">2-b) Repulsão entre números primos&lt;/h2>
&lt;p>Inciamos nosso texto falando sobre como a teoria de matrizes aleatórias floreceu com os estudos estatísticos de núcleos atômicos pesados, especificamente nos trabalhos de Wigner. Embora tenha essa origem, muitas vezes ferramentas matemáticas desenvolvidas apenas por motivações práticas alcançam outros ramos da matemática. Brevemente discutirei aqui alguns pontos e relações com uma das conjecturas mais famosas da matemática: a hipótese de Riemann.&lt;/p>
&lt;p>Qualquer pessoa com alguma curiosidade sobre matemática já ouviu falar sobre a hipótese de Riemann. Essa hipótese estabele uma relação entre os zeros da função zeta de Riemann e a distribuição de números primos. Dada sua importância os maiores ciêntistas do século XX se debruçaram sobre ela almejando a imortalidade. Um desses ciêntistas foi Hugh Montgomery[4].&lt;/p>
&lt;p>Por volta de 1970 Montgomery notou que os zeros da função zeta tinham uma certa propriedade cuirosa, pareciam repelir uns aos outros. Uma expressão foi obtidada, que é a seguinte&lt;/p>
&lt;p>$$
1 - \left( \frac{\sin (\pi u)}{\pi u}\right)^2 + \delta(u)
$$&lt;/p>
&lt;p>Não se preocupe em entender a expressão acima, ela está aqui apenas for motivos estéticos.
O que importa é que ela é simples, tão simples que quando Freeman Dyson - um dos gigantes da física-matemática - colocou os olhos sobre tal equação ele notou imediatamente que tal equação era idêntica a obtida no contexto de matrizes aleatórias Hermitianas (uma matriz é hermitiana se ela é igual a sua transporta conjugada) utilizadas para compreender o comportamento de núcleos de átomos pesados, tais como urânio. A imagem abaixo é uma carta escrita por Dyson.&lt;/p>
&lt;p>&lt;img src="carta.png" alt="">&lt;/p>
&lt;p>As conexão entre um ferramental desenvolvido para estudar núcleos atômicos e números primos era realmente inesperada e talvez seja um dos caminhos para a prova da hipotese de Riemann[5, 2]. Contudo deixemos a história de lado, e voltemos ao ponto principal que é te dar outro exemplo de universalidade.&lt;/p>
&lt;p>Lembra que Montgomery disse que parecia haver uma repulsão entre os zeros da função Zeta? O que seria esse conceito de repulsão em matrizes aleatórias? Vamos checar numericamente&lt;/p>
&lt;p>Voltaremos a usar nossas matrizes aleatórias geradas por distribuições Gaussianas e Laplacianas. Usando o mesmo conjunto de autovalores que obtivemos anteriormente iremos calular o espaçamento entre cada par de autovalores para cada realização de uma matriz aleatória. É bem fácil, basta chamar a função &lt;code>diff&lt;/code> do numpy&lt;/p>
&lt;pre>&lt;code class="language-python">diff_laplace = np.diff(vals_laplace, axis=1)
diff_normal = np.diff(vals_normal, axis=1)
&lt;/code>&lt;/pre>
&lt;p>Agora o que faremos é estimar a densidade de probabilidade usnado KDE. Mas antes disso aqui vai uma dica:&lt;/p>
&lt;blockquote>
&lt;p>&lt;strong>Evite o KDE do sklearn no seu dia a dia, a implementação é lenta e não flexivél. Difícilmente você conseguirá bons resultados com milhões de pontos. Aqui vou usar uma implementação de KDE mais eficiente você pode instalar ela execuntando o comando abaixo&lt;/strong>&lt;/p>
&lt;/blockquote>
&lt;pre>&lt;code class="language-python">!pip install KDEpy
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">from KDEpy import FFTKDE
estimator_normal = FFTKDE( bw='silverman').fit(diff_normal.flatten())
x_normal, probs_normal = estimator_normal.evaluate(100)
mu_normal = np.mean(diff_normal, axis=1).mean()
estimator_laplace = FFTKDE( bw='silverman').fit(diff_laplace.flatten())
x_laplace, probs_laplace = estimator_laplace.evaluate(100)
mu_laplace = np.mean(diff_laplace, axis=1).mean()
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">goe_law = lambda x: np.pi*x*np.exp(-np.pi*x**2/4)/2
spacings = np.linspace(0, 4, 100)
p_s = goe_law(spacings)
plt.plot(spacings, p_s, label=r'GOE analítico', c='orange', linestyle='--')
plt.plot(
x_normal/mu_normal,
probs_normal*mu_normal,
linestyle=':',
linewidth=2,
zorder=1,
label='normal', c='black')
plt.plot(x_laplace/mu_laplace, probs_laplace*mu_laplace, zorder=2,
linestyle='--', label='laplace', c='tomato')
plt.legend()
plt.savefig('RMT_diff_distribution.png', facecolor='w')
plt.close()
&lt;/code>&lt;/pre>
&lt;p>&lt;img src="RMT_diff_distribution.png" alt="">&lt;/p>
&lt;p>O que as distribuições acima dizem é que dado sua matriz ser $i.i.d.$ quadrada e simétrica então a probabilidade que você encontre dois autovalores iguais é $0$ (zero). Além do mais, existe um ponto de máximo global em relação a distribuição de espaçamentos. Esse comportamento que balanceia repulsão e atração dos autovalores lembra o comportamento de partículas em um fluído. Não é de espantar que o método matemático desenvolvido por Wigner para compreender tais matrizes foi denominado Gás de Coloumb[2].&lt;/p>
&lt;p>Agora que você tem pelo menos uma ideia do que seria essa repulsão para o caso que já abordamos (matrizes simétricas quadradas) voltemos ao problema dos números primos.&lt;/p>
&lt;p>O comando a seguir baixa os primeiros 100k zeros da função zeta&lt;/p>
&lt;pre>&lt;code class="language-python">!wget http://www.dtc.umn.edu/~odlyzko/zeta_tables/zeros1
&lt;/code>&lt;/pre>
&lt;p>Um pequeno preprocessamento dos dados:&lt;/p>
&lt;pre>&lt;code class="language-python">zeros = []
with open('zeros1', 'r') as f:
for line in f.readlines():
# remove all spaces in the line and convert it to a float
zeros.append(float(line.replace(' ', '')))
zeta_zeros = np.array(zeros)
&lt;/code>&lt;/pre>
&lt;p>Iremos calcular os espaçamentos entre os zeros, a média de tais espaçamento e executar um KDE&lt;/p>
&lt;pre>&lt;code class="language-python">from KDEpy import FFTKDE
diff_zeta = np.diff(zeta_zeros[10000:])
m = np.mean(diff_zeta)
estimator = FFTKDE( bw='silverman').fit(diff_zeta)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">x, probs = estimator.evaluate(100)
p = np.pi
goe_law = lambda x: p*x*np.exp(-p*x**2/4)/2
def gue(xs):
arg = -4/np.pi*np.power(xs,2)
vals = 32/np.pi**2*xs**2*np.exp(arg)
return vals
spacings = np.linspace(0, 4, 100)
p_s = gue(spacings)
p_s2 = goe_law(spacings)
plt.plot(x/m, probs*m, label='zeros zeta', linestyle='--')
plt.plot(spacings, p_s, label=r'GUE analítico', c='blue', linestyle='-.')
plt.plot(spacings, p_s2, label=r'GOE analitico', c='orange', linestyle='-.')
plt.xlim(-0.1, 4)
plt.legend()
plt.savefig('zeta.png', facecolor='w')
plt.close()
&lt;/code>&lt;/pre>
&lt;p>&lt;img src="zeta.png" alt="">&lt;/p>
&lt;p>Veja que a propriedade de repulsão apareceu novamente. Note que dentro do plot eu coloquei uma outra curva &lt;code>GOE analítico&lt;/code>, essa curva é aquela que melhor descreve a distribuição de espaçamentos quando suas matrizes aleatórias são simétricas. Isso é uma lição importante aqui e resalta o que eu já disse anteriormente. Não temos apenas &lt;em>&amp;ldquo;um limite central para matrizes aleatórias&lt;/em>&amp;rdquo;, mas todo um &lt;strong>zoológico que mudará dependendo do tipo do seu problema.&lt;/strong>.&lt;/p>
&lt;h1 id="3-usando-rmt-para-encontrar-e-filtrar-ruídos-em-matrizes">3-Usando &lt;em>RMT&lt;/em> para encontrar e filtrar ruídos em matrizes&lt;/h1>
&lt;p>Na seção 1 relembramos o resultado do teorema central do limite. Na seção 2 foi mostrado que devemos ter em mente as simetrias e restrições do nosso problema para analisar qual regra de universalidade é respeitada. Isto é: a depender da simetria e restrições das nossas matrizes temos um outro &amp;ldquo;&lt;em>timbre de universalidade&lt;/em>&amp;rdquo;.&lt;/p>
&lt;p>Um exemplo de outro timbre surge no espectro de matrizes de correlação; matrizes que são comumente utilizadas para análise de carteiras de investimento. Tais matrizes tem &lt;strong>pelo menos a seguinte estrutura&lt;/strong>:&lt;/p>
&lt;p>$$
\mathbf C = \mathbf X \mathbf X^T
$$
onde $\mathbf X$ é uma matriz real $N\times M$ e $M&amp;gt;N$.&lt;/p>
&lt;p>O código abaixo permite explorar em um exemplo o espectro de matrizes aleatórias $N\neq M$ com entradas dadas pela distribuição normal.&lt;/p>
&lt;pre>&lt;code class="language-python">def get_marchenko_bounds(Q, sigma=1):
&amp;quot;&amp;quot;&amp;quot;Computes the Marchenko bounds for a given Q and sigma.
Args:
Q : (float) The Q-value.
sigma : (float) The std value.
Returns:
(float, float): The lower and upper bounds for the eigenvalues.
&amp;quot;&amp;quot;&amp;quot;
QiSqrt = np.sqrt(1/Q)
lp = np.power(sigma*(1 + QiSqrt),2)
lm = np.power(sigma*(1 - QiSqrt),2)
return lp, lm
def marchenko_pastur(l, Q, sigma=1):
&amp;quot;&amp;quot;&amp;quot;Return the probability of a Marchenko-Pastur distribution for
a given Q , sigma and eigenvalue.
Args:
l : (float) The eigenvalue.
Q : (float) The Q-value.
sigma : (float) The std value.
Returns:
(float): The probability
&amp;quot;&amp;quot;&amp;quot;
lp, lm = get_marchenko_bounds(Q, sigma)
# outside the interval [lm, lp]
if l &amp;gt; lp or l &amp;lt; lm:
return 0
return (Q/(2*np.pi*sigma*sigma*l))*np.sqrt((lp-l)*(l-lm))
def plot_marchenko_pastur(ax, eigen_values, Q, sigma=1, bins=100, just_the_bulk=False):
&amp;quot;&amp;quot;&amp;quot;Plots the Marchenko-Pastur distribution for a given Q and sigma
Args:
ax : (matplotlib.axes) The axes to plot on.
eigen_values : (np.array) The eigenvalues.
Q : (float) : The Q-value.
sigma : (float) std
bins : (int) The number of bins to use.
just_the_bulk : (bool) If True, only the eigenvalues inside of
the Marchenko-Pastur bounds are plotted.
&amp;quot;&amp;quot;&amp;quot;
l_max, l_min = get_marchenko_bounds(Q, sigma)
eigenvalues_points = np.linspace(l_min, l_max, 100)
pdf = np.vectorize(lambda x : marchenko_pastur(x, Q, sigma))(eigenvalues_points)
if just_the_bulk:
eigen_values = eigen_values[ (eigen_values &amp;lt; l_max)]
ax.plot(eigenvalues_points, pdf, color = 'r', label='Marchenko-Pastur')
ax.hist(eigen_values, label='sample', bins=bins , density=True)
ax.set_xlabel(r&amp;quot;$\lambda$&amp;quot;)
ax.set_ylabel(r&amp;quot;$\rho$&amp;quot;)
ax.legend()
N = 1000
T = 4000
Q = T/N
X = np.random.normal(0,1,size=(N,T))
cor = np.corrcoef(X)
vals = np.linalg.eigh(cor)[0]
fig, ax = plt.subplots(1,1)
plot_marchenko_pastur(ax, vals, Q, sigma=1, bins=100)
plt.legend()
plt.savefig('Marchenko_Pastur.png', facecolor='w')
plt.close()
&lt;/code>&lt;/pre>
&lt;p>&lt;img src="Marchenko_Pastur.png" alt="">&lt;/p>
&lt;p>A função em vermelho na figura acima é a &lt;strong>universalidade&lt;/strong> que aparece em matrizes com a restrição $N\times M$ e entradas $i.i.d.$ e média $0$. Tal &lt;strong>universalidade&lt;/strong> tem como formato a distribuição de Marchenko-Pastur que é dada por&lt;/p>
&lt;p>$$
\rho (\lambda) = \frac{Q}{2\pi \sigma^2}\frac{\sqrt{(\lambda_{\max} - \lambda)(\lambda - \lambda_{\min})}}{\lambda}
$$
onde
$$
\lambda_{\max,\min} = \sigma^2(1 \pm \sqrt{\frac{1}{Q}})^2.
$$&lt;/p>
&lt;p>Note os parâmetros como $Q$ e $\sigma$. Tais parâmetros precisam ser ajustados para obter um melhor fit com dados reais.&lt;/p>
&lt;p>Agora iremos para um caso real. Vamos usar dados obtidos via Yahoo Finance com a biblioteca &lt;code>yfinance&lt;/code> para consturir uma matriz de correlação com dados de ativos financeiros&lt;/p>
&lt;pre>&lt;code class="language-python"># você precisa desse pacote para baixar os dados
!pip install yfinance
&lt;/code>&lt;/pre>
&lt;p>Isso aqui é um post bem informal, então peguei peguei uma lista aleatória com alguns tickers que encontrei na internet&lt;/p>
&lt;pre>&lt;code class="language-python">
!wget https://raw.githubusercontent.com/shilewenuw/get_all_tickers/master/get_all_tickers/tickers.csv
&lt;/code>&lt;/pre>
&lt;p>selecionei apenas 500 para evitar que o processo de download seja muito demorado&lt;/p>
&lt;pre>&lt;code class="language-python">tickers = np.loadtxt('tickers.csv', dtype=str, delimiter=',').tolist()
tickers = np.random.choice(tickers, size=500, replace=False).tolist()
&lt;/code>&lt;/pre>
&lt;p>vamos baixar agora os dados em um periódo específico&lt;/p>
&lt;pre>&lt;code class="language-python">
import yfinance as yf
df = yf.download (tickers,
start=&amp;quot;2017-01-01&amp;quot;, end=&amp;quot;2019-10-01&amp;quot;,
interval = &amp;quot;1d&amp;quot;,
group_by = 'ticker',
progress = True)
&lt;/code>&lt;/pre>
&lt;p>o &lt;code>yfinance&lt;/code> vai gerar um dataframe com multiindex, então precisamos separar da
forma que queremos&lt;/p>
&lt;pre>&lt;code class="language-python">
tickers_available = list(set([ ticket for ticket, _ in df.columns.T.to_numpy()]))
prices = pd.DataFrame()
for ticker in tickers_available:
try:
prices[ticker] = df[(ticker, 'Adj Close')]
except KeyError:
pass
&lt;/code>&lt;/pre>
&lt;p>Agora iremos calcular o retorno. Aqui entra um ponto delicado. Você poderá achar alguns posts na internet ou mesmo artigos argumentando que é necessário calcular o retorno como
$\log (r+1)$ pois assim as entradas da sua matriz seguirá uma distribuição normal o que permitirá a aplicação de RMT. Já vimos no presente texto que não precisamos que as entradas da matrizes venham de uma distribuição normal para que a &lt;strong>universalidade&lt;/strong> apareça. A escolha ou não de usar $\log$ nos retornos merece mais atenção, inclusive com críticas em relação ao uso[6, 7, 8]. Mas esse post não pretende te vender nada, por isso vou ficar com o mais simples.&lt;/p>
&lt;pre>&lt;code class="language-python"># calculamos os retornos
returns_all = prices.pct_change()
# a primeira linha não faz sentido, não existe retorno no primeiro dia
returns_all = returns_all.iloc[1:, :]
# vamos limpar todas as linhas se mnegociação e dropar qualquer coluna com muitos NaN
returns_all.dropna(axis = 1, thresh=len(returns_all.index)/2, inplace=True)
returns_all.dropna(axis = 0, inplace=True)
# seleciona apenas 150 colunas
returns_all = returns_all[np.random.choice(returns_all.columns, size=120, replace=False)]
#returns_all = returns_all.iloc[150:]
&lt;/code>&lt;/pre>
&lt;p>Com o &lt;code>df&lt;/code> pronto calcularemos a matriz de correlação e seus autovalores&lt;/p>
&lt;pre>&lt;code class="language-python">correlation_matrix = returns_all.interpolate().corr()
vals = np.linalg.eigh(correlation_matrix.values)[0]
&lt;/code>&lt;/pre>
&lt;p>Vamos usar os parâmetros padrões para $Q$ e $\sigma$ e torcer para que funcione&lt;/p>
&lt;pre>&lt;code class="language-python">
T, N = returns_all.shape
Q=T/N
sigma= 1
fig, ax = plt.subplots(1,1)
plot_marchenko_pastur(ax, vals, Q, sigma=1, bins=200, just_the_bulk=False)
plt.legend()
plt.savefig('Marchenko_Pastur_all.png', facecolor='w')
plt.close()
&lt;/code>&lt;/pre>
&lt;p>&lt;img src="Marchenko_Pastur_all.png" alt="">&lt;/p>
&lt;p>Usando todo o intervalo de tempo do nosso &lt;code>df&lt;/code> obtivemos o que parece um ajuste razoável. É claro que você poderia (deveria) rodar algum teste estatistico para verificar tal ajuste.
Existem alguns trabalhos que fizeram essa análise de forma rigorosa, comparando mercados e periódos específicos em relação a distribuição de Marchenko-Pastur[9].&lt;/p>
&lt;p>Se você for uma pessoa atenta notará que na imagem acima existem alguns autovalores fora do suporte da Marchenko-Pastur. A ideia de filtragem via RMT é como dito em [9] testar seus dados em relação a &amp;ldquo;&lt;em>hipótese nula&lt;/em>&amp;rdquo; da RMT. No caso se seus autovalores estão dentro do &lt;em>bulk&lt;/em> da distribuição que descreve um modelo de entradas &lt;em>i.i.d.&lt;/em>.&lt;/p>
&lt;p>Como isso foi aplicado em alguns trabalhos? Vamos ver na prática.&lt;/p>
&lt;p>Usaremos $70$% da série histórica para calcular uma nova matriz de correlação. Com a matriz de correlação em mãos vamos computar os autovalores e autovetores.&lt;/p>
&lt;pre>&lt;code class="language-python"># iremos usar 70% da serie para realizar a filtragem
returns_all.shape[0]*0.70
n_days = returns_all.shape[0]
n_days_in = int(n_days*(1-0.70))
returns = returns_all.copy()
sample = returns.iloc[:(returns.shape[0]-n_days_in), :].copy()
correlation_matrix = sample.interpolate().corr()
vals, vecs = np.linalg.eigh(correlation_matrix.values)
&lt;/code>&lt;/pre>
&lt;p>Os autovalores e autovetores podem ser compreendidos como a decomposição de uma dada matriz.
Portanto, o seguinte teste precisa passar&lt;/p>
&lt;pre>&lt;code class="language-python"> assert np.abs(
np.dot(vecs, np.dot(np.diag(vals), np.transpose(vecs))).flatten()
- correlation_matrix.values.flatten()
).max() &amp;lt; 1e-10
&lt;/code>&lt;/pre>
&lt;p>A distribuição de Marchenko-Pastur serve como um indicativo para nossa filtragem. O que faremos é jogar fora todos os autovalores
que estão dentro da distribuição de Marchenko-Pastur, posteriormente reconstruiremos a matriz de correlação.&lt;/p>
&lt;pre>&lt;code class="language-python">T, N = returns.shape
Q=T/N
sigma = 1
lp, lm = get_marchenko_bounds(Q, sigma)
# Filter the eigenvalues out
vals[vals &amp;lt;= lp ] = 0
# Reconstruct the matrix
filtered_matrix = np.dot(vecs, np.dot(np.diag(vals), np.transpose(vecs)))
np.fill_diagonal(filtered_matrix, 1)
&lt;/code>&lt;/pre>
&lt;p>Com a matriz de correlação filtrada você pode fazer o que bem entender com ela - existem outras maneiras de se realizar uma filtragem - uma das possíveis aplicações que precisa ser utilizada com cuidado é usar tal matriz filtrada como input para algoritmos de otimização de carteira. Talvez faça um outro post descrevendo essa otimização de forma mais clara, mas esse não é meu enfoque nesse post e nem minha especialidade. Portanto, se você quiser dar uma lida recomendo os seguintes posts: [17, 18]&lt;/p>
&lt;p>O que você precisa saber é que uma matriz de covariância, $\mathbf C_\sigma$, adimite uma decomposição em relação a matriz de correlação atráves da seguinte forma&lt;/p>
&lt;p>$$
\mathbf C_\sigma = \mathbf D^{-1/2} \mathbf C \mathbf D^{-1/2}
$$
onde $\mathbf D^{-1/2}$ é uma matriz diagonal com as entradas sendo os desvios padrão para cada serie de dados, isto é&lt;br>
$$
\begin{bmatrix}
\sigma_{1} &amp;amp;0 &amp;amp;\cdots &amp;amp;0 \\
0 &amp;amp;\sigma_{2} &amp;amp;\cdots &amp;amp;0 \\
\vdots &amp;amp;\vdots &amp;amp;\ddots &amp;amp;\vdots \\
0 &amp;amp;0 &amp;amp;\cdots &amp;amp;\sigma_{M} \end{bmatrix}
$$&lt;/p>
&lt;p>Discutimos uma maneira de obter uma matriz de correlação filtrada, $\mathbf{\tilde C}$, através de RMT,
a ideia é plugar essa nova matriz na equação anterior e obter uma nova matriz de covariância onde as informações menos relevantes foram eliminadas.&lt;/p>
&lt;p>$$
\mathbf{\tilde C_\sigma} = \mathbf D^{-1/2} \mathbf{\tilde C} \mathbf D^{-1/2}.
$$&lt;/p>
&lt;p>Tendo essa nova matriz de covâriancia filtrada agora basta você ingerir ela em algum método preferido para otimização e comparar com o resultado obtido usando a matriz original. Aqui usaremos o clássico Markowitz&lt;/p>
&lt;pre>&lt;code class="language-python"># Reconstruct the filtered covariance matrix
covariance_matrix = sample.cov()
inv_cov_mat = np.linalg.pinv(covariance_matrix)
# Construct minimum variance weights
ones = np.ones(len(inv_cov_mat))
inv_dot_ones = np.dot(inv_cov_mat, ones)
min_var_weights = inv_dot_ones/ np.dot( inv_dot_ones , ones)
variances = np.diag(sample.cov().values)
standard_deviations = np.sqrt(variances)
D = np.diag(standard_deviations)
filtered_cov = np.dot(D ,np.dot(filtered_matrix,D))
filtered_cov = filtered_matrix
filtered_cov = (np.dot(np.diag(standard_deviations),
np.dot(filtered_matrix,np.diag(standard_deviations))))
filt_inv_cov = np.linalg.pinv(filtered_cov)
# Construct minimum variance weights
ones = np.ones(len(filt_inv_cov))
inv_dot_ones = np.dot(filt_inv_cov, ones)
filt_min_var_weights = inv_dot_ones/ np.dot( inv_dot_ones , ones)
def get_cumulative_returns_over_time(sample, weights):
weights[weights &amp;lt;= 0 ] = 0
weights = weights / weights.sum()
return (((1+sample).cumprod(axis=0))-1).dot(weights)
cumulative_returns = get_cumulative_returns_over_time(returns, min_var_weights).values
cumulative_returns_filt = get_cumulative_returns_over_time(returns, filt_min_var_weights).values
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">
in_sample_ind = np.arange(0, (returns.shape[0]-n_days_in+1))
out_sample_ind = np.arange((returns.shape[0]-n_days_in), returns.shape[0])
f = plt.figure()
ax = plt.subplot(111)
points = np.arange(0, len(cumulative_returns))[out_sample_ind]
ax.plot(points, cumulative_returns[out_sample_ind], 'orange', linestyle='--', label='original')
ax.plot(points, cumulative_returns_filt[out_sample_ind], 'b', linestyle='-.', label='filtrado')
ymax = max(cumulative_returns[out_sample_ind].max(), cumulative_returns_filt[out_sample_ind].max())
ymin = min(cumulative_returns[out_sample_ind].min(), cumulative_returns_filt[out_sample_ind].min())
plt.legend()
plt.savefig('comp.png', facecolor='w')
plt.close()
&lt;/code>&lt;/pre>
&lt;p>&lt;img src="comp.png" alt="">&lt;/p>
&lt;p>Obtivemos uma melhora, mas novamente ressaltamos que uma analise mais criteriosa deveria ter sido feita. Vamos listar alguns pontos&lt;/p>
&lt;ol>
&lt;li>Em relação a questão da escolha do intervalo de tempo. Isto é, se o tamanho foi pequeno de mais para capturar a correlação ou se foi grande de mais tal que as correlações entre ativos não são estacionárias.&lt;/li>
&lt;li>O (não) uso do $\log$-retorno e seu impacto&lt;/li>
&lt;li>Uma escolha não aleatória do que seria analisado&lt;/li>
&lt;li>Métodos de unfolding dos autovalores (tema para outro post)&lt;/li>
&lt;/ol>
&lt;h1 id="5---vantagens-críticas-e-sugestões">5 - Vantagens, críticas e sugestões&lt;/h1>
&lt;p>Você poderá encontrar alguns trabalhos e posts descrevendo o uso de matrizes aleatórias para filtragem de matrizes de correlação sem uma boa crítica ou explicitação das limitações vou linkar aqui alguns pontos positivos e negativos e limitações&lt;/p>
&lt;h2 id="onde-realmente-rmt-se-mostrou-útil">Onde realmente RMT se mostrou útil&lt;/h2>
&lt;ul>
&lt;li>Obviamente a RMT é indiscutivelmente bem sucedida na matemática e física permitindo compreender sistemas apenas analisando a estatística dos &lt;em>gases matriciais&lt;/em>.&lt;/li>
&lt;li>Em machine learning a RMT também está provando ser uma ferramenta útil para compreender e melhorar o processo de aprendizado [15].&lt;/li>
&lt;li>Entender comportamentos de sistemas sociais, biológicos e econômicos. Aqui com entender o comportamento digo apenas saber se um dado segue uma característica dada por alguma lei específica como a lei de semicírculo. Isto é, não existe discussão em você pegar um dado sistema que é representado por uma matriz, estudar o comportamento do seu espectro de autovalores e autovetores e verificar que seguem algumas lei de universalidade. &lt;strong>Isso é bem diferente de dizer que se você filtrar uma matriz de correlação via RMT você irá obter sempre resultados melhores.&lt;/strong>&lt;/li>
&lt;/ul>
&lt;h2 id="limitações">Limitações&lt;/h2>
&lt;ul>
&lt;li>Note que não realizamos nenhum tipo de teste para decidir se realmente a distribuição de autovalores era a distribuição desejada. Baseamos isso só no olhometro, obviamente não é uma boa ideia.&lt;/li>
&lt;li>A filtragem apenas removendo os autovalores apesar de simples é limitada e pode ser contra produtiva, outros métodos de filtragem podem ser inclusive melhores[14]. Inclusive não é uma das únicas aplicações de RMT para tratamento desse tipo de dado [16]&lt;/li>
&lt;/ul>
&lt;h2 id="para-conhecer-mais">Para conhecer mais&lt;/h2>
&lt;h3 id="ciêntistas">Ciêntistas&lt;/h3>
&lt;ul>
&lt;li>Alguns grandes nomes de RMT: Madan Lal Mehta, Freeman Dyson e Terrence Tao&lt;/li>
&lt;li>Alguns brasileiros: Marcel Novaes autor do livro
&lt;a href="https://link.springer.com/book/10.1007/978-3-319-70885-0" target="_blank" rel="noopener">Introduction to Random Matrices - Theory and Practice&lt;/a>-
&lt;a href="https://arxiv.org/abs/1712.07903" target="_blank" rel="noopener">arxiv&lt;/a>; Fernando Lucas Metz trabalhou com o Nobel Giorgio Parisi.&lt;/li>
&lt;/ul>
&lt;h3 id="encontrou-um-erro-ou-quer-melhorar-esse-texto">Encontrou um erro ou quer melhorar esse texto?&lt;/h3>
&lt;ul>
&lt;li>Faça sua contribuição criando uma
&lt;a href="https://github.com/devmessias/devmessias.github.io/issues/new" target="_blank" rel="noopener">issue&lt;/a> ou um PR editando esse arquivo aqui
&lt;a href="https://github.com/devmessias/devmessias.github.io/blob/master/content/post/random_matrix_theory/index.md" target="_blank" rel="noopener">random_matrix_theory/index.md&lt;/a>.&lt;/li>
&lt;/ul>
&lt;h1 id="6-referências">6-Referências&lt;/h1>
&lt;ul>
&lt;li>
&lt;p>[1] M. Kac, “Can One Hear the Shape of a Drum?,” The American Mathematical Monthly, vol. 73, no. 4, p. 1, Apr. 1966, doi: 10.2307/2313748.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>[2] Wigner, E.P., 1957. Statistical properties of real symmetric matrices with many dimensions (pp. 174-184). Princeton University.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>[4] “From Prime Numbers to Nuclear Physics and Beyond,” Institute for Advanced Study.
&lt;a href="https://www.ias.edu/ideas/2013/primes-random-matrices" target="_blank" rel="noopener">https://www.ias.edu/ideas/2013/primes-random-matrices&lt;/a> (accessed Sep. 30, 2020).&lt;/p>
&lt;/li>
&lt;li>
&lt;p>[5] “GUE hypothesis,” What’s new.
&lt;a href="https://terrytao.wordpress.com/tag/gue-hypothesis/" target="_blank" rel="noopener">https://terrytao.wordpress.com/tag/gue-hypothesis/&lt;/a> (accessed Nov. 22, 2021).&lt;/p>
&lt;/li>
&lt;li>
&lt;p>[6] R. Hudson and A. Gregoriou, “Calculating and Comparing Security Returns is Harder than you Think: A Comparison between Logarithmic and Simple Returns,” Social Science Research Network, Rochester, NY, SSRN Scholarly Paper ID 1549328, Feb. 2010. doi: 10.2139/ssrn.1549328.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>[7] A. Meucci, “Quant Nugget 2: Linear vs. Compounded Returns – Common Pitfalls in Portfolio Management,” Social Science Research Network, Rochester, NY, SSRN Scholarly Paper ID 1586656, May 2010. Accessed: Dec. 01, 2021. [Online]. Available:
&lt;a href="https://papers.ssrn.com/abstract=1586656" target="_blank" rel="noopener">https://papers.ssrn.com/abstract=1586656&lt;/a>&lt;/p>
&lt;/li>
&lt;li>
&lt;p>[8] Lidian, “Analysis on Stocks: Log(1+return) or Simple Return?,” Medium, Sep. 18, 2020.
&lt;a href="https://medium.com/@huangchingchiu/analysis-on-stocks-log-1-return-or-simple-return-371c3f60fab2" target="_blank" rel="noopener">https://medium.com/@huangchingchiu/analysis-on-stocks-log-1-return-or-simple-return-371c3f60fab2&lt;/a> (accessed Nov. 25, 2021).&lt;/p>
&lt;/li>
&lt;li>
&lt;p>[9] N. A. Eterovic and D. S. Eterovic, “Separating the Wheat from the Chaff: Understanding Portfolio Returns in an Emerging Market,” Social Science Research Network, Rochester, NY, SSRN Scholarly Paper ID 2161646, Oct. 2012. doi: 10.2139/ssrn.2161646.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>[10] E. P. Wigner, “Characteristic Vectors of Bordered Matrices With Infinite Dimensions,” Annals of Mathematics, vol. 62, no. 3, pp. 548–564, 1955, doi: 10.2307/1970079.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>[11] E. P. Wigner, “On the statistical distribution of the widths and spacings of nuclear resonance levels,” Mathematical Proceedings of the Cambridge Philosophical Society, vol. 47, no. 4, pp. 790–798, Oct. 1951, doi: 10.1017/S0305004100027237.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>[13] F. W. K. Firk and S. J. Miller, “Nuclei, Primes and the Random Matrix Connection,” Symmetry, vol. 1, no. 1, pp. 64–105, Sep. 2009, doi: 10.3390/sym1010064.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>[14] L. Sandoval, A. B. Bortoluzzo, and M. K. Venezuela, “Not all that glitters is RMT in the forecasting of risk of portfolios in the Brazilian stock market,” Physica A: Statistical Mechanics and its Applications, vol. 410, pp. 94–109, Sep. 2014, doi: 10.1016/j.physa.2014.05.006.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>[15] M. E. A. Seddik, C. Louart, M. Tamaazousti, and R. Couillet, “Random Matrix Theory Proves that Deep Learning Representations of GAN-data Behave as Gaussian Mixtures,” arXiv:2001.08370 [cs, stat], Jan. 2020, Accessed: Dec. 05, 2021. [Online]. Available:
&lt;a href="http://arxiv.org/abs/2001.08370" target="_blank" rel="noopener">http://arxiv.org/abs/2001.08370&lt;/a>&lt;/p>
&lt;/li>
&lt;li>
&lt;p>[16] D. B. Aires, “Análise de crises financeiras brasileiras usando teoria das matrizes aleatórias,” Universidade Estadual Paulista (Unesp), 2021. Accessed: Dec. 05, 2021. [Online]. Available:
&lt;a href="https://repositorio.unesp.br/handle/11449/204550" target="_blank" rel="noopener">https://repositorio.unesp.br/handle/11449/204550&lt;/a>&lt;/p>
&lt;/li>
&lt;li>
&lt;p>[17] S. Rome, “Eigen-vesting II. Optimize Your Portfolio With Optimization,” Scott Rome, Mar. 22, 2016.
&lt;a href="http://srome.github.io//Eigenvesting-II-Optimize-Your-Portfolio-With-Optimization/" target="_blank" rel="noopener">http://srome.github.io//Eigenvesting-II-Optimize-Your-Portfolio-With-Optimization/&lt;/a> (accessed Dec. 05, 2021).&lt;/p>
&lt;/li>
&lt;li>
&lt;p>[18] “11.1 Portfolio Optimization — MOSEK Fusion API for Python 9.3.10.”
&lt;a href="https://docs.mosek.com/latest/pythonfusion/case-studies-portfolio.html" target="_blank" rel="noopener">https://docs.mosek.com/latest/pythonfusion/case-studies-portfolio.html&lt;/a> (accessed Dec. 05, 2021).&lt;/p>
&lt;/li>
&lt;/ul></description></item></channel></rss>