<?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>/tag/python/</link><atom:link href="/tag/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>/tag/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>Dissecting processes and failures in Linux with lsof and strace: cases for MlOps and DevOps</title><link>/post/using_lsof_and_strace_to_investigate_process_and_failures/</link><pubDate>Fri, 04 Feb 2022 08:31:00 -0300</pubDate><guid>/post/using_lsof_and_strace_to_investigate_process_and_failures/</guid><description>&lt;p>In DevOps or MlOps discovering what a process is doing now can save your system from a catastrophe. But sometimes we are already in a failure. When those failures happen, the following questions appear:&lt;/p>
&lt;ul>
&lt;li>
&lt;p>&lt;em>The process it’s hanging and I don’t know why!&lt;/em>&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;em>What is the cause of the problem?&lt;/em>&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;em>Is it a network issue?&lt;/em>&lt;/p>
&lt;/li>
&lt;li>
&lt;p>…and so on and so forth.&lt;/p>
&lt;/li>
&lt;/ul>
&lt;p>Being able to answer these questions faster and with a precise answer can save you or give you a promotion. I’ll show you some simple examples of how those questions can be answered.&lt;/p>
&lt;figure id="figure-the-strace-logo-is-an-ostrich">
&lt;a data-fancybox="" href="/post/using_lsof_and_strace_to_investigate_process_and_failures/strace_lsof_twitter_hu8f2dca20993b287d55ca9195e297c994_439856_2000x2000_fit_lanczos_3.png" data-caption="The strace logo is an ostrich.">
&lt;img src="/post/using_lsof_and_strace_to_investigate_process_and_failures/strace_lsof_twitter_hu8f2dca20993b287d55ca9195e297c994_439856_2000x2000_fit_lanczos_3.png" alt="" >
&lt;/a>
&lt;figcaption>
The strace logo is an ostrich.
&lt;/figcaption>
&lt;/figure>
&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="#concepts">Concepts&lt;/a>
&lt;ul>
&lt;li>&lt;a href="#everything-is-a-file---the-unix-mantra">&lt;em>“Everything is a file.”&lt;/em> - The UNIX mantra.&lt;/a>
&lt;ul>
&lt;li>&lt;a href="#lsof">LSOF&lt;/a>&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;a href="#system-calls-and-strace">System Calls and strace&lt;/a>&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;a href="#a-deep-dive-into-failures">A deep dive into failures&lt;/a>
&lt;ul>
&lt;li>&lt;a href="#network-issues">Network issues&lt;/a>
&lt;ul>
&lt;li>&lt;a href="#is-my-server-alive">Is my server alive?&lt;/a>&lt;/li>
&lt;li>&lt;a href="#is-my-process-stuck-waiting-for-someone-what-is-causing-the-process-hanging">Is my process stuck waiting for someone? What is causing the process hanging?&lt;/a>&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;a href="#problems-with-regular-files">Problems with regular files&lt;/a>
&lt;ul>
&lt;li>&lt;a href="#which-processes-is-this-file-attached-to">Which processes is this file attached to?&lt;/a>&lt;/li>
&lt;li>&lt;a href="#i-made-a-mistake-deleted-an-important-file-how-can-i-recover-it">I made a mistake! Deleted an important file! How can I recover it?&lt;/a>&lt;/li>
&lt;li>&lt;a href="#silent-errors-associated-with-files-and-permissions">Silent errors associated with files and permissions&lt;/a>&lt;/li>
&lt;li>&lt;a href="#is-this-process-using-a-cache-where-can-i-find-this-cache-which-configs-files-does-this-process-use">Is this process using a cache? Where can I find this cache? Which configs files does this process use?&lt;/a>&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;a href="#dissecting-your-database-system">Dissecting your database system&lt;/a>
&lt;ul>
&lt;li>&lt;a href="#is-this-process--well-behaved-how-many-connections-does-it-have">Is this process well behaved? How many connections does it have?&lt;/a>&lt;/li>
&lt;li>&lt;a href="#everything-is-working-proprely">Everything is working proprely?&lt;/a>&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;a href="#extras-related-to-files-proc-and-strace">Extras related to files (&lt;code>/proc/&lt;/code>) and &lt;code>strace&lt;/code>&lt;/a>
&lt;ul>
&lt;li>&lt;a href="#creating-a-sys-call-summary-what-does-my-program-do">Creating a SYS CALL summary: what does my program do?&lt;/a>&lt;/li>
&lt;li>&lt;a href="#did-this-process-start-with-the-correct-environment-variables">Did this process start with the correct environment variables?&lt;/a>&lt;/li>
&lt;li>&lt;a href="#i-forgot-to-redirect-the-outputs-what-can-i-do-now">I forgot to redirect the outputs! What can I do now?&lt;/a>&lt;/li>
&lt;li>&lt;a href="#how-this-program-has-been-called-what-is-the-working-dir-of-the-process">How this program has been called? What is the working dir of the process?&lt;/a>&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;a href="#conclusion--suggestions">Conclusion &amp;amp; Suggestions&lt;/a>&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ul>
&lt;/nav>
&lt;/details>
&lt;p>&lt;strong>Introduction&lt;/strong>&lt;/p>
&lt;p>Linux is a very transparent operating system. Transparency means that is easy to dig in the system&amp;rsquo;s behavior to understand how it works. Also, Linux is easy to control even in the low-level behaviors. But how can this help to understand a process and consequently a failure?&lt;/p>
&lt;p>The first step to understanding a process is to analyze the output. But sometimes the output doesn’t give us enough information to use. Here I’ll talk about how we can extract useful information using the &lt;code>strace&lt;/code> and &lt;code>lsof&lt;/code> commands. To use these commands it is good to know two concepts: the &lt;em>“Everything is a file ”&lt;/em> mantra and the &lt;strong>system call&lt;/strong> mechanism.&lt;/p>
&lt;h1 id="concepts">Concepts&lt;/h1>
&lt;h2 id="everything-is-a-file---the-unix-mantra">&lt;em>“Everything is a file.”&lt;/em> - The UNIX mantra.&lt;/h2>
&lt;p>&lt;img src="everthing_is_a_file.png" alt="everything_is_a_file">&lt;/p>
&lt;p>What comes to your mind when someone talks about files? Maybe a jpeg or a CSV if you work as a data scientist. But in UNIX approach to do stuff everything can be a file, even network connections. When a thing is not a file it has at least a file descriptor associated with it. Maybe you’re thinking that I’m wandering from the post. &lt;em>“How can this stuff help to improve our comprehension about a process or failure?”&lt;/em> The answer is straightforward: if everything is a file, we can use the same set of tools to list, read and interact (API) with files to analyze a generic process. Here is where &lt;code>lsof&lt;/code> appears.&lt;/p>
&lt;h3 id="lsof">LSOF&lt;/h3>
&lt;p>lsof is an acronym for &lt;strong>l&lt;/strong>ist of &lt;strong>o&lt;/strong>pen &lt;strong>f&lt;/strong>iles. In simple terms, Lsof is a command-line tool that can list open file descriptors in your machine. Besides that, Lsof allows using a set of different filters to give you a filtered list of opened files. Thus, we can list the open file descriptors of a user or a process.&lt;/p>
&lt;p>To put all the open files in your machine use the following command:&lt;/p>
&lt;pre>&lt;code class="language-bash">username:/$ lsof &amp;gt; lsof_everything.txt
&lt;/code>&lt;/pre>
&lt;p>The file &lt;code>lsof_everything.txt&lt;/code> is huge and will look similar to this&lt;/p>
&lt;pre>&lt;code>COMMAND PID TID TASKCMD USER FD TYPE DEVICE SIZE/OFF NODE NAME
systemd 1 root cwd unknown /proc/1/cwd (readlink: Permission denied)
systemd 1 root rtd unknown /proc/1/root (readlink: Permission denied)
systemd 1 root txt unknown /proc/1/exe (readlink: Permission denied)
&lt;/code>&lt;/pre>
&lt;p>Take some time to analyze the output. The output relates to the first lines to the &lt;code>root&lt;/code> user and you don’t have permission to gain information about these files, which is good. Let’s remove this wasteful information filtering the SYS CALLs related to just your user.&lt;/p>
&lt;pre>&lt;code class="language-bash">username:/$ lsof -u username &amp;gt; lsof_my.txt
&lt;/code>&lt;/pre>
&lt;p>The &lt;code>txt&lt;/code> file is still big. Try to look into this file to see if you can find anything interesting, like a webpage address.&lt;/p>
&lt;p>We have a lot of different columns in the file. But don’t be worried, I’ll show you the columns that I believe are the most important ones.&lt;/p>
&lt;ul>
&lt;li>COMMAND
&lt;ul>
&lt;li>The command name used to initiate the process&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>PID
&lt;ul>
&lt;li>This is an integer number that identifies a process, &lt;strong>P&lt;/strong>rocess &lt;strong>ID&lt;/strong>entification number.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>USER
&lt;ul>
&lt;li>The user to whom the process belongs.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>TYPE
&lt;ul>
&lt;li>This may be one of the most important columns. It has more than 60 possible values. Such column says the type of the node associated with the file. If the file is related with connections and sockets you will see things like that: &lt;strong>IPV4, IPV6,&lt;/strong> &lt;strong>unix&lt;/strong>, &lt;strong>INET&lt;/strong>, etc. If it’s an regular file (csv, jpeg, txt, etc.) you will see the &lt;strong>REG&lt;/strong> value.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>NODE
&lt;ul>
&lt;li>This helps us to identify the node associated with the file descriptor. It can be a number, a string, etc. In the case of internet protocols this column will have values like &lt;strong>TCP, UDP&lt;/strong>.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>NAME
&lt;ul>
&lt;li>The values here will change a lot. For example, sometimes it can be a web server address or just a cryptic string. Regardless of the difficulty of interpreting the values in this column you should look carrefully here.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ul>
&lt;p>If you want a more deep understanding of the columns just uses &lt;code>man lsof&lt;/code> .&lt;/p>
&lt;h2 id="system-calls-and-strace">System Calls and strace&lt;/h2>
&lt;p>The SYSTEM_CALL is a mechanism that allows a program to ask the kernel for some resources, like the access of data stored in the disk. Therefore, if we have a tool to intercept those calls, we can have a deep comprehension of what a program is doing or what it want’s to do in your system. A celebrated tool to intercept the system calls is the &lt;code>strace&lt;/code>.&lt;/p>
&lt;p>If the strace command is not available in your system, install it. In apt-based distros just calling the following command should be enough.&lt;/p>
&lt;pre>&lt;code class="language-bash">$ apt install strace
&lt;/code>&lt;/pre>
&lt;div class="alert alert-note">
&lt;div>
In older Debian distros (&amp;lt;=10) you can get the last deb package from here: &lt;a href="http://ftp.de.debian.org/debian/pool/main/s/strace/strace_5.10-1_amd64.deb">strace_5.10-1_amd64.deb&lt;/a>. The new version of strace has some cool features that can facilitate our job.
&lt;/div>
&lt;/div>
&lt;p>You can use &lt;code>strace&lt;/code> in two different ways. The first one is to call strace followed by the strace arguments and the command to be intercepted:&lt;/p>
&lt;pre>&lt;code class="language-bash">$ strace ARGS command
&lt;/code>&lt;/pre>
&lt;p>In the second way we will replace the command by the &lt;code>-p&lt;/code> argument followed by the process identification number (&lt;strong>PID&lt;/strong>) of the process to be intercepted:&lt;/p>
&lt;pre>&lt;code class="language-bash">$ strace ARGS -p PID
&lt;/code>&lt;/pre>
&lt;p>To discover the PID of a process, you can use the command &lt;code>ps aux | grep -i ‘[p]rocess_name’&lt;/code>.&lt;/p>
&lt;p>Let’s see an example. We will ask &lt;code>strace&lt;/code> to intercept any system call performed by the &lt;code>ls&lt;/code> command and we want to record the time that the system call was performed using the &lt;code>-t&lt;/code> argument.&lt;/p>
&lt;pre>&lt;code class="language-bash">$ strace -t ls
&lt;/code>&lt;/pre>
&lt;p>The output will be something similar to this:&lt;/p>
&lt;pre>&lt;code>18:02:23 execve(&amp;quot;/usr/bin/ls&amp;quot;, [&amp;quot;ls&amp;quot;], 0x7fffa727a418 /* 54 vars */) = 0
18:02:23 brk(NULL) = 0x55ebef60c000
18:02:23 access(&amp;quot;/etc/ld.so.preload&amp;quot;, R_OK) = -1 ENOENT (No such file or directory)
18:02:23 openat(AT_FDCWD, &amp;quot;/etc/ld.so.cache&amp;quot;, O_RDONLY|O_CLOEXEC) = 3
...
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>18:02:23 execve(&amp;quot;/usr/bin/ls&amp;quot;, [&amp;quot;ls&amp;quot;], 0x7fffa727a418 /* 54 vars */) = 0
18:02:23 brk(NULL) = 0x55ebef60c000
18:02:23 access(&amp;quot;/etc/ld.so.preload&amp;quot;, R_OK) = -1 ENOENT (No such file or directory)
18:02:23 openat(AT_FDCWD, &amp;quot;/etc/ld.so.cache&amp;quot;, O_RDONLY|O_CLOEXEC) = 3
...
&lt;/code>&lt;/pre>
&lt;p>Each line of the &lt;code>strace&lt;/code> output represents a single SYSTEM CALL. It’s easy to see the following pattern:&lt;/p>
&lt;p>&lt;strong>Name of the SYS CALL(Arguments to be used in the system call) = Result of the SYS CALL&lt;/strong>&lt;/p>
&lt;p>Yes, it’s hard to understand the output or impossible without using a manual. For each SYS CALL you can use the &lt;code>man &lt;/code> command to get more information about what each line represents. For example, to see what &lt;code>openat&lt;/code> does and the meaning of each argument, use the following command:&lt;/p>
&lt;pre>&lt;code class="language-bash">$ man 2 openat
&lt;/code>&lt;/pre>
&lt;p>&lt;code>openat&lt;/code> is a sys call responsible for requesting a file to be opened. The result of the last line in the output of ls commands, &lt;code> 3&lt;/code>, means a successfully SYS CALL.&lt;/p>
&lt;h1 id="a-deep-dive-into-failures">A deep dive into failures&lt;/h1>
&lt;p>We will see here failures and issues related to files, connections, etc. But don’t be afraid to explore other problems, we are just scratching the surface of &lt;code>strace&lt;/code> and &lt;code>lsof&lt;/code>.&lt;/p>
&lt;h2 id="network-issues">Network issues&lt;/h2>
&lt;p>First, install the following packages:&lt;/p>
&lt;pre>&lt;code class="language-bash">$ python -m pip install requests flask
&lt;/code>&lt;/pre>
&lt;p>Create a script &lt;code>server_mlops.py&lt;/code> which we will use to simulate a server with network issues&lt;/p>
&lt;pre>&lt;code class="language-python"># server_mlops.py
import time
import flask
app = flask.Flask(__name__)
@app.route('/')
def hello_world():
sleep_time = flask.request.args.get('sleep', default=10, type=int)
print('sleep_time:', sleep_time)
time.sleep(sleep_time)
return 'Hello World!'
if __name__ == '__main__':
app.run()
&lt;/code>&lt;/pre>
&lt;p>Starts the server:&lt;/p>
&lt;pre>&lt;code class="language-bash">$ python server_mlops.py
&lt;/code>&lt;/pre>
&lt;p>GET The PID of the process:&lt;/p>
&lt;pre>&lt;code class="language-bash">$ ps aux | grep -i '[s]erver_mlops.py'
&lt;/code>&lt;/pre>
&lt;p>You will see a output similar to this:&lt;/p>
&lt;pre>&lt;code class="language-bash">devmess+ 19321 18.0 0.3 29716 24792 pts/5 S+ 14:27 0:00 python server_mlops.py
&lt;/code>&lt;/pre>
&lt;p>The number in front of the username (&lt;code>19321&lt;/code>) is the &lt;code>PID&lt;/code> of the process.&lt;/p>
&lt;h3 id="is-my-server-alive">Is my server alive?&lt;/h3>
&lt;p>We have to use a unique set of filters to answer this question using the &lt;code>lsof&lt;/code>. Therefore, we need to use the argument &lt;code>-a&lt;/code> , which represents an &lt;code>AND&lt;/code> operator. The &lt;code>-i&lt;/code> argument asks to show just the files associated with connections and finally the argument &lt;code>-p INT&lt;/code> makes the &lt;code>losf&lt;/code> list just the files opened by the process with the PID &lt;code>INT&lt;/code>.&lt;/p>
&lt;pre>&lt;code class="language-bash">$ lsof -a -i -p 19321
&lt;/code>&lt;/pre>
&lt;p>You will have a output similar to this&lt;/p>
&lt;table>
&lt;thead>
&lt;tr>
&lt;th>COMMAND&lt;/th>
&lt;th>PID&lt;/th>
&lt;th>USER&lt;/th>
&lt;th>FD&lt;/th>
&lt;th>TYPE&lt;/th>
&lt;th>DEVICE&lt;/th>
&lt;th>SIZE/OFF&lt;/th>
&lt;th>NODE&lt;/th>
&lt;th>NAME&lt;/th>
&lt;/tr>
&lt;/thead>
&lt;tbody>
&lt;tr>
&lt;td>python&lt;/td>
&lt;td>19321&lt;/td>
&lt;td>devmessias&lt;/td>
&lt;td>4u&lt;/td>
&lt;td>IPv4&lt;/td>
&lt;td>16108218&lt;/td>
&lt;td>0t0&lt;/td>
&lt;td>TCP&lt;/td>
&lt;td>localhost:5000 (LISTEN)&lt;/td>
&lt;/tr>
&lt;/tbody>
&lt;/table>
&lt;p>The output shows that at least our server is listening in the &lt;code>5000&lt;/code> port. Try to remove the &lt;code>-a&lt;/code> argument and see what happens.&lt;/p>
&lt;h3 id="is-my-process-stuck-waiting-for-someone-what-is-causing-the-process-hanging">Is my process stuck waiting for someone? What is causing the process hanging?&lt;/h3>
&lt;p>This can happen in a myriad of cases. For example, in the dependency management systems like pip/conda. Thus, it is superb to know if you can answer fast if you have a problem on your side or not. Let’s create a simple simulation of this issue. To do so, create the &lt;code>client_mlops.py&lt;/code> using the following code:&lt;/p>
&lt;pre>&lt;code class="language-python">#!/usr/bin/env python
#client_mlops.py
import requests
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
'--sleep', type=int, help='time to sleep', default=0)
args = parser.parse_args()
print('Ask for localhost:5000 to sleep for {} seconds'.format(args.sleep))
r = requests.get('http://localhost:5000', params={'sleep': int(args.sleep)})
print(r.text)
&lt;/code>&lt;/pre>
&lt;p>In the above code, we have the sleep argument. This argument will ask &lt;code>server_mlops&lt;/code> to wait for a couple of seconds before sending the answer. Let’s see how these situations appear to us at the system call level.&lt;/p>
&lt;p>Start the &lt;code>client_mlops.py&lt;/code> with the &lt;code>strace:&lt;/code>&lt;/p>
&lt;pre>&lt;code class="language-bash">$ strace -e poll,select,connect,recvfrom,sendto python client_mlops.py --sleep=20
&lt;/code>&lt;/pre>
&lt;p>The &lt;code>-e&lt;/code> argument followed by &lt;code>poll,select,connect,recvfrom,sendto&lt;/code> asks to filter just the sys calls related with connections issues. The output of this fake failure will be something like this&lt;/p>
&lt;pre>&lt;code>connect(4, {sa_family=AF_INET, sin_port=htons(5000), sin_addr=inet_addr(&amp;quot;127.0.0.1&amp;quot;)}, 16) = 0
connect(4, {sa_family=AF_INET6, sin6_port=htons(5000), inet_pton(AF_INET6, &amp;quot;::1&amp;quot;, &amp;amp;sin6_addr), sin6_flowinfo=htonl(0), sin6_scope_id=0}, 28) = 0
connect(4, {sa_family=AF_INET6, sin6_port=htons(5000), inet_pton(AF_INET6, &amp;quot;::1&amp;quot;, &amp;amp;sin6_addr), sin6_flowinfo=htonl(0), sin6_scope_id=0}, 28) = -1 ECONNREFUSED (Connection refused)
connect(4, {sa_family=AF_INET, sin_port=htons(5000), sin_addr=inet_addr(&amp;quot;127.0.0.1&amp;quot;)}, 16) = 0
sendto(4, &amp;quot;GET /?sleep=10 HTTP/1.1\r\nHost: l&amp;quot;..., 154, 0, NULL, 0) = 154
recvfrom(4,
&lt;/code>&lt;/pre>
&lt;p>In the last line we see an unfinished &lt;code>recvfrom&lt;/code> &lt;strong>SYS_CALL&lt;/strong> . Do you want to know more about &lt;code>recvfrom&lt;/code>? Execute &lt;code>man 2 recvfrom&lt;/code> in a terminal session. But what matters here? The point is that: &lt;code>strace&lt;/code> is telling us there is no problem with our client program, something is problematic on the server side.&lt;/p>
&lt;p>You can also use the &lt;code>lsof&lt;/code> to investigate this problem. Let’s simulate this scenario.&lt;/p>
&lt;p>Starts the client again:&lt;/p>
&lt;pre>&lt;code class="language-bash">$ python client_mlops.py --sleep=100
&lt;/code>&lt;/pre>
&lt;p>Now, get the PID using &lt;code>ps aux | grep -i '[c]lient_mlops.py'&lt;/code> and execute the &lt;code>lsof&lt;/code> with the obtained PID&lt;/p>
&lt;pre>&lt;code class="language-bash">lsof -a -i -p 19321
&lt;/code>&lt;/pre>
&lt;p>the output will be something like this&lt;/p>
&lt;table>
&lt;thead>
&lt;tr>
&lt;th>COMMAND&lt;/th>
&lt;th>PID&lt;/th>
&lt;th>USER&lt;/th>
&lt;th>FD&lt;/th>
&lt;th>TYPE&lt;/th>
&lt;th>DEVICE&lt;/th>
&lt;th>SIZE/OFF&lt;/th>
&lt;th>NODE&lt;/th>
&lt;th>NAME&lt;/th>
&lt;/tr>
&lt;/thead>
&lt;tbody>
&lt;tr>
&lt;td>python&lt;/td>
&lt;td>31551&lt;/td>
&lt;td>devmessias&lt;/td>
&lt;td>4u&lt;/td>
&lt;td>IPv4&lt;/td>
&lt;td>16622065&lt;/td>
&lt;td>0t0&lt;/td>
&lt;td>TCP&lt;/td>
&lt;td>localhost:57314-&amp;gt;localhost:5000 (ESTABLISHED)&lt;/td>
&lt;/tr>
&lt;/tbody>
&lt;/table>
&lt;p>What &lt;code>lsof&lt;/code> is telling us is that: ‘’&lt;em>You client seems fine. At least it is connected with the server&lt;/em>“”. What does this mean? This means the answer was not of great help.&lt;/p>
&lt;h2 id="problems-with-regular-files">Problems with regular files&lt;/h2>
&lt;p>Sometimes you can have a problem with regular files and you don’t know. Nothing was printed in the output. For example, a wrong cache being used, a program that tries to access a file that doesn’t have permission, a malicious or a bad writing process accessing/creating files in your system, etc.&lt;/p>
&lt;p>Here we will simulate simple examples related to regular files. To do so, first, copy any file to the &lt;code>tmp&lt;/code> folder or just call the following command:&lt;/p>
&lt;pre>&lt;code class="language-bash">$ man strace &amp;gt; /tmp/dummy_file.txt
&lt;/code>&lt;/pre>
&lt;h3 id="which-processes-is-this-file-attached-to">Which processes is this file attached to?&lt;/h3>
&lt;p>Being able to answer this question can be quite useful. For example, suppose that there is a huge file in your disk being created, almost filling up your system and you want to discover which process is doing this.&lt;/p>
&lt;p>First, create the following script.&lt;/p>
&lt;pre>&lt;code class="language-python">#!/usr/bin/env python
# file_open.py
import time
f = open('/tmp/dummy_file.txt', 'r')
input('Press Enter to continue...')
&lt;/code>&lt;/pre>
&lt;p>Now open two different terminal sessions and perform the following command &lt;code>python file_open.py &lt;/code>. in each one.&lt;/p>
&lt;p>To find all the processes which are attached to &lt;code>dummy_file.txt&lt;/code> you just need to call &lt;code>lsof&lt;/code> like this:&lt;/p>
&lt;pre>&lt;code class="language-bash">$ lsof /tmp/dummy_file.txt
&lt;/code>&lt;/pre>
&lt;p>The output should be something similar to this:&lt;/p>
&lt;pre>&lt;code>COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
python 15411 devmessias 3r REG 8,2 0 2911031 /tmp/dummy_file.txt
python 20777 devmessias 3r REG 8,2 0 2911031 /tmp/dummy_file.txt
&lt;/code>&lt;/pre>
&lt;p>We have two distinct processes, two different PIDs, using the same file.&lt;/p>
&lt;h3 id="i-made-a-mistake-deleted-an-important-file-how-can-i-recover-it">I made a mistake! Deleted an important file! How can I recover it?&lt;/h3>
&lt;p>Here the simulation will be more than one more process attached to a file and you accidentally perform some action that deletes the file.&lt;/p>
&lt;p>Create a file &lt;code>accident.txt&lt;/code>. Open a terminal session and perform the following command. &lt;strong>Don’t close the session!&lt;/strong>&lt;/p>
&lt;pre>&lt;code class="language-bash">$ python -c 'f=open(&amp;quot;accident.txt&amp;quot;, &amp;quot;r&amp;quot;);input(&amp;quot;...&amp;quot;)'
&lt;/code>&lt;/pre>
&lt;p>In another session, perform the following commands:&lt;/p>
&lt;pre>&lt;code class="language-bash">$ rm accident.txt
$ ls accident.txt
&lt;/code>&lt;/pre>
&lt;p>And it’s gone :(&lt;/p>
&lt;pre>&lt;code>ls: cannot access 'acidente.txt': No such file or directory
&lt;/code>&lt;/pre>
&lt;p>Don’t worry! Linux has a lot of cool aspects and one of them will help us to recover our file.&lt;/p>
&lt;p>In Linux any process has a directory associated with it, this directory will be inside of the &lt;code>/proc&lt;/code> folder. And what do these directories store? A lot of things! I assure you that you can be surprised. For example, these folders also store the file descriptors associated with any process using &lt;code>accident.txt&lt;/code>. Let’s see if there are any processes using this file.&lt;/p>
&lt;pre>&lt;code class="language-bash">$ lsof -u your_username | grep 'accident.txt'
&lt;/code>&lt;/pre>
&lt;p>In my case, I’ve obtained the following output:&lt;/p>
&lt;pre>&lt;code>python 22465 devmessias 3r REG 8,2 37599 14288174 path/accident.txt (deleted)
&lt;/code>&lt;/pre>
&lt;p>This is great news! We have a process PID &lt;code>22465&lt;/code> that still has a file descriptor associated with &lt;code>accident.txt&lt;/code>. Now we can use a simple &lt;code>cp&lt;/code> command to recover the data. To do so, we need to use the file descriptor number. In my case is &lt;code>3&lt;/code> which is the number in front of the &lt;code>r&lt;/code> character in the output above.&lt;/p>
&lt;pre>&lt;code class="language-bash">$ cp /proc/22465/fd/3 recovered.txt
&lt;/code>&lt;/pre>
&lt;p>Now just call &lt;code>nano recovered.txt&lt;/code> and testify the result . It’s not magic! It’s just how the &lt;strong>process pseudo-filesystem&lt;/strong> works!&lt;/p>
&lt;h3 id="silent-errors-associated-with-files-and-permissions">Silent errors associated with files and permissions&lt;/h3>
&lt;p>Let’s create a simple example of an undue access to a file using the following script&lt;/p>
&lt;pre>&lt;code class="language-python">#!/usr/bin/env python
# file_404.py
import time
try:
f = open('/tmp/file_that_dosent_exist.csv', 'r')
except FileNotFoundError:
pass
try:
# create a file with sudo and then change the permission using chmod 700
f = open('/tmp/file_wrong_permission.csv', 'r')
except PermissionError:
pass
input('Press Enter to continue...')
&lt;/code>&lt;/pre>
&lt;p>Call &lt;code>python file_404.py&lt;/code>, nothing will appears.&lt;/p>
&lt;p>To trace any SYS CALL related to regular files made by &lt;code>python file_404.py &lt;/code> you just need to use the &lt;code>-e trace=file&lt;/code> arg, like this:&lt;/p>
&lt;pre>&lt;code class="language-bash">$ strace -f -e trace=file python file_404.py
&lt;/code>&lt;/pre>
&lt;p>The argument &lt;code>-f&lt;/code> says to &lt;code>strace&lt;/code> to monitor any children&amp;rsquo;s process. You probably will use &lt;code>-f&lt;/code> every time when you’re dealing with strace in real case scenarios.&lt;/p>
&lt;p>The output of the previous command should be like this&lt;/p>
&lt;pre>&lt;code>lstat(&amp;quot;something/file_404.py&amp;quot;, {st_mode=S_IFREG|0644, st_size=242, ...}) = 0
openat(AT_FDCWD, &amp;quot;file_404.py&amp;quot;, O_RDONLY) = 3
openat(AT_FDCWD, &amp;quot;/tmp/file_that_dosent_exist.csv&amp;quot;, O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, &amp;quot;/tmp/file_wrong_permission.csv&amp;quot;, O_RDONLY|O_CLOEXEC) = -1 EACCES (Permission denied)
&lt;/code>&lt;/pre>
&lt;p>Cool! With the &lt;code>strace&lt;/code> we are able to identify errors even when the programmer used a dangerous practice in the code.&lt;/p>
&lt;p>Ok, but let’s improve our output. We can filter the strace output redirecting into it the &lt;code>awk&lt;/code> (or &lt;code>grep&lt;/code>) and performing a conditional check that each line should start with the &lt;code>open&lt;/code> string and have the pattern &lt;code>= -1&lt;/code> in the line. The &lt;code>-1&lt;/code> means that the &lt;code>openat&lt;/code> SYS CALL had returned an error.&lt;/p>
&lt;pre>&lt;code class="language-bash">$ strace -f -e trace=file python file_404.py 2&amp;gt;&amp;amp;1 | awk '/^open/ &amp;amp;&amp;amp; /= -1/ {print}'
&lt;/code>&lt;/pre>
&lt;p>The output now will be simpler and easier to analyze:&lt;/p>
&lt;pre>&lt;code>openat(AT_FDCWD, &amp;quot;/home/devmessias/anaconda3/pyvenv.cfg&amp;quot;, O_RDONLY) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, &amp;quot;/tmp/arquivo_404.csv&amp;quot;, O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, &amp;quot;/tmp/arquivo_permission.csv&amp;quot;, O_RDONLY|O_CLOEXEC) = -1 EACCES (Permission denied)
&lt;/code>&lt;/pre>
&lt;p>If you are using the last versions of &lt;code>strace&lt;/code> (5.2&amp;gt;=) you can use a more simple command like this:&lt;/p>
&lt;pre>&lt;code class="language-bash">$ strace -f -e trace=openat -e status=failed python file_404.py
&lt;/code>&lt;/pre>
&lt;h3 id="is-this-process-using-a-cache-where-can-i-find-this-cache-which-configs-files-does-this-process-use">Is this process using a cache? Where can I find this cache? Which configs files does this process use?&lt;/h3>
&lt;p>It is a tedious task to search for cache or configs files used by a process and sometimes we need to delete these cache files. Another task that appears very often is to discover which files a process is using or if it is doing anything strange in your system. Maybe you want to discover if your python script is using the correct libs and files. For all these situations, you can use the following command:&lt;/p>
&lt;pre>&lt;code class="language-bash">$ strace -f -e trace=file command
&lt;/code>&lt;/pre>
&lt;p>If you want to get just the SYS CALLs that was perfomed succesfully do the next:&lt;/p>
&lt;pre>&lt;code class="language-bash">$ strace -f -e trace=file comando 2&amp;gt;&amp;amp;1 | awk '/^open/ &amp;amp;&amp;amp; !/= -1/ {print}'
&lt;/code>&lt;/pre>
&lt;p>In the above command the &lt;code>!&lt;/code> is as a negation parameter for the &lt;code>awk&lt;/code> search.&lt;/p>
&lt;p>Again, the new versions of strace allows the status flag:&lt;/p>
&lt;pre>&lt;code>$ strace -f -e trace=openat -e status=successful python file_404.py
&lt;/code>&lt;/pre>
&lt;h2 id="dissecting-your-database-system">Dissecting your database system&lt;/h2>
&lt;p>The &lt;code>strace&lt;/code> and &lt;code>lsof&lt;/code> are powerful tools to discover and solve bugs. You don’t need to believe me. Just check the number of bugs in MySQL that &lt;code>strace&lt;/code> was used to tackle
&lt;a href="http://mysqlentomologist.blogspot.com/2017/12/using-strace-for-mysql-troubleshooting.html" target="_blank" rel="noopener">“using strace for mysql troubleshooting&lt;/a>. Thus, it’s not a surprise that we can use &lt;code>strace&lt;/code> in our daily life dealing with databases.&lt;/p>
&lt;h3 id="is-this-process--well-behaved-how-many-connections-does-it-have">Is this process well behaved? How many connections does it have?&lt;/h3>
&lt;p>In MlOps or DevOps we always need to deal with database connections. Sometimes we must check if a process is closing these connections or is creating more than necessary. If these connections are made using the &lt;strong>TCP&lt;/strong> protocol you can list all established connections using the following command:&lt;/p>
&lt;pre>&lt;code class="language-bash">$ lsof -iTCP -sTCP:ESTABLISHED
&lt;/code>&lt;/pre>
&lt;p>As expected, we get a lot of unwanted information like website addresses and other application communications. If we want to list just the &lt;strong>TCP&lt;/strong> connection in a process, we must pass the &lt;strong>PID&lt;/strong> like this:&lt;/p>
&lt;pre>&lt;code class="language-bash">$ lsof -iTCP -sTCP:ESTABLISHED -p 22157
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
python 22157 devmessias 4u IPv4 9474517 0t0 TCP localhost:35932-&amp;gt;localhost:mysql (ESTABLISHED)
python 22157 devmessias 5u IPv4 9474518 0t0 TCP localhost:35934-&amp;gt;localhost:mysql (ESTABLISHED)
python 22157 devmessias 6u IPv4 9475529 0t0 TCP localhost:37048-&amp;gt;localhost:5000 (ESTABLISHED)
&lt;/code>&lt;/pre>
&lt;p>As can you see we also have some connections in our server that are not related to the &lt;code>mysql&lt;/code>. If we want to investigate just the &lt;code>mysql&lt;/code> connections between all the processes in our system just do:&lt;/p>
&lt;pre>&lt;code class="language-bash">$ lsof -iTCP:mysql -sTCP:ESTABLISHED
python 22157 devmessias 4u IPv4 9474517 0t0 TCP localhost:35932-&amp;gt;localhost:mysql (ESTABLISHED)
python 22157 devmessias 5u IPv4 9474518 0t0 TCP localhost:35934-&amp;gt;localhost:mysql (ESTABLISHED)
&lt;/code>&lt;/pre>
&lt;p>The process identified by &lt;em>22157&lt;/em> PID has two connections with our mysql server.&lt;/p>
&lt;p>Notice we have used a pattern in the &lt;code>-i&lt;/code> argument. This pattern follows this structure:&lt;/p>
&lt;pre>&lt;code class="language-bash">lsof -i[protocol][@hostname|hostaddr][:service|port]
&lt;/code>&lt;/pre>
&lt;h3 id="everything-is-working-proprely">Everything is working proprely?&lt;/h3>
&lt;p>Let’s give you a taste of what we can extract from the mysql service using &lt;code>strace&lt;/code> in order to get a comprehension about the processes.&lt;/p>
&lt;p>Get the PID of &lt;code>mysqld&lt;/code>&lt;/p>
&lt;pre>&lt;code class="language-bash">$ps aux | grep -i '[m]ysqld'
mysql 14001 1 0 13:41 ? 00:00:18 /usr/sbin/mysqld
&lt;/code>&lt;/pre>
&lt;p>We will ask the &lt;code>strace&lt;/code> to increase the size of the strings up to 50 characters (&lt;code>-s 50&lt;/code>) and we will omit any SYS CALL of the type &lt;code>io_getevents&lt;/code> , &lt;code>nanosleep&lt;/code> and &lt;code>futex&lt;/code>.&lt;/p>
&lt;pre>&lt;code class="language-bash">$ sudo strace -s 50 -f -e trace=!io_getevents,nanosleep,futex -p 10767
&lt;/code>&lt;/pre>
&lt;p>Chose one of your databases and tables to do the following examples. Here, I’ve perfomed this SQL query:&lt;/p>
&lt;pre>&lt;code class="language-sql">SELECT * FROM product WHERE product_id = 1;
&lt;/code>&lt;/pre>
&lt;p>My output prompted some stuff like this&lt;/p>
&lt;pre>&lt;code class="language-bash">[pid 14334] recvfrom(52, &amp;quot;,\0\0\0&amp;quot;, 4, MSG_DONTWAIT, NULL, NULL) = 4
[pid 14334] recvfrom(52, &amp;quot;\3SELECT * FROM product WHERE product_id = 1&amp;quot;, 44, MSG_DONTWAIT, NULL, NULL) = 44
[pid 14334] sendto(52, &amp;quot;\1\0\0\1\5F\0\0\2\3def\16farmers_market\7product\7product\nprodu&amp;quot;..., 477, MSG_DONTWAIT, NULL, 0 &amp;lt;unfinished ...&amp;gt;
[pid 14207] sched_yield( &amp;lt;unfinished ...&amp;gt;
[pid 14334] &amp;lt;... sendto resumed&amp;gt;) = 477
[pid 14207] &amp;lt;... sched_yield resumed&amp;gt;) = 0
...
&lt;/code>&lt;/pre>
&lt;p>We can see the SQL query above. This also shows how &lt;code>strace&lt;/code> can help us to gain a deep understanding about our system. We can see how the sql queries are comunicating using de &lt;code>recvfrom&lt;/code> and &lt;code>sendfrom&lt;/code> calls. The &lt;code>man 2 recvfrom&lt;/code> says the first number, 52, represents the file descriptor associated with a unix socket.&lt;/p>
&lt;p>We can use this approach to investigate $IO$ problems (
&lt;a href="https://newbiedba.wordpress.com/2017/01/04/using-strace-in-linux-to-troubleshoot-database-performance-issues/" target="_blank" rel="noopener">using-strace-in-linux-to-troubleshoot-database-performance-issues&lt;/a>) as well many others. But let’s simulate a lock condition and see what happens.&lt;/p>
&lt;p>Start a session and initiate any transaction. Don’t finish with a &lt;strong>COMMIT;&lt;/strong> command!&lt;/p>
&lt;pre>&lt;code># first session
MariaDB [you_db]&amp;gt; BEGIN;
Query OK, 0 rows affected (0.001 sec)
MariaDB [your_db]&amp;gt; UPDATE customer SET customer_first_name = 'something' WHERE customer_id=1;
Query OK, 0 rows affected (0.001 sec)
Rows matched: 1 Changed: 0 Warnings: 0
MariaDB [you_db]&amp;gt;
&lt;/code>&lt;/pre>
&lt;p>Looks in the &lt;code>strace&lt;/code> output, something like this should appear&lt;/p>
&lt;pre>&lt;code>[pid 14334] recvfrom(52, &amp;quot;I\0\0\0&amp;quot;, 4, MSG_DONTWAIT, NULL, NULL) = 4
[pid 14334] recvfrom(52, &amp;quot;\3UPDATE customer SET customer_first_name = 'Brun&amp;quot;..., 73, MSG_DONTWAIT, NULL, NULL) = 73
[pid 14334] sendto(52, &amp;quot;0\0\0\1\0\0\0\3\0\0\0(Rows matched: 1 Changed: 0 Warnings:&amp;quot;..., 52, MSG_DONTWAIT, NULL, 0) = 52
[pid 14334] recvfrom(52, 0x7fd354007348, 4, MSG_DONTWAIT, NULL, NULL) = -1 EAGAIN
[pid 14334] poll([{fd=52, events=POLLIN|POLLPRI}], 1, 28800000
&lt;/code>&lt;/pre>
&lt;p>The &lt;code>poll&lt;/code> is a system call that will wait for any change in the file descriptor 52. The process is waiting for the &lt;code>COMMIT;&lt;/code> clause in our first mysql session. Note the absence of the enclosing &lt;code>)&lt;/code> in the last line.&lt;/p>
&lt;p>Open another mysql session, try to execute the same SQL query (whitouth the BEGIN)&lt;/p>
&lt;pre>&lt;code># second session
MariaDB [your_db]&amp;gt; UPDATE customer SET customer_first_name = 'something' WHERE customer_id=1;
&lt;/code>&lt;/pre>
&lt;p>The db row it’s in a lock state. If we look in the &lt;code>strace&lt;/code> output just some new lines will be printed, like this&lt;/p>
&lt;pre>&lt;code> &amp;lt;unfinished ...&amp;gt;
[pid 29884] recvfrom(83, &amp;quot;I\0\0\0&amp;quot;, 4, MSG_DONTWAIT, NULL, NULL) = 4
[pid 29884] recvfrom(83, &amp;quot;\3UPDATE customer SET customer_first_name = 'someth&amp;quot;..., 73, MSG_DONTWAIT, NULL, NULL) = 73
&lt;/code>&lt;/pre>
&lt;p>Our second transction is waiting for the first to be commited in our db. If you perform a commit in the first session this will hapen in the &lt;code>strace&lt;/code> output:&lt;/p>
&lt;pre>&lt;code>[pid 14334] &amp;lt;... poll resumed&amp;gt;) = 1 ([{fd=52, revents=POLLIN}])
[pid 14334] recvfrom(52, &amp;quot;\7\0\0\0&amp;quot;, 4, MSG_DONTWAIT, NULL, NULL) = 4
[pid 14334] recvfrom(52, &amp;quot;\3COMMIT&amp;quot;, 7, MSG_DONTWAIT, NULL, NULL) = 7
...
&lt;/code>&lt;/pre>
&lt;p>Your first transaction was performed and the lock was released allowing the second transaction to be executed.&lt;/p>
&lt;h2 id="extras-related-to-files-proc-and-strace">Extras related to files (&lt;code>/proc/&lt;/code>) and &lt;code>strace&lt;/code>&lt;/h2>
&lt;p>I gave you some examples about connection issues, regular files accidents and database management. Here I’ll give more examples that I believe are not so useful although they are very interesting.&lt;/p>
&lt;h3 id="creating-a-sys-call-summary-what-does-my-program-do">Creating a SYS CALL summary: what does my program do?&lt;/h3>
&lt;p>An overview of what your program does can help you to perform some optimizations or discover something strange. We can use the &lt;code>strace -c&lt;/code> to get an overview of the system calls. For example, the following command gave me a summary of system calls of a &lt;code>make sync-env&lt;/code> that I’m using in one of my projects:&lt;/p>
&lt;pre>&lt;code class="language-bash">$ strace -c -e trace=!\wait4 make sync-env
&lt;/code>&lt;/pre>
&lt;p>The exclamation mark, &lt;code>-e trace=!\wait4&lt;/code>, in the above command tells &lt;code>strace&lt;/code> to ignore any &lt;code>wait4&lt;/code> system call.&lt;/p>
&lt;p>What I’ve obtained was this&lt;/p>
&lt;pre>&lt;code>% time seconds usecs/call calls errors syscall
------ ----------- ----------- --------- --------- ----------------
14,54 0,000209 6 33 13 openat
13,01 0,000187 17 11 vfork
12,32 0,000177 7 25 mmap
8,49 0,000122 3 31 close
8,42 0,000121 5 21 rt_sigprocmask
8,14 0,000117 6 17 read
6,89 0,000099 5 19 11 stat
5,85 0,000084 3 23 fstat
2,85 0,000041 8 5 mprotect
2,64 0,000038 9 4 write
2,51 0,000036 2 16 fcntl
2,02 0,000029 3 9 rt_sigaction
1,95 0,000028 14 2 readlink
1,95 0,000028 14 2 getdents64
1,25 0,000018 4 4 brk
1,25 0,000018 18 1 1 access
1,25 0,000018 3 5 pipe
1,11 0,000016 4 4 ioctl
0,84 0,000012 6 2 getcwd
0,70 0,000010 10 1 munmap
0,49 0,000007 7 1 lstat
0,49 0,000007 7 1 execve
0,49 0,000007 3 2 prlimit64
0,35 0,000005 5 1 chdir
0,21 0,000003 3 1 arch_prctl
------ ----------- ----------- --------- --------- ----------------
100.00 0,001437 241 25 total
&lt;/code>&lt;/pre>
&lt;p>What can we extract from the above output? A lot of things. For example &lt;code>make sync-env&lt;/code> spent 14% of the time doing system calls of the type &lt;code>opennat&lt;/code> and 20 of these 33 &lt;code>openat&lt;/code> calls had some problem.&lt;/p>
&lt;h3 id="did-this-process-start-with-the-correct-environment-variables">Did this process start with the correct environment variables?&lt;/h3>
&lt;p>We have several reasons to use environment variables. These variables are easy to configure, improve security, and prevent errors. So they are used everywhere to store a secret, point to a lib and much more. However, sometimes we are not so sure whether a process is using the correct environment variables or not.&lt;/p>
&lt;p>Let’s try something simple&lt;/p>
&lt;pre>&lt;code class="language-bash">$ ANSWER=42 python script.py
&lt;/code>&lt;/pre>
&lt;p>As I said previously the &lt;code>/proc&lt;/code> is responsible for storing the state of any process running in your machine. So, it’s not a surprise that we can extract the environment variables from that.&lt;/p>
&lt;p>To print the environment variables of the process with a PID &lt;code>4301&lt;/code> just call this &lt;code>cat /proc/4031/environ&lt;/code> and get an ugly output. To improve the output we can use the &lt;code>tr&lt;/code> and replace the null characters &lt;code>\0&lt;/code> by break lines &lt;code>\n&lt;/code>. Like this:&lt;/p>
&lt;pre>&lt;code class="language-bash">$ tr '\0' '\n' &amp;lt; /proc/4031/environ
&lt;/code>&lt;/pre>
&lt;p>You will have a output similar to this&lt;/p>
&lt;pre>&lt;code>ANSWER=42
SHELL=/bin/bash
LANGUAGE=en_US
JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/bin/java
...more stuff
&lt;/code>&lt;/pre>
&lt;p>If you want to look just at the environment variables with a given string pattern you can use &lt;code>awk&lt;/code> , &lt;code>grep&lt;/code>, or anything that you feel more comfortable. For example, doing this&lt;/p>
&lt;pre>&lt;code class="language-bash">$ tr '\0' '\n' &amp;lt; /proc/4031/environ 2&amp;gt;&amp;amp;1 | awk '/^CONDA/ {print}'
&lt;/code>&lt;/pre>
&lt;p>I’ve obtained this&lt;/p>
&lt;pre>&lt;code>CONDA_EXE=/home/devmessias/anaconda3/bin/conda
CONDA_PREFIX=/home/devmessias/anaconda3
CONDA_PROMPT_MODIFIER=(base)
CONDA_SHLVL=1
CONDA_PYTHON_EXE=/home/devmessias/anaconda3/bin/python
CONDA_DEFAULT_ENV=base
&lt;/code>&lt;/pre>
&lt;h3 id="i-forgot-to-redirect-the-outputs-what-can-i-do-now">I forgot to redirect the outputs! What can I do now?&lt;/h3>
&lt;p>Suppose you started a process without redirecting the output to a file. Maybe you forgot or you are too optimistic about the problems and now you want to persist the errors. If restart the process it’s out of question you can use the &lt;code>strace&lt;/code> to solve your headache. Let’s see how we can solve that.&lt;/p>
&lt;p>The system calls responsible to request the kernel to write in the &lt;strong>stdin, stdout&lt;/strong> and &lt;strong>stderr&lt;/strong> is the &lt;code>write&lt;/code> . If you want to know more you should read the manual&lt;/p>
&lt;pre>&lt;code class="language-bash">$ man 2 write
&lt;/code>&lt;/pre>
&lt;p>But the most important part of the &lt;code>write&lt;/code> manual is on the top and is this:&lt;/p>
&lt;pre>&lt;code>NAME
write - write to a file descriptor
SYNOPSIS
#include &amp;lt;unistd.h&amp;gt;
ssize_t write(int fd, const void *buf, size_t count);
&lt;/code>&lt;/pre>
&lt;p>As you can see the first argument is an integer that represents the file descriptor. If &lt;strong>fd=1&lt;/strong> this means a writing in the &lt;strong>stdout&lt;/strong> and if &lt;strong>fd=2&lt;/strong> the writing will be in the &lt;strong>stderr&lt;/strong>. So, it’s an easy piece here. We just need to monitor any sys call &lt;code>write&lt;/code> with the &lt;code>fd&lt;/code> equals to $1$ or $2$ and save the values in a file.&lt;/p>
&lt;p>When I need to do this (two or three times in my life time) I use the following pattern&lt;/p>
&lt;pre>&lt;code class="language-bash">$ strace -f -t -etrace=write -s 1000 -p 4320 2&amp;gt;&amp;amp;1 | grep --line-buffered -e 'write(2, ' -e 'write(1, ' &amp;gt; out.txt
&lt;/code>&lt;/pre>
&lt;p>I’m asking &lt;code>strace&lt;/code> to monitor any SYS CALL &lt;code>write&lt;/code> from the process with the PID &lt;code>4320&lt;/code> or children created by them (&lt;code>-f&lt;/code>) . And saving the output in the &lt;code>out.txt&lt;/code> file.&lt;/p>
&lt;p>The following code changes the &lt;code>server_mlops.py&lt;/code> to help you to explore more this scenario.&lt;/p>
&lt;pre>&lt;code class="language-python"># server_mlops.py
import time
import flask
import sys
app = flask.Flask(__name__)
@app.route('/')
def hello_world():
sleep_time = flask.request.args.get('sleep', default=10, type=int)
print('sleep_time:', sleep_time)
for i in range(sleep_time):
print(f'INFO: {i} of sleep_time \n asdf \t ')
print(f'ERROR: Example msg {i}', file=sys.stderr)
time.sleep(1)
return 'Hello World!'
if __name__ == '__main__':
app.run()
&lt;/code>&lt;/pre>
&lt;h3 id="how-this-program-has-been-called-what-is-the-working-dir-of-the-process">How this program has been called? What is the working dir of the process?&lt;/h3>
&lt;p>Ok, you can answer these questions using &lt;code>htop&lt;/code>. However we can get the same information without installing anything, just looking in a file inside of the &lt;code>/proc/&lt;/code> folder, like this&lt;/p>
&lt;pre>&lt;code class="language-bash">$ tr '\0' '\t' &amp;lt; /proc/A_PID_NUMBER/cmdline
&lt;/code>&lt;/pre>
&lt;p>In my case I’ve obtined this&lt;/p>
&lt;pre>&lt;code>python client.py --sleep 1000
&lt;/code>&lt;/pre>
&lt;p>To discover the working directory do this&lt;/p>
&lt;pre>&lt;code class="language-bash">$ readlink /proc/A_PID_NUMBER/cwd
&lt;/code>&lt;/pre>
&lt;h2 id="conclusion--suggestions">Conclusion &amp;amp; Suggestions&lt;/h2>
&lt;p>I hope that after reading this post you can be more prepared to face problems in your daily tasks. But if you have any suggestion you can send me an email
&lt;a href="devmessias@gmail.com">devmessias@gmail.com&lt;/a>. Thanks!&lt;/p>
&lt;p>If you want to know more about &lt;code>strace &lt;/code> and linux in general I strongly recommend spent some hours navigating and reading Julia Evans’ blog
&lt;a href="https://jvns.ca/" target="_blank" rel="noopener">https://jvns.ca/&lt;/a>.&lt;/p></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><item><title>Helios: graph layout viz and streaming</title><link>/project/helios/</link><pubDate>Mon, 13 Sep 2021 17:43:22 +0000</pubDate><guid>/project/helios/</guid><description>&lt;a href="https://github.com/fury-gl/helios">
Helios repo
&lt;/a>
&lt;p>Helios is a Python library aiming to provide an easy way to visualize huge networks dynamically. Helios also provides visualizations through an interactive Stadia-like streaming system in which users can be collaboratively access (and share) visualizations created in a server or through Jupyter Notebook/Lab environments. It incorporates state-of-the-art layout algorithms and optimized rendering techniques (powered by
&lt;a href="https://github.com/fury-gl/" target="_blank" rel="noopener">FURY&lt;/a>).&lt;/p>
&lt;p>&lt;img src="https://user-images.githubusercontent.com/6979335/125310065-a3a9f480-e308-11eb-98d9-0ff5406a0e96.gif" alt="">&lt;/p>
&lt;center>&lt;img src="https://user-images.githubusercontent.com/6979335/126175583-c7d85f0a-3d0c-400e-bbdd-4cbcd2a36fed.gif" alt="..." height="300"/>&lt;/center>
&lt;p align="center">
&lt;a href="#general-information">General Information&lt;/a> •
&lt;a href="#key-features">Key Features&lt;/a> •
&lt;a href="#installation">Installation&lt;/a> •
&lt;a href="#how-to-use">Usage&lt;/a> •
&lt;a href="#history">History&lt;/a> •
&lt;a href="#credits">Credits&lt;/a>
&lt;/p>
&lt;h1 id="general-information">General Information&lt;/h1>
&lt;ul>
&lt;li>&lt;strong>Website and Documentation:&lt;/strong>
&lt;a href="https://heliosnetwork.io/" target="_blank" rel="noopener">https://heliosnetwork.io/&lt;/a>&lt;/li>
&lt;li>&lt;strong>Examples:&lt;/strong>
&lt;a href="https://heliosnetwork.io/examples_gallery/index.html" target="_blank" rel="noopener">https://heliosnetwork.io/examples_gallery/index.html&lt;/a>&lt;/li>
&lt;li>&lt;strong>Blog:&lt;/strong>
&lt;a href="https://heliosnetwork.io/blog.html" target="_blank" rel="noopener">https://heliosnetwork.io/blog.html&lt;/a>&lt;/li>
&lt;li>&lt;strong>Free software:&lt;/strong> MIT license&lt;/li>
&lt;li>&lt;strong>Community:&lt;/strong> Come to chat on
&lt;a href="https://discord.gg/6btFPPj" target="_blank" rel="noopener">Discord&lt;/a>&lt;/li>
&lt;/ul>
&lt;h1 id="key-features">Key Features&lt;/h1>
&lt;ul>
&lt;li>Force-directed layout using octrees&lt;/li>
&lt;li>Minimum-distortion embeddings&lt;/li>
&lt;li>ForceAtlas2 using cugraph&lt;/li>
&lt;li>Interactive local and Remote rendering in Jupyter Notebooks&lt;/li>
&lt;li>WebRTC or MJPEG interactive streaming system&lt;/li>
&lt;/ul>
&lt;h1 id="installation">Installation&lt;/h1>
&lt;p>Use pip install pointed to this repository:&lt;/p>
&lt;pre>&lt;code>pip git+https://github.com/fury-gl/helios.git
&lt;/code>&lt;/pre>
&lt;p>As an alternative, Helios can be installed from the source code through the following steps:&lt;/p>
&lt;ul>
&lt;li>
&lt;p>&lt;strong>Step 1.&lt;/strong> Get the latest source by cloning this repo:&lt;/p>
&lt;pre>&lt;code>git clone https://github.com/fury-gl/helios.git
&lt;/code>&lt;/pre>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Step 2.&lt;/strong> Install requirements:&lt;/p>
&lt;pre>&lt;code>pip install -r requirements.txt
&lt;/code>&lt;/pre>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Step 3.&lt;/strong> Install Helios&lt;/p>
&lt;p>As a
&lt;a href="https://pip.pypa.io/en/stable/reference/pip_install/#id44" target="_blank" rel="noopener">local project installation&lt;/a> using:&lt;/p>
&lt;pre>&lt;code> pip install .
&lt;/code>&lt;/pre>
&lt;p>Or as an
&lt;a href="https://pip.pypa.io/en/stable/reference/pip_install/#id44" target="_blank" rel="noopener">&amp;ldquo;editable&amp;rdquo; installation&lt;/a> using:&lt;/p>
&lt;pre>&lt;code> pip install -e .
&lt;/code>&lt;/pre>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Step 4:&lt;/strong> Enjoy!&lt;/p>
&lt;/li>
&lt;/ul>
&lt;p>For more information, see also
&lt;a href="https://heliosnetwork.io/latest/installation.html" target="_blank" rel="noopener">installation page on heliosnetwork.io&lt;/a>&lt;/p>
&lt;h2 id="dependencies">Dependencies&lt;/h2>
&lt;p>Helios requires Python 3.7+ and the following mandatory dependencies:&lt;/p>
&lt;ul>
&lt;li>numpy &amp;gt;= 1.7.1&lt;/li>
&lt;li>vtk &amp;gt;= 8.1.0&lt;/li>
&lt;li>fury&lt;/li>
&lt;/ul>
&lt;p>To enable WebRTC streaming and enable optimizations to the streaming system, install the following optional packages:&lt;/p>
&lt;ul>
&lt;li>
&lt;p>Required for WebRTC streaming&lt;/p>
&lt;ul>
&lt;li>aiohttp&lt;/li>
&lt;li>aiortc&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>
&lt;p>Optional packages that may improve performance&lt;/p>
&lt;ul>
&lt;li>cython&lt;/li>
&lt;li>opencv&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ul>
&lt;h2 id="testing">Testing&lt;/h2>
&lt;p>After installation, you can install test suite requirements:&lt;/p>
&lt;pre>&lt;code>pip install -r requirements_dev.txt
&lt;/code>&lt;/pre>
&lt;p>And to launch test suite:&lt;/p>
&lt;pre>&lt;code>pytest -svv helios
&lt;/code>&lt;/pre>
&lt;h1 id="usage">Usage&lt;/h1>
&lt;p>There are many ways to start using Helios:&lt;/p>
&lt;ul>
&lt;li>Go to
&lt;a href="https://heliosnetwork.io/getting_started.html" target="_blank" rel="noopener">Getting Started&lt;/a>&lt;/li>
&lt;li>Explore our
&lt;a href="https://heliosnetwork.io/examples_gallery/index.html" target="_blank" rel="noopener">Examples&lt;/a> or
&lt;a href="https://heliosnetwork.io/latest/auto_examples/index.htmlhttps://heliosnetwork.io/api.html" target="_blank" rel="noopener">API&lt;/a>.&lt;/li>
&lt;/ul>
&lt;p>Example usage:&lt;/p>
&lt;pre>&lt;code class="language-python"> from helios import NetworkDraw
from helios.layouts import HeliosFr
import numpy as np
vertex_count = 8
edges = np.array([
[0,1],
[0,2],
[1,2],
[2,3],
[3,4],
[3,5],
[4,5],
[5,6],
[6,7],
[7,0]
]);
centers = np.random.normal(size=(vertex_count, 3))
network_draw = NetworkDraw(
positions=centers,
edges=edges,
colors=(0.25,0.25,0.25),
scales=1,
node_edge_width=0,
marker='s',
edge_line_color=(0.5,0.5,0.5),
window_size=(600, 600)
)
layout = HeliosFr(edges, network_draw)
layout.start()
network_draw.showm.initialize()
network_draw.showm.start()
&lt;/code>&lt;/pre>
&lt;h1 id="history">History&lt;/h1>
&lt;p>Helios project started as a replacement to the desktop version of the
&lt;a href="https://filipinascimento.github.io/networks3d/" target="_blank" rel="noopener">Networks 3D&lt;/a> tools. The project evolved quickly along the summer of 2021 due to the GSoC’21 under the responsibility of the Python Software Foundation and the FURY team. The majority of the initial work has been done by
&lt;a href="https://github.com/devmessias" target="_blank" rel="noopener">@devmessias&lt;/a> mentored by
&lt;a href="https://github.com/filipinascimento" target="_blank" rel="noopener">@filipinascimento&lt;/a> and
&lt;a href="https://github.com/skoudoro" target="_blank" rel="noopener">@skoudoro&lt;/a>. The GSoC’21 project associated with Helios is “A system for collaborative visualization of large network layouts using FURY”. Check out the
&lt;a href="https://gist.github.com/devmessias/1cb802efb0a094686c129259498710b3" target="_blank" rel="noopener">final report&lt;/a> for more information.&lt;/p></description></item><item><title>GSoC- Google Summer of Code 2021 Final Work Product</title><link>/post/2021-23-08-gsoc-devmessias-final-report/2021-23-08-gsoc-devmessias-final-report/</link><pubDate>Mon, 23 Aug 2021 00:00:00 +0000</pubDate><guid>/post/2021-23-08-gsoc-devmessias-final-report/2021-23-08-gsoc-devmessias-final-report/</guid><description>&lt;blockquote>
&lt;p>Detailed weekly tasks, progress and work done can be found
&lt;a href="https://blogs.python-gsoc.org/en/demvessiass-blog/google-summer-of-code-final-work-product-3/" target="_blank" rel="noopener">here&lt;/a>&lt;/p>
&lt;/blockquote>
&lt;h2 id="abstract">Abstract&lt;/h2>
&lt;p>We have changed some points of my project in the first meeting.
Specifically, we focused the efforts into developing a streaming system
using the WebRTC protocol that could be used in more generic scenarios
than just the network visualization. In addition to that, we have opted
to develop the network visualization for fury as a separated repository
and package available
&lt;a href="https://github.com/fury-gl/helios" target="_blank" rel="noopener">here&lt;/a>. The
name Helios was selected for this new network visualization system based
on the Fury rendering pipeline.&lt;/p>
&lt;h2 id="proposed-objectives">Proposed Objectives&lt;/h2>
&lt;ul>
&lt;li>Create a streaming system (stadia-like) for FURY
&lt;ul>
&lt;li>Should work in a low-bandwidth scenario&lt;/li>
&lt;li>Should allow user interactions and collaboration across the
Internet using a web-browser&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>Helios Network System objectives:
&lt;ul>
&lt;li>Implement the Force-Directed Algorithm with examples&lt;/li>
&lt;li>Implement the ForceAtlas2 algorithm using cugraph with examples&lt;/li>
&lt;li>Implement Minimum-Distortion Embeddings algorithm (PyMDE) and
examples&lt;/li>
&lt;li>Non-blocking network algorithms computation avoiding the GIL
using the Shared Memory approach&lt;/li>
&lt;li>Create the documentation and the actions for the CI&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>Stretch Goals:
&lt;ul>
&lt;li>Create an actor in FURY to draw text efficiently using shaders&lt;/li>
&lt;li>Add support to draw millions of nodes using FURY&lt;/li>
&lt;li>Add support to control the opengl state on FURY&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ul>
&lt;h2 id="objectives-completed">Objectives Completed&lt;/h2>
&lt;ul>
&lt;li>
&lt;p>&lt;strong>Create a streaming system (stadia-like) for FURY&lt;/strong>&lt;/p>
&lt;p>There are several reasons to have a streaming system for data
visualization. Because I am doing my Ph.D. in developing country, I
always need to think of the less expensive solutions to use the
computational resources available. For example, with the GPU&amp;rsquo;s
prices increasing, it is necessary to share the a single machine
with GPU with other users at different locations.&lt;/p>
&lt;p>To construct the streaming system for my project we have opted to
follow three main properties and behaviors:&lt;/p>
&lt;ol>
&lt;li>avoid blocking the code execution in the main thread (where the
vtk/fury instance resides)&lt;/li>
&lt;li>work inside of a low bandwidth environment&lt;/li>
&lt;li>make it easy and cheap to share the rendering result. For
example, using the free version of &lt;code>ngrok&lt;/code>&lt;/li>
&lt;/ol>
&lt;p>To achieve the first property we need to circumvent the GIL and
allow python code to execute in parallel. Using the threading module
alone is not good enough to reach real parallelism as Python calls
in the same process can not execute concurrently. In addition to
that, to achieve better organization it is desirable to define the
server system as an uncoupled module from the rendering pipeline.
Therefore, I have chosen to employ the multiprocessing approach for
that. The second and third property can be only achieved choosing a
suitable protocol for transfering the rendered results to the
client. We have opted to implement two streaming protocols: the
MJPEG and the WebRTC. The latter is more suitable for low-bandwidth
scenarios [1].&lt;/p>
&lt;p>The image below shows a simple representation of the streaming
system.&lt;/p>
&lt;pre>&lt;code class="language-{=html}">&amp;lt;center&amp;gt;
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-{=html}">&amp;lt;/center&amp;gt;
&lt;/code>&lt;/pre>
&lt;p>The video below shows how our streaming system works smothly and can
be easily integrated inside of a Jupyter notebook.&lt;/p>
&lt;/li>
&lt;/ul>
&lt;p>
&lt;a href="https://user-images.githubusercontent.com/6979335/130284952-2ffbf117-7119-4048-b7aa-428e0162fb7a.mp4" target="_blank" rel="noopener">Video: WebRTC Streaming +
Ngrok&lt;/a>&lt;/p>
&lt;p>
&lt;a href="https://user-images.githubusercontent.com/6979335/130284261-20e84622-427e-4a59-a46f-6a33f5473025.mp4" target="_blank" rel="noopener">Video: WebRTC Streaming +
Jupyter&lt;/a>&lt;/p>
&lt;p>&lt;em>Pull Requests:&lt;/em> *
&lt;a href="https://github.com/fury-gl/fury/pull/480" target="_blank" rel="noopener">https://github.com/fury-gl/fury/pull/480&lt;/a>&lt;/p>
&lt;ul>
&lt;li>
&lt;p>&lt;strong>2D and 3D marker actor&lt;/strong>&lt;/p>
&lt;p>This feature gave FURY the ability to efficiently draw millions of
markers and impostor 3D spheres. This feature was essential for the
development of Helios. This feature work with signed distance fields
(SDFs) you can get more information about how SDFs works here [4]
.&lt;/p>
&lt;p>The image below shows 1 million of markers rendered using an Intel
HD graphics 3000.&lt;/p>
&lt;/li>
&lt;/ul>
&lt;p>&lt;img src="https://user-images.githubusercontent.com/6979335/116004971-70927780-a5db-11eb-8363-8c0757574eb4.png" alt="image1">&lt;/p>
&lt;ul>
&lt;li>
&lt;p>&lt;strong>Fine-Tunning the OpenGl State&lt;/strong>&lt;/p>
&lt;p>Sometimes users may need to have finer control on how OpenGL will
render the actors. This can be useful when they need to create
specialized visualization effects or to improve the performance.&lt;/p>
&lt;p>In this PR I have worked in a feature that allows FURY to control
the OpenGL context created by VTK&lt;/p>
&lt;p>&lt;em>Pull Request:&lt;/em>&lt;/p>
&lt;ul>
&lt;li>
&lt;a href="https://github.com/fury-gl/fury/pull/432" target="_blank" rel="noopener">https://github.com/fury-gl/fury/pull/432&lt;/a>&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Helios Network Visualization Lib: Network Layout Algorithms&lt;/strong>&lt;/p>
&lt;p>&lt;strong>Case 1:&lt;/strong> Suppose that you need to monitor a hashtag and build a
social graph. You want to interact with the graph and at the same
time get insights about the structure of the user interactions. To
get those insights you can perform a node embedding using any kind
of network layout algorithm, such as force-directed or minimum
distortion embeddings.&lt;/p>
&lt;p>&lt;strong>Case 2:&lt;/strong> Suppose that you are modelling a network dynamic such as
an epidemic spreading or a Kuramoto model. In some of those network
dynamics a node can change the state and the edges related to the
node must be deleted. For example, in an epidemic model a node can
represent a person who died due to a disease. Consequently, the
layout of the network must be recomputed to give better insights.&lt;/p>
&lt;p>In the described cases, if we want a better (UX) and at the same
time a more practical and insightful application of Helios, the
employed layout algorithms should not block any kind of computation
in the main thread.&lt;/p>
&lt;p>In Helios we already have a lib written in C (with a python wrapper)
which performs the force-directed layout algorithm using separated
threads avoiding the GIL problem and consequently avoiding blocking
the main thread. But what about the other open-source network layout
libs available on the internet? Unfortunately, most of those libs
have not been implemented like Helios force-directed methods and
consequently, if we want to update the network layout the Python
interpreter will block the computation and user interaction in your
network visualization.&lt;/p>
&lt;p>My solution for having PyMDE and CuGraph-ForceAtlas not blocking the
main thread was to break the network layout method into two
different types of processes: A and B and communicate both process
using the Shared Memory approach. You can more information about
this PR through my following posts [2], [3].&lt;/p>
&lt;/li>
&lt;/ul>
&lt;p>The image below show an example that I made and is available at
&lt;a href="https://github.com/fury-gl/helios/blob/main/docs/examples/viz_mde.py" target="_blank" rel="noopener">https://github.com/fury-gl/helios/blob/main/docs/examples/viz_mde.py&lt;/a>&lt;/p>
&lt;p>&lt;img src="https://user-images.githubusercontent.com/6979335/125310065-a3a9f480-e308-11eb-98d9-0ff5406a0e96.gif" alt="image2">
&lt;em>Pull Requests:&lt;/em>&lt;/p>
&lt;ul>
&lt;li>&lt;strong>MDE Layout:&lt;/strong>
&lt;a href="https://github.com/fury-gl/helios/pull/6" target="_blank" rel="noopener">https://github.com/fury-gl/helios/pull/6&lt;/a>&lt;/li>
&lt;li>&lt;strong>CuGraph ForceAtlas2&lt;/strong>
&lt;a href="https://github.com/fury-gl/helios/pull/13" target="_blank" rel="noopener">https://github.com/fury-gl/helios/pull/13&lt;/a>&lt;/li>
&lt;li>&lt;strong>Force-Directed and MDE improvements&lt;/strong>
&lt;a href="https://github.com/fury-gl/helios/pull/14" target="_blank" rel="noopener">https://github.com/fury-gl/helios/pull/14&lt;/a>&lt;/li>
&lt;li>&lt;strong>Helios Network Visualization Lib: Visual Aspects&lt;/strong>&lt;/li>
&lt;/ul>
&lt;p>I&amp;rsquo;ve made several stuffs to give Helios a better visual aspects. One of
them was to give a smooth real-time network layout animations. Because
the layout computations happens into a different process that the
process responsible to render the network was necessary to record the
positions and communicate the state of layout between both process.&lt;/p>
&lt;p>The GIF below shows how the network layout through IPC behaved before
these modification&lt;/p>
&lt;pre>&lt;code class="language-{=html}">&amp;lt;center&amp;gt;
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-{=html}">&amp;lt;/center&amp;gt;
&lt;/code>&lt;/pre>
&lt;p>below, you can see how after those modifications the visual aspect is
better.&lt;/p>
&lt;pre>&lt;code class="language-{=html}">&amp;lt;center&amp;gt;
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-{=html}">&amp;lt;/center&amp;gt;
&lt;/code>&lt;/pre>
&lt;p>&lt;em>Pull Requests:&lt;/em>&lt;/p>
&lt;ul>
&lt;li>&lt;strong>OpenGL SuperActors:&lt;/strong>
&lt;a href="https://github.com/fury-gl/helios/pull/1" target="_blank" rel="noopener">https://github.com/fury-gl/helios/pull/1&lt;/a>&lt;/li>
&lt;li>&lt;strong>Fixed the flickering effect&lt;/strong>
&lt;a href="https://github.com/fury-gl/helios/pull/10" target="_blank" rel="noopener">https://github.com/fury-gl/helios/pull/10&lt;/a>&lt;/li>
&lt;li>&lt;strong>Improvements in the network node visual aspects&lt;/strong>
&lt;a href="https://github.com/fury-gl/helios/pull/15" target="_blank" rel="noopener">https://github.com/fury-gl/helios/pull/15&lt;/a>&lt;/li>
&lt;li>&lt;strong>Smooth animations when using IPC layouts&lt;/strong>
&lt;a href="https://github.com/fury-gl/helios/pull/17" target="_blank" rel="noopener">https://github.com/fury-gl/helios/pull/17&lt;/a>&lt;/li>
&lt;li>&lt;strong>Helios Network Visualization Lib: CI and Documentation&lt;/strong>&lt;/li>
&lt;/ul>
&lt;p>Because Helios was an project that begins in my GSoC project It was
necessary to create the documentation, hosting and more. Now we have a
online documentation available at
&lt;a href="https://heliosnetwork.io/" target="_blank" rel="noopener">https://heliosnetwork.io/&lt;/a> altough
the documentation still need some improvements.&lt;/p>
&lt;p>Below is presented the Helios Logo which was developed by my mentor
Filipi Nascimento.&lt;/p>
&lt;pre>&lt;code class="language-{=html}">&amp;lt;center&amp;gt;
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-{=html}">&amp;lt;/center&amp;gt;
&lt;/code>&lt;/pre>
&lt;p>&lt;em>Pull Requests:&lt;/em>&lt;/p>
&lt;ul>
&lt;li>
&lt;p>&lt;strong>CI and pytests:&lt;/strong>
&lt;a href="https://github.com/fury-gl/helios/pull/5" target="_blank" rel="noopener">https://github.com/fury-gl/helios/pull/5&lt;/a>,
&lt;a href="https://github.com/fury-gl/helios/pull/20" target="_blank" rel="noopener">https://github.com/fury-gl/helios/pull/20&lt;/a>&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Helios Logo, Sphinx Gallery and API documentation&lt;/strong>
&lt;a href="https://github.com/fury-gl/helios/pull/18" target="_blank" rel="noopener">https://github.com/fury-gl/helios/pull/18&lt;/a>&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Documentation improvements:&lt;/strong>
&lt;a href="https://github.com/fury-gl/helios/pull/8" target="_blank" rel="noopener">https://github.com/fury-gl/helios/pull/8&lt;/a>&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Objectives in Progress&lt;/strong>&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Draw texts on FURY and Helios&lt;/strong>&lt;/p>
&lt;p>This two PRs allows FURY and Helios to draw millions of characters
in VTK windows instance with low computational resources
consumptions. I still working on that, finishing the SDF font
rendering which the theory behinds was developed here [5].&lt;/p>
&lt;p>&lt;em>Pull Requests:&lt;/em>&lt;/p>
&lt;ul>
&lt;li>
&lt;p>
&lt;a href="https://github.com/fury-gl/helios/pull/24" target="_blank" rel="noopener">https://github.com/fury-gl/helios/pull/24&lt;/a>&lt;/p>
&lt;/li>
&lt;li>
&lt;p>
&lt;a href="https://github.com/fury-gl/fury/pull/489" target="_blank" rel="noopener">https://github.com/fury-gl/fury/pull/489&lt;/a>&lt;/p>
&lt;pre>&lt;code class="language-{=html}">&amp;lt;center&amp;gt;
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-{=html}">&amp;lt;/center&amp;gt;
&lt;/code>&lt;/pre>
&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>GSoC weekly Blogs&lt;/strong>&lt;/p>
&lt;p>Weekly blogs were added to the FURY Website.&lt;/p>
&lt;p>&lt;em>Pull Requests:&lt;/em>&lt;/p>
&lt;ul>
&lt;li>&lt;strong>First Evaluation:&lt;/strong>
&lt;a href="https://github.com/fury-gl/fury/pull/476" target="_blank" rel="noopener">https://github.com/fury-gl/fury/pull/476&lt;/a>&lt;/li>
&lt;li>&lt;strong>Second Evaluation:&lt;/strong> TBD&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ul>
&lt;h3 id="references">References&lt;/h3>
&lt;p>[1] ( Python GSoC - Post #1 - A Stadia-like system for data
visualization - demvessias s Blog, n.d.;
&lt;a href="https://blogs.python-gsoc.org/en/demvessiass-blog/post-1-a-stadia-like-system-for-data-visualization/" target="_blank" rel="noopener">https://blogs.python-gsoc.org/en/demvessiass-blog/post-1-a-stadia-like-system-for-data-visualization/&lt;/a>&lt;/p>
&lt;p>[2] Python GSoC - Post #2: SOLID, monkey patching a python issue and
network layouts through WebRTC - demvessias s Blog, n.d.;
&lt;a href="https://blogs.python-gsoc.org/en/demvessiass-blog/post-2-solid-monkey-patching-a-python-issue-and-network-layouts-through-webrtc/" target="_blank" rel="noopener">https://blogs.python-gsoc.org/en/demvessiass-blog/post-2-solid-monkey-patching-a-python-issue-and-network-layouts-through-webrtc/&lt;/a>&lt;/p>
&lt;p>[3] Python GSoC - Post #3: Network layout algorithms using IPC
-demvessias s Blog,
n.d.)
&lt;a href="https://blogs.python-gsoc.org/en/demvessiass-blog/post-3-network-layout-algorithms-using-ipc/" target="_blank" rel="noopener">https://blogs.python-gsoc.org/en/demvessiass-blog/post-3-network-layout-algorithms-using-ipc/&lt;/a>&lt;/p>
&lt;p>[4] Rougier, N.P., 2018. An open access book on Python, OpenGL and
Scientific Visualization [WWW Document]. An open access book on
Python, OpenGL and Scientific Visualization. URL
&lt;a href="https://github.com/rougier/python-opengl" target="_blank" rel="noopener">https://github.com/rougier/python-opengl&lt;/a> (accessed 8.21.21).&lt;/p>
&lt;p>[5] Green, C., 2007. Improved alpha-tested magnification for vector
textures and special effects, in: ACM SIGGRAPH 2007 Courses on -SIGGRAPH
&amp;lsquo;07. Presented at the ACM SIGGRAPH 2007 courses, ACM Press, San Diego,
California, p. 9.
&lt;a href="https://doi.org/10.1145/1281500.1281665" target="_blank" rel="noopener">https://doi.org/10.1145/1281500.1281665&lt;/a>&lt;/p></description></item><item><title>GSoC- SDF fonts and OpenGL</title><link>/post/2021-16-08-gsoc-devmessias-11/2021-16-08-gsoc-devmessias-11/</link><pubDate>Mon, 16 Aug 2021 00:00:00 +0000</pubDate><guid>/post/2021-16-08-gsoc-devmessias-11/2021-16-08-gsoc-devmessias-11/</guid><description>&lt;h1 id="what-did-i-do-this-week">What did I do this week?&lt;/h1>
&lt;h2 id="fury">FURY&lt;/h2>
&lt;ul>
&lt;li>
&lt;a href="https://github.com/fury-gl/fury/pull/489" target="_blank" rel="noopener">PR fury-gl/fury#489:&lt;/a>&lt;/li>
&lt;/ul>
&lt;p>| I&amp;rsquo;ve created the PR that will allow FURY to draw hundreds thousands of
labels using texture maps. By default, this PR give to FURY three
pre-built texture maps using different fonts. However, is quite easy
to create new fonts to be used in a visualization.
| It&amp;rsquo;s was quite hard to develop the shader code and find the correct
positions of the texture maps to be used in the shader. Because we
used the freetype-py to generate the texture and packing the glyps.
However, the lib has some examples with bugs. But fortunelly, now
everthing is woking on FURY. I&amp;rsquo;ve also created two different examples
to show how this PR works.&lt;/p>
&lt;pre>&lt;code>*
The first example, viz_huge_amount_of_labels.py, shows that feature has a realy good performance. The user can
draw hundreds of thounsands of characters in a regular computer.
![](https://user-images.githubusercontent.com/6979335/129643743-6cb12c06-3415-4a02-ba43-ccc97003b02d.png)
* The second example, viz_billboad_labels.py, shows the different behaviors of the label actor. In addition, presents
to the user how to create a new texture atlas font to be used across different visualizations.
&lt;/code>&lt;/pre>
&lt;ul>
&lt;li>
&lt;a href="https://github.com/fury-gl/fury/pull/437" target="_blank" rel="noopener">PR fury-gl/fury#437:&lt;/a>
&lt;ul>
&lt;li>
&lt;p>&lt;strong>Fix: avoid multiple OpenGl context on windows using asyncio&lt;/strong>&lt;/p>
&lt;pre>&lt;code>The streaming system must be generic, but opengl and vtk behaves in uniques ways in each Operating System. Thus, can be tricky
to have the same behavior acrros different OS. One hard stuff that we founded is that was not possible to use my
TimeIntervals objects (implemented with threading module) with vtk. The reason for this impossibility is because we can't use
vtk in windows in different threads. But fortunely, moving from the threading (multithreading) to the asyncio approcach (concurrency)
have fixed this issue and now the streaming system is ready to be used anywhere.
&lt;/code>&lt;/pre>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Flickering&lt;/strong>&lt;/p>
&lt;pre>&lt;code>Finally, I could found the cause of the flickering effect on the streaming system.
This flickering was appearing only when the streaming was created using the Widget object.
The cause seems to be a bug or a strange behavior from vtk.
Calling
&lt;/code>&lt;/pre>
&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ul>
&lt;p>iren.MouseWheelForwardEvent() or&lt;/p>
&lt;p>iren.MouseWheelBackwardEvent() inside of a thread without invoking the
Start method from a vtk instance produces a memory corruption.
Fortunately, I could fix this behavior and now the streaming system is
working without this glitch effect.&lt;/p>
&lt;pre>&lt;code>FURY/Helios
&lt;/code>&lt;/pre>
&lt;ul>
&lt;li>
&lt;a href="https://github.com/fury-gl/helios/pull/24" target="_blank" rel="noopener">PR fury-gl/helios#24 :&lt;/a>&lt;/li>
&lt;/ul>
&lt;p>This uses the
&lt;a href="https://github.com/fury-gl/fury/pull/489" target="_blank" rel="noopener">PRfury-gl/fury#489:&lt;/a> to give
the network label feature to helios. Is possible to draw node labels,
update the colors, change the positions at runtime. In addition, when a
network layout algorithm is running this will automatically update the
node labels positions to follow the nodes across the screen.&lt;/p>
&lt;p>&lt;img src="https://user-images.githubusercontent.com/6979335/129642582-fc6785d8-0e4f-4fdd-81f4-b2552e1ff7c7.png" alt="image1">&lt;/p>
&lt;ul>
&lt;li>
&lt;a href="https://github.com/fury-gl/helios/pull/23" target="_blank" rel="noopener">PR fury-gl/helios#23:
Merged.&lt;/a>&lt;/li>
&lt;/ul>
&lt;p>This PR granted compatibility between IPC Layouts and Windows. Besides
that , now is quite easier to create new network layouts using inter
process communication&lt;/p>
&lt;h1 id="did-i-get-stuck-anywhere">Did I get stuck anywhere?&lt;/h1>
&lt;p>I did not get stuck this week.&lt;/p></description></item><item><title>GSoC- Network layout algorithms using IPC</title><link>/post/2021-07-12-gsoc-devmessias-6/2021-07-12-gsoc-devmessias-6/</link><pubDate>Mon, 12 Jul 2021 00:00:00 +0000</pubDate><guid>/post/2021-07-12-gsoc-devmessias-6/2021-07-12-gsoc-devmessias-6/</guid><description>&lt;p>Hi all. In the past weeks, I&amp;rsquo;ve been focusing on developing Helios; the
network visualization library for FURY. I improved the visual aspects of
the network rendering as well as implemented the most relevant network
layout methods.&lt;/p>
&lt;p>In this post I will discuss the most challenging task that I faced to
implement those new network layout methods and how I solved it.&lt;/p>
&lt;h2 id="the-problem-network-layout-algorithm-implementations-with-a-blocking-behavior">The problem: network layout algorithm implementations with a blocking behavior&lt;/h2>
&lt;p>&lt;strong>Case 1:&lt;/strong> Suppose that you need to monitor a hashtag and build a
social graph. You want to interact with the graph and at the same time
get insights about the structure of the user interactions. To get those
insights you can perform a node embedding using any kind of network
layout algorithm, such as force-directed or minimum distortion
embeddings.&lt;/p>
&lt;p>&lt;strong>Case 2:&lt;/strong> Suppose that you are modelling a network dynamic such as an
epidemic spreading or a Kuramoto model. In some of those network
dynamics a node can change the state and the edges related to the node
must be deleted. For example, in an epidemic model a node can represent
a person who died due to a disease. Consequently, the layout of the
network must be recomputed to give better insights.&lt;/p>
&lt;p>In described cases if we want a better (UX) and at the same time a more
practical and insightful application of Helios layouts algorithms
shouldn&amp;rsquo;t block any kind of computation in the main thread.&lt;/p>
&lt;p>In Helios we already have a lib written in C (with a python wrapper)
which performs the force-directed layout algorithm using separated
threads avoiding the GIL problem and consequently avoiding the blocking.
But and the other open-source network layout libs available on the
internet? Unfortunately, most of those libs have not been implemented
like Helios force-directed methods and consequently, if we want to
update the network layout the python interpreter will block the
computation and user interaction in your network visualization. How to
solve this problem?&lt;/p>
&lt;h2 id="why-is-using-the-python-threading-is-not-a-good-solution">Why is using the python threading is not a good solution?&lt;/h2>
&lt;p>One solution to remove the blocking behavior of the network layout libs
like PyMDE is to use the threading module from python. However, remember
the GIL problem: only one thread can execute python code at once.
Therefore, this solution will be unfeasible for networks with more than
some hundreds of nodes or even less! Ok, then how to solve it well?&lt;/p>
&lt;h2 id="ipc-using-python">IPC using python&lt;/h2>
&lt;p>As I said in my previous posts I&amp;rsquo;ve created a streaming system for data
visualization for FURY using webrtc. The streaming system is already
working and an important piece in this system was implemented using the
python SharedMemory from multiprocessing. We can get the same ideas from
the streaming system to remove the blocking behavior of the network
layout libs.&lt;/p>
&lt;p>My solution to have PyMDE and CuGraph-ForceAtlas without blocking was to
break the network layout method into two different types of processes: A
and B. The list below describes the most important behaviors and
responsibilities for each process&lt;/p>
&lt;p>&lt;strong>Process A:&lt;/strong>&lt;/p>
&lt;ul>
&lt;li>Where the visualization (NetworkDraw) will happen&lt;/li>
&lt;li>Create the shared memory resources: edges, weights, positions,
info..&lt;/li>
&lt;li>Check if the process B has updated the shared memory resource which
stores the positions using the timestamp stored in the info_buffer&lt;/li>
&lt;li>Update the positions inside of NetworkDraw instance&lt;/li>
&lt;/ul>
&lt;p>&lt;strong>Process B:&lt;/strong>&lt;/p>
&lt;ul>
&lt;li>Read the network information stored in the shared memory resources:
edges , weights, positions&lt;/li>
&lt;li>Execute the network layout algorithm&lt;/li>
&lt;li>Update the positions values inside of the shared memory resource&lt;/li>
&lt;li>Update the timestamp inside of the shared memory resource&lt;/li>
&lt;/ul>
&lt;p>I used the timestamp information to avoid unnecessary updates in the
FURY/VTK window instance, which can consume a lot of computational
resources.&lt;/p>
&lt;h3 id="how-have-i-implemented-the-code-for-a-and-b">How have I implemented the code for A and B?&lt;/h3>
&lt;p>Because we need to deal with a lot of different data and share them
between different processes I&amp;rsquo;ve created a set of tools to deal with
that, take a look for example in the
&lt;a href="https://github.com/fury-gl/helios/blob/main/helios/layouts/ipc_tools.py#L111" target="_blank" rel="noopener">ShmManagerMultiArrays
Object&lt;/a>
, which makes the memory management less painful.&lt;/p>
&lt;p>I'm breaking the layout method into two different processes. Thus I&amp;rsquo;ve
created two abstract objects to deal with any kind of network layout
algorithm which must be performed using inter-process-communication
(IPC). Those objects are:
&lt;a href="https://github.com/devmessias/helios/blob/a0a24525697ec932a398db6413899495fb5633dd/helios/layouts/base.py#L65" target="_blank" rel="noopener">NetworkLayoutIPCServerCalc&lt;/a>
; used by processes of type B and
&lt;a href="https://github.com/devmessias/helios/blob/a0a24525697ec932a398db6413899495fb5633dd/helios/layouts/base.py#L135" target="_blank" rel="noopener">NetworkLayoutIPCRender&lt;/a>
; which should be used by processes of type A.&lt;/p>
&lt;p>I&amp;rsquo;ll not bore you with the details of the implementation. But let&amp;rsquo;s take
a look into some important points. As I&amp;rsquo;ve said saving the timestamp
after each step of the network layout algorithm. Take a look into the
method _check_and_sync from NetworkLayoutIPCRender
&lt;a href="https://github.com/fury-gl/helios/blob/a0a24525697ec932a398db6413899495fb5633dd/helios/layouts/base.py#L266" target="_blank" rel="noopener">here&lt;/a>.
Notice that the update happens only if the stored timestamp has been
changed. Also, look at this line
&lt;a href="https://github.com/fury-gl/helios/blob/a0a24525697ec932a398db6413899495fb5633dd/helios/layouts/mde.py#L180" target="_blank" rel="noopener">helios/layouts/mde.py#L180&lt;/a>,
the IPC-PyMDE implementation This line writes a value 1 into the second
element of the info_buffer. This value is used to inform the process A
that everything worked well. I used that info for example in the tests
for the network layout method, see the link
&lt;a href="https://github.com/fury-gl/helios/blob/a0a24525697ec932a398db6413899495fb5633dd/helios/tests/test_mde_layouts.py#L43" target="_blank" rel="noopener">helios/tests/test_mde_layouts.py#L43&lt;/a>&lt;/p>
&lt;h2 id="results">Results&lt;/h2>
&lt;p>Until now Helios has three network layout methods implemented: Force
Directed , Minimum Distortion Embeddings and Force Atlas 2. Here
&lt;a href="https://github.com/fury-gl/helios/blob/a0a24525697ec932a398db6413899495fb5633dd/docs/examples/viz_helios_mde.ipynb" target="_blank" rel="noopener">docs/examples/viz_helios_mde.ipynb&lt;/a>
you can get a jupyter notebook that I&amp;rsquo;ve a created showing how to use
MDE with IPC in Helios.&lt;/p>
&lt;p>In the animation below we can see the result of the Helios-MDE
application into a network with a set of anchored nodes.&lt;/p>
&lt;p>&lt;img src="https://user-images.githubusercontent.com/6979335/125310065-a3a9f480-e308-11eb-98d9-0ff5406a0e96.gif" alt="image1">&lt;/p>
&lt;h2 id="next-steps">Next steps&lt;/h2>
&lt;p>I&amp;rsquo;ll probably focus on the Helios network visualization system.
Improving the documentation and testing the ForceAtlas2 in a computer
with cuda installed. See the list of opened
&lt;a href="https://github.com/fury-gl/helios/issues" target="_blank" rel="noopener">issues&lt;/a>&lt;/p>
&lt;h2 id="summary-of-most-important-pull-requests">Summary of most important pull-requests:&lt;/h2>
&lt;ul>
&lt;li>IPC tools for network layout methods (helios issue #7)
&lt;a href="https://github.com/fury-gl/helios/pull/6" target="_blank" rel="noopener">fury-gl/helios/pull/6&lt;/a>&lt;/li>
&lt;li>New network layout methods for fury (helios issue #7)
&lt;a href="https://github.com/fury-gl/helios/pull/9" target="_blank" rel="noopener">fury-gl/helios/pull/9&lt;/a>
&lt;a href="https://github.com/fury-gl/helios/pull/14" target="_blank" rel="noopener">fury-gl/helios/pull/14&lt;/a>
&lt;a href="https://github.com/fury-gl/helios/pull/13" target="_blank" rel="noopener">fury-gl/helios/pull/13&lt;/a>&lt;/li>
&lt;li>Improved the visual aspects and configurations of the network
rendering(helios issue #12)
&lt;a href="https://github.com/devmessias/helios/tree/fury_network_actors_improvements" target="_blank" rel="noopener">https://github.com/devmessias/helios/tree/fury_network_actors_improvements&lt;/a>&lt;/li>
&lt;li>Tests, examples and documentation for Helios (helios issues #3 and
#4)
&lt;a href="https://github.com/fury-gl/helios/pull/5" target="_blank" rel="noopener">fury-gl/helios/pull/5&lt;/a>&lt;/li>
&lt;li>Reduced the flickering effect on the FURY/Helios streaming system
&lt;a href="https://github.com/fury-gl/helios/pull/10" target="_blank" rel="noopener">fury-gl/helios/pull/10&lt;/a>
&lt;a href="https://github.com/fury-gl/fury/pull/437/commits/a94e22dbc2854ec87b8c934f6cabdf48931dc279" target="_blank" rel="noopener">fury-gl/fury/pull/437/commits/a94e22dbc2854ec87b8c934f6cabdf48931dc279&lt;/a>&lt;/li>
&lt;/ul></description></item><item><title>GSoC- Bugs!</title><link>/post/2021-06-21-gsoc-devmessias-3/2021-06-21-gsoc-devmessias-3/</link><pubDate>Mon, 21 Jun 2021 00:00:00 +0000</pubDate><guid>/post/2021-06-21-gsoc-devmessias-3/2021-06-21-gsoc-devmessias-3/</guid><description>&lt;h2 id="what-did-you-do-this-week">What did you do this week?&lt;/h2>
&lt;ul>
&lt;li>
&lt;a href="https://github.com/fury-gl/fury/pull/422/commits/8a0012b66b95987bafdb71367a64897b25c89368" target="_blank" rel="noopener">PR fury-gl/fury#422
(merged):&lt;/a>
Integrated the 3d impostor spheres with the marker actor.&lt;/li>
&lt;li>
&lt;a href="https://github.com/fury-gl/fury/pull/422" target="_blank" rel="noopener">PR fury-gl/fury#422
(merged):&lt;/a> Fixed some
issues with my maker PR which now it's merged on fury.&lt;/li>
&lt;li>
&lt;a href="https://github.com/fury-gl/fury/pull/432" target="_blank" rel="noopener">PR fury-gl/fury#432&lt;/a>
I've made some improvements in my PR which can be used to fine tune
the opengl state on VTK.&lt;/li>
&lt;li>
&lt;a href="https://github.com/fury-gl/fury/pull/437" target="_blank" rel="noopener">PR fury-gl/fury#437&lt;/a>
I've made several improvements in my streamer proposal for FURY
related to memory management.&lt;/li>
&lt;li>
&lt;a href="https://github.com/fury-gl/helios/pull/1" target="_blank" rel="noopener">PR fury-gl/helios#1&lt;/a>
First version of async network layout using force-directed.&lt;/li>
&lt;/ul>
&lt;h2 id="did-i-get-stuck-anywhere">Did I get stuck anywhere?&lt;/h2>
&lt;h3 id="a-python-core-issue">A python-core issue&lt;/h3>
&lt;p>I've spent some hours trying to discover this issue. But now it's
solved through the commit
&lt;a href="https://github.com/devmessias/fury/commit/071dab85a86ec4f97eba36721b247ca9233fd59e" target="_blank" rel="noopener">devmessias/fury/commit/071dab85&lt;/a>&lt;/p>
&lt;p>The 
&lt;a href="https://docs.python.org/3/library/multiprocessing.shared_memory.html" target="_blank" rel="noopener">SharedMemory&lt;/a>
from python&amp;gt;=3.8 offers a new a way to share memory resources between
unrelated process. One of the advantages of using the SharedMemory
instead of the RawArray from multiprocessing is that the SharedMemory
allows to share memory blocks without those processes be related with a
fork or spawm method. The SharedMemory behavior allowed to achieve our
jupyter integration and
&lt;a href="https://github.com/fury-gl/fury/pull/437/files#diff-7680a28c3a88a93b8dae7b777c5db5805e1157365805eeaf2e58fd12a00df046" target="_blank" rel="noopener">simplifies the use of the streaming
system&lt;/a>.
However, I saw a issue in the shared memory implementation.&lt;/p>
&lt;p>Let&amp;rsquo;s see the following scenario:&lt;/p>
&lt;pre>&lt;code>1-Process A creates a shared memory X
2-Process A creates a subprocess B using popen (shell=False)
3-Process B reads X
4-Process B closes X
5-Process A kills B
4-Process A closes X
5-Process A unlink() the shared memory resource X
&lt;/code>&lt;/pre>
&lt;p>The above scenario should work flawless. Calling unlink() in X is the
right way as discussed in the python official documentation. However,
there is a open issue related the unlink method&lt;/p>
&lt;ul>
&lt;li>
&lt;a href="https://bugs.python.org/issue38119" target="_blank" rel="noopener">Issue:
https://bugs.python.org/issue38119&lt;/a>&lt;/li>
&lt;li>
&lt;a href="https://github.com/python/cpython/pull/21516" target="_blank" rel="noopener">PR
python/cpython/pull/21516&lt;/a>&lt;/li>
&lt;/ul>
&lt;p>Fortunately, I could use a
&lt;a href="https://bugs.python.org/msg388287" target="_blank" rel="noopener">monkey-patching&lt;/a> solution to fix
that meanwhile we wait to the python-core team to fix the
resource_tracker (38119) issue.&lt;/p>
&lt;h2 id="what-is-coming-up-next">What is coming up next?&lt;/h2>
&lt;p>I'm planning to work in the
&lt;a href="https://github.com/fury-gl/fury/pull/432" target="_blank" rel="noopener">fury-gl/fury#432&lt;/a> and
&lt;a href="https://github.com/fury-gl/helios/pull/1" target="_blank" rel="noopener">fury-gl/helios#1&lt;/a>.&lt;/p></description></item><item><title>GSoC- A Stadia-like system for data visualization</title><link>/post/2021-06-12-gsoc-devmessias-2/2021-06-12-gsoc-devmessias-2/</link><pubDate>Sat, 12 Jun 2021 00:00:00 +0000</pubDate><guid>/post/2021-06-12-gsoc-devmessias-2/2021-06-12-gsoc-devmessias-2/</guid><description>&lt;p>Hi all! In this post I'll talk about the PR
&lt;a href="https://github.com/fury-gl/fury/pull/437" target="_blank" rel="noopener">#437&lt;/a>.&lt;/p>
&lt;p>There are several reasons to have a streaming system for data
visualization. Because I&amp;rsquo;m doing a PhD in a developing country I always
need to think of the cheapest way to use the computational resources
available. For example, with the GPUs prices increasing, it&amp;rsquo;s necessary
to share a machine with a GPU with different users in different
locations. Therefore, to convince my Brazilian friends to use FURY I
need to code thinking inside of the (a) low-budget scenario.&lt;/p>
&lt;p>To construct the streaming system for my project I&amp;rsquo;m thinking about the
following properties and behaviors:&lt;/p>
&lt;ol>
&lt;li>I want to avoid blocking the code execution in the main thread
(where the vtk/fury instance resides).&lt;/li>
&lt;li>The streaming should work inside of a low bandwidth environment.&lt;/li>
&lt;li>I need an easy way to share the rendering result. For example, using
the free version of ngrok.&lt;/li>
&lt;/ol>
&lt;p>To achieve the property &lt;strong>1.&lt;/strong> we need to circumvent the GIL problem.
Using the threading module alone it&amp;rsquo;s not good enough because we can&amp;rsquo;t
use the python-threading for parallel CPU computation. In addition, to
achieve a better organization it&amp;rsquo;s better to define the server system as
an uncoupled module. Therefore, I believe that multiprocessing-lib in
python will fit very well for our proposes.&lt;/p>
&lt;p>For the streaming system to work smoothly in a low-bandwidth scenario we
need to choose the protocol wisely. In the recent years the WebRTC
protocol has been used in a myriad of applications like google hangouts
and Google Stadia aiming low latency behavior. Therefore, I choose the
webrtc as my first protocol to be available in the streaming system
proposal.&lt;/p>
&lt;p>To achieve the third property, we must be economical in adding
requirements and dependencies.&lt;/p>
&lt;p>Currently, the system has some issues, but it's already working. You
can see some tutorials about how to use this streaming system
&lt;a href="https://github.com/devmessias/fury/tree/feature_fury_stream_client/docs/tutorials/04_stream" target="_blank" rel="noopener">here&lt;/a>.
After running one of these examples you can easily share the results and
interact with other users. For example, using the ngrok For example,
using the ngrok&lt;/p>
&lt;pre>&lt;code>./ngrok http 8000
&lt;/code>&lt;/pre>
&lt;p>|&lt;/p>
&lt;h2 id="how-does-it-works">How does it works?&lt;/h2>
&lt;p>The image below it's a simple representation of the streaming system.&lt;/p>
&lt;p>&lt;img src="https://user-images.githubusercontent.com/6979335/121934889-33ff1480-cd1e-11eb-89a4-562fbb953ba4.png" alt="image1">&lt;/p>
&lt;p>As you can see, the streaming system is made up of different processes
that share some memory blocks with each other. One of the hardest part
of this PR was to code this sharing between different objects like VTK,
numpy and the webserver. I'll discuss next some of technical issues
that I had to learn/circumvent.&lt;/p>
&lt;h3 id="sharing-data-between-process">Sharing data between process&lt;/h3>
&lt;p>We want to avoid any kind of unnecessary duplication of data or
expensive copy/write actions. We can achieve this economy of
computational resources using the multiprocessing module from python.&lt;/p>
&lt;h4 id="multiprocessing-rawarray">multiprocessing RawArray&lt;/h4>
&lt;p>| The
&lt;a href="https://docs.python.org/3/library/multiprocessing.html#multiprocessing.sharedctypes.RawArray" target="_blank" rel="noopener">RawArray&lt;/a>
from multiprocessing allows to share resources between different
processes. However, there are some tricks to get a better performance
when we are dealing with RawArray's. For example,
&lt;a href="https://github.com/devmessias/fury/tree/6ae82fd239dbde6a577f9cccaa001275dcb58229" target="_blank" rel="noopener">take a look at my
PR in a older
stage.&lt;/a>
In this older stage my streaming system was working well. However, one
of my mentors (Filipi Nascimento) saw a huge latency for
high-resolutions examples. My first thought was that latency was
caused by the GPU-CPU copy from the opengl context. However, I
discovered that I've been using RawArray's wrong in my entire life!
| See for example this line of code
&lt;a href="https://github.com/devmessias/fury/blob/6ae82fd239dbde6a577f9cccaa001275dcb58229/fury/stream/client.py#L101" target="_blank" rel="noopener">fury/stream/client.py#L101&lt;/a>
The code below shows how I've been updating the raw arrays&lt;/p>
&lt;pre>&lt;code>raw_arr_buffer[:] = new_data
&lt;/code>&lt;/pre>
&lt;p>This works fine for small and medium sized arrays, but for large ones it
takes a large amount of time, more than GPU-CPU copy. The explanation
for this bad performance is available here :
&lt;a href="https://stackoverflow.com/questions/33853543/demystifying-sharedctypes-performance" target="_blank" rel="noopener">Demystifying sharedctypes
performance.&lt;/a>
The solution which gives a stupendous performance improvement is quite
simple. RawArrays implements the buffer protocol. Therefore, we just
need to use the memoryview:&lt;/p>
&lt;pre>&lt;code>memview(arr_buffer)[:] = new_data
&lt;/code>&lt;/pre>
&lt;p>The memview is really good, but there it's a litle issue when we are
dealing with uint8 RawArrays. The following code will cause an
exception:&lt;/p>
&lt;pre>&lt;code>memview(arr_buffer_uint8)[:] = new_data_uint8
&lt;/code>&lt;/pre>
&lt;p>There is a solution for uint8 rawarrays using just memview and cast
methods. However, numpy comes to rescue and offers a simple and a
generic solution. You just need to convert the rawarray to a np
representation in the following way:&lt;/p>
&lt;pre>&lt;code>arr_uint8_repr = np.ctypeslib.as_array(arr_buffer_uint8)
arr_uint8_repr[:] = new_data_uint8
&lt;/code>&lt;/pre>
&lt;p>You can navigate to my repository in this specific
&lt;a href="https://github.com/devmessias/fury/commit/b1b0caf30db762cc018fc99dd4e77ba0390b2f9e" target="_blank" rel="noopener">commit
position&lt;/a>
and test the streaming examples to see how this little modification
improves the performance.&lt;/p>
&lt;h3 id="multiprocessing-inside-of-different-operating-systems">Multiprocessing inside of different Operating Systems&lt;/h3>
&lt;p>Serge Koudoro, who is one of my mentors, has pointed out an issue of the
streaming system running in MacOs. I don't know many things about
MacOs, and as pointed out by Filipi the way that MacOs deals with
multiprocessing is very different than the Linux approach. Although we
solved the issue discovered by Serge, I need to be more careful to
assume that different operating systems will behave in the same way. If
you want to know more,I recommend that you read this post
&lt;a href="https://britishgeologicalsurvey.github.io/science/python-forking-vs-spawn/" target="_blank" rel="noopener">Python:
Forking vs
Spawm&lt;/a>.
And it's also important to read the official documentation from python.
It can save you a lot of time. Take a look what the official python
documentation says about the multiprocessing method&lt;/p>
&lt;p>&lt;img src="https://user-images.githubusercontent.com/6979335/121958121-b0ebb780-cd39-11eb-862a-37244f7f635b.png" alt="image2">
Source:
&lt;a href="https://docs.python.org/3/library/multiprocessing.html" target="_blank" rel="noopener">https://docs.python.org/3/library/multiprocessing.html&lt;/a>&lt;/p></description></item><item><title>Bibcure</title><link>/project/bibcure/</link><pubDate>Wed, 13 Sep 2017 17:43:22 +0000</pubDate><guid>/project/bibcure/</guid><description>&lt;a href="https://github.com/bibcure/bibcure">
Bibcure helps in boring tasks by keeping your bibfile up to date and normalized...also allows you to easily download all papers inside your bibtex
&lt;/a>
&lt;p>&lt;img src="https://raw.githubusercontent.com/bibcure/logo/master/gifs/bibcure_op.gif" alt="">&lt;/p>
&lt;h1 id="requirementsinstall">Requirements/Install&lt;/h1>
&lt;pre>&lt;code>$ sudo python /usr/bin/pip install bibcure
&lt;/code>&lt;/pre>
&lt;h2 id="scihub2pdfbeta">scihub2pdf(beta)&lt;/h2>
&lt;p>&lt;img src="https://raw.githubusercontent.com/bibcure/logo/master/sci_hub_64.png" alt=""> If you want download articles via a DOI number, article title or a bibtex file, using the
database of arxiv, libgen or sci-hub, see&lt;/p>
&lt;p>
&lt;a href="https://github.com/bibcure/scihub2pdf" target="_blank" rel="noopener">bibcure/scihub2pdf&lt;/a>&lt;/p>
&lt;h1 id="features-and-how-to-use">Features and how to use&lt;/h1>
&lt;h2 id="bibcure">bibcure&lt;/h2>
&lt;p>Given a bib file&amp;hellip;&lt;/p>
&lt;pre>&lt;code>$ bibcure -i input.bib -o output.bib
&lt;/code>&lt;/pre>
&lt;ul>
&lt;li>
&lt;p>check sure the Arxiv items have been published, then update them(requires
internet connection)&lt;/p>
&lt;/li>
&lt;li>
&lt;p>complete all fields(url, journal, etc) of all bib items using DOI number(requires
internet connection)&lt;/p>
&lt;/li>
&lt;li>
&lt;p>find and create DOI number associated with each bib item which has not
DOI field(requires
internet connection)&lt;/p>
&lt;/li>
&lt;li>
&lt;p>abbreviate jorunals names&lt;/p>
&lt;/li>
&lt;/ul>
&lt;h2 id="arxivcheck">arxivcheck&lt;/h2>
&lt;p>Given a arxiv id&amp;hellip;&lt;/p>
&lt;pre>&lt;code>$ arxivcheck 1601.02785
&lt;/code>&lt;/pre>
&lt;ul>
&lt;li>check if has been published, and then returns the updated bib (requires internet connection)&lt;/li>
&lt;/ul>
&lt;p>Given a title&amp;hellip;&lt;/p>
&lt;pre>&lt;code>$ arxivcheck --title An useful paper published on arxiv
&lt;/code>&lt;/pre>
&lt;p>search papers related and return a bib the first item.
You can easily append a bib into a bibfile, just do&lt;/p>
&lt;pre>&lt;code>$ arxivcheck --title An useful paper published on arxiv &amp;gt;&amp;gt; file.bib
&lt;/code>&lt;/pre>
&lt;p>You also can interact with results, just pass &amp;ndash;ask parameter&lt;/p>
&lt;pre>&lt;code>$ arxivcheck --ask --title An useful paper published on arxiv
&lt;/code>&lt;/pre>
&lt;h2 id="scihub2pdf">scihub2pdf&lt;/h2>
&lt;p>Given a bibtex file&lt;/p>
&lt;pre>&lt;code>$ scihub2pdf -i input.bib
&lt;/code>&lt;/pre>
&lt;p>Given a DOI number&amp;hellip;&lt;/p>
&lt;pre>&lt;code>$ scihub2pdf 10.1038/s41524-017-0032-0
&lt;/code>&lt;/pre>
&lt;p>Given arxivId&amp;hellip;&lt;/p>
&lt;pre>&lt;code>$ scihub2pdf arxiv:1708.06891
&lt;/code>&lt;/pre>
&lt;p>Given a title&amp;hellip;&lt;/p>
&lt;pre>&lt;code>$ scihub2bib --title An useful paper
&lt;/code>&lt;/pre>
&lt;p>or arxiv&amp;hellip;&lt;/p>
&lt;pre>&lt;code>$ scihub2bib --title arxiv:An useful paper
&lt;/code>&lt;/pre>
&lt;p>Location folder as argument&lt;/p>
&lt;pre>&lt;code>$ scihub2pdf -i input.bib -l somefoler/
&lt;/code>&lt;/pre>
&lt;p>Use libgen instead sci-hub&lt;/p>
&lt;pre>&lt;code>$ scihub2pdf -i input.bib --uselibgen
&lt;/code>&lt;/pre>
&lt;h2 id="doi2bib">doi2bib&lt;/h2>
&lt;p>Given a DOI number&amp;hellip;&lt;/p>
&lt;pre>&lt;code>$ doi2bib 10.1038/s41524-017-0032-0
&lt;/code>&lt;/pre>
&lt;ul>
&lt;li>get bib item given a doi(requires
internet connection)&lt;/li>
&lt;/ul>
&lt;p>You can easily append
a bib into a bibfile, just do&lt;/p>
&lt;pre>&lt;code>$ doi2bib 10.1038/s41524-017-0032-0 &amp;gt;&amp;gt; file.bib
&lt;/code>&lt;/pre>
&lt;p>You also can generate a bibtex from a txt file containing a list of DOIs&lt;/p>
&lt;pre>&lt;code>$ doi2bib --input file_with_dois.txt --output refs.bib
&lt;/code>&lt;/pre>
&lt;h2 id="title2bib">title2bib&lt;/h2>
&lt;p>Given a title&amp;hellip;&lt;/p>
&lt;pre>&lt;code>$ title2bib An useful paper
&lt;/code>&lt;/pre>
&lt;ul>
&lt;li>search papers related and return a bib for the selected paper(requires
internet connection)&lt;/li>
&lt;/ul>
&lt;p>You can easily append
a bib into a bibfile, just do&lt;/p>
&lt;pre>&lt;code>$ title2bib An useful paper --first &amp;gt;&amp;gt; file.bib
&lt;/code>&lt;/pre>
&lt;p>You also can generate a bibtex from a txt file containing a list of &amp;ldquo;titles&amp;rdquo;&lt;/p>
&lt;pre>&lt;code>$ title2bib --input file_with_titles.txt --output refs.bib --first
&lt;/code>&lt;/pre>
&lt;h2 id="sci-hub-vs-libgen">Sci-Hub vs LibGen&lt;/h2>
&lt;h3 id="sci-hub">Sci-hub:&lt;/h3>
&lt;ul>
&lt;li>Stable&lt;/li>
&lt;li>Annoying CAPTCHA&lt;/li>
&lt;li>Fast&lt;/li>
&lt;/ul>
&lt;h3 id="libgen">Libgen&lt;/h3>
&lt;ul>
&lt;li>Unstalbe&lt;/li>
&lt;li>No CAPTCHA&lt;/li>
&lt;li>Slow&lt;/li>
&lt;/ul></description></item><item><title>Python Triângulo</title><link>/project/python_triangulo/</link><pubDate>Mon, 15 Aug 2016 11:29:40 -0300</pubDate><guid>/project/python_triangulo/</guid><description/></item><item><title>ReciclaAqui</title><link>/project/reciclaaqui/</link><pubDate>Tue, 31 May 2016 10:45:56 +0000</pubDate><guid>/project/reciclaaqui/</guid><description>&lt;p>O Recicla Aqui é um projeto que desenvolvo em parceria com um amigo(Régis Maicon). Tal projeto visa inserir
tecnologia no processo da coleta seletiva e aumentar a qualidade de vida dos catadores de material reciclável.&lt;/p>
&lt;p>Temos três eixos norteadores:&lt;/p>
&lt;h4 id="fornecer-tecnologias-de--gerenciamento-e-formação-técnica--para-as-cooperativas">Fornecer tecnologias de Gerenciamento e Formação técnica para as Cooperativas&lt;/h4>
&lt;h4 id="criação-de-um-aplicativo-que-permita-conectar-cidadães-e-coletores">Criação de um aplicativo que permita conectar Cidadães e Coletores&lt;/h4>
&lt;h4 id="revitalização-da-imagem-dos-coletores">&amp;ldquo;Revitalização&amp;rdquo; da imagem dos coletores&lt;/h4>
&lt;h4 id="alfabetização-tecnológica">&amp;ldquo;Alfabetização Tecnológica&amp;rdquo;&lt;/h4>
&lt;p>O aplicativo você encontra na Goolge Play (futuramente na Apple Store)&lt;/p>
&lt;p>Objetivamos utilizar as redes sociais para conscientizar a população da importância dos catadores&lt;/p>
&lt;p>&lt;img src="/img/reciclaAqui/2.jpeg" alt="Alt text" title="Optional title">
&lt;img src="/img/reciclaAqui/reciclaaqui3.png" alt="Alt text" title="Optional title">
&lt;img src="/img/reciclaAqui/reciclaaqui4.png" alt="Alt text" title="Optional title">&lt;/p></description></item><item><title>eMaTe</title><link>/project/emate/</link><pubDate>Mon, 01 Jan 0001 00:00:00 +0000</pubDate><guid>/project/emate/</guid><description>&lt;p>eMaTe it is a python package which the main goal is to provide methods capable of estimating the spectral densities and trace
functions of large sparse matrices. eMaTe can run in both CPU and GPU and can estimate the spectral density and related trace functions, such as entropy and Estrada index, even in directed or undirected networks with million of nodes.&lt;/p>
&lt;h2 id="install">Install&lt;/h2>
&lt;pre>&lt;code>pip install emate
&lt;/code>&lt;/pre>
&lt;p>If you a have a GPU you should also install cupy.&lt;/p>
&lt;h2 id="kernel-polynomial-method-kpm">Kernel Polynomial Method (KPM)&lt;/h2>
&lt;p>The Kernel Polynomial Method can estimate the spectral density of large sparse Hermitan matrices with a computational cost almost linear. This method combines three key ingredients: the Chebyshev expansion + the stochastic trace estimator + kernel smoothing.&lt;/p>
&lt;h3 id="example">Example&lt;/h3>
&lt;pre>&lt;code class="language-python">import networkx as nx
import numpy as np
n = 3000
g = nx.erdos_renyi_graph(n , 3/n)
W = nx.adjacency_matrix(g)
vals = np.linalg.eigvals(W.todense()).real
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">from emate.hermitian import tfkpm
num_moments = 40
num_vecs = 40
extra_points = 10
ek, rho = tfkpm(W, num_moments, num_vecs, extra_points)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">import matplotlib.pyplot as plt
plt.hist(vals, density=True, bins=100, alpha=.9, color=&amp;quot;steelblue&amp;quot;)
plt.scatter(ek, rho, c=&amp;quot;tomato&amp;quot;, zorder=999, alpha=0.9, marker=&amp;quot;d&amp;quot;)
&lt;/code>&lt;/pre>
&lt;p>If the CUPY package it is available in your machine, you can also use the cupy implementation. When compared to tf-kpm, the
Cupy-kpm is slower for median matrices (100k) and faster for larger matrices (&amp;gt; 10^6). The main reason it&amp;rsquo;s because the tf-kpm was implemented in order to calc all te moments in a single step.&lt;/p>
&lt;pre>&lt;code class="language-python">import matplotlib.pyplot as plt
from emate.hermitian import cupykpm
num_moments = 40
num_vecs = 40
extra_points = 10
ek, rho = cupykpm(W.tocsr(), num_moments, num_vecs, extra_points)
plt.hist(vals, density=True, bins=100, alpha=.9, color=&amp;quot;steelblue&amp;quot;)
plt.scatter(ek.get(), rho.get(), c=&amp;quot;tomato&amp;quot;, zorder=999, alpha=0.9, marker=&amp;quot;d&amp;quot;)
&lt;/code>&lt;/pre>
&lt;p>&lt;img src="docs/source/imgs/kpm.png" alt="">&lt;/p>
&lt;h2 id="stochastic-lanczos-quadrature-slq">Stochastic Lanczos Quadrature (SLQ)&lt;/h2>
&lt;blockquote>
&lt;p>The problem of estimating the trace of matrix functions appears in applications ranging from machine learning and scientific computing, to computational biology.[2]&lt;/p>
&lt;/blockquote>
&lt;h3 id="example-1">Example&lt;/h3>
&lt;h4 id="computing-the-estrada-index">Computing the Estrada index&lt;/h4>
&lt;pre>&lt;code class="language-python">from emate.symmetric.slq import pyslq
import tensorflow as tf
def trace_function(eig_vals):
return tf.exp(eig_vals)
num_vecs = 100
num_steps = 50
approximated_estrada_index, _ = pyslq(L_sparse, num_vecs, num_steps, trace_function)
exact_estrada_index = np.sum(np.exp(vals_laplacian))
approximated_estrada_index, exact_estrada_index
&lt;/code>&lt;/pre>
&lt;p>The above code returns&lt;/p>
&lt;pre>&lt;code>(3058.012, 3063.16457163222)
&lt;/code>&lt;/pre>
&lt;h4 id="entropy">Entropy&lt;/h4>
&lt;pre>&lt;code class="language-python">import scipy
import scipy.sparse
def entropy(eig_vals):
s = 0.
for val in eig_vals:
if val &amp;gt; 0:
s += -val*np.log(val)
return s
L = np.array(G.laplacian(normalized=True), dtype=np.float64)
vals_laplacian = np.linalg.eigvalsh(L).real
exact_entropy = entropy(vals_laplacian)
def trace_function(eig_vals):
def entropy(val):
return tf.cond(val&amp;gt;0, lambda:-val*tf.log(val), lambda: 0.)
return tf.map_fn(entropy, eig_vals)
L_sparse = scipy.sparse.coo_matrix(L)
num_vecs = 100
num_steps = 50
approximated_entropy, _ = pyslq(L_sparse, num_vecs, num_steps, trace_function)
approximated_entropy, exact_entropy
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>(-509.46283, -512.5283224633046)
&lt;/code>&lt;/pre>
&lt;p>
&lt;a href="https://www.tandfonline.com/doi/abs/10.1080/03610919008812866" target="_blank" rel="noopener">[1] Hutchinson, M. F. (1990). A stochastic estimator of the trace of the influence matrix for laplacian smoothing splines. Communications in Statistics-Simulation and Computation, 19(2), 433-450.&lt;/a>&lt;/p>
&lt;p>
&lt;a href="https://epubs.siam.org/doi/abs/10.1137/16M1104974" target="_blank" rel="noopener">[2] Ubaru, S., Chen, J., &amp;amp; Saad, Y. (2017). Fast Estimation of tr(f(A)) via Stochastic Lanczos Quadrature. SIAM Journal on Matrix Analysis and Applications, 38(4), 1075-1099.&lt;/a>&lt;/p>
&lt;p>
&lt;a href="">[3] The Kernel Polynomial Method applied to
tight binding systems with
time-dependence&lt;/a>&lt;/p></description></item></channel></rss>