<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://joao-vap.github.io//feed.xml" rel="self" type="application/atom+xml" /><link href="https://joao-vap.github.io//" rel="alternate" type="text/html" /><updated>2026-05-21T05:24:46-07:00</updated><id>https://joao-vap.github.io//feed.xml</id><title type="html">João V. A. P.</title><subtitle>Mestrando do Programa de Matemática Pura do Instituto de Ciências Matemáticas e de Computação (ICMC - USP) e Bacharel em Física Computacional pelo Instituto de Física de São Carlos (IFSC - USP). Premiado &apos;Bernhard Gross&apos; (2022) pelo melhor desempenho acadêmico no curso. Possui interesse em métodos computacionais em física, matématica e suas intersecções. Realizou inciações científicas em múltiplas áreas, como: Métodos de Regressão em dados de alta dimensão (2020-2021), desenvolvimento de interface para pesquisa em ocultações estelares (2021-2022) e, mais recentemente, no estudo da Teoria de Matrizes Aleatórias e assintótica de dinâmica de partículas (2023-atual). Já realizou também estágio como desenvolvedor em uma startup de tecnologia (2022-2023) onde trabalhou com ferramentas computacionais de produção.</subtitle><author><name>João V. A. Pimenta</name><email>joaovictorpi[...]@usp.br</email></author><entry><title type="html">An intro to RMT</title><link href="https://joao-vap.github.io//posts/2025/05/IntroRMT/" rel="alternate" type="text/html" title="An intro to RMT" /><published>2025-05-10T00:00:00-07:00</published><updated>2025-05-10T00:00:00-07:00</updated><id>https://joao-vap.github.io//posts/2025/05/RMT</id><content type="html" xml:base="https://joao-vap.github.io//posts/2025/05/IntroRMT/"><![CDATA[<p>Our story starts with astronomy, one of the primordial sciences, and two prominent personalities from the sixteenth century; the astronomers Tycho Brahe (1546-1601) from Denmark and Johannes Kepler (1571-1630) from Germany. Brahe was perhaps the best observational astronomer we ever knew of, his observations were precise and all encompassing. His obsessive and careful note taking of the motion of celestial bodies was, and may still be, unheard of <sup id="fnref:1" role="doc-noteref"><a href="#fn:1" class="footnote" rel="footnote">1</a></sup>. On the other hand, Kepler had a more mathematical approach to astronomy; there is a reason to think of Kepler when we talk about the laws of orbiting bodies. As history would have it, Tycho later met Kepler and asked him to work as his assistant although unfortunately, not much time passed between this event and Brahe’s death. His last words, “<em>Ne frusta vixisse vidar</em>” (May I not seemed to have lived in vain) were recorded by Kepler. Indeed, the incredible amount of observations made during his lifetime would go on to empower Kepler to correctly deduce and improve his formulae of orbiting motions. The lasting gap between observational theory and mathematics was filled later on by Isaac Newton (1643-1727), the English most prolific physicist, astronomer and mathematician, who derived, by first principles, the laws of gravitation and fully explained the observational data gathered so far. Thenceforth, the motion of planets was well understood and there was a good idea on how to deal with other heavenly bodies.</p>

<p>There was some difficulty to describe the celestial motion, however, when it came to comets and like-bodies from outer space. The observations were scarce and imprecise; these bodies made appearance once or only a couple times during a lifetime if one was lucky enough to even find it. The theory of gravitational laws appointed ellipsis and parabolas as contenders for trajectories, but the observational data were still lacking. The pending question then was how to, from a small set of error-prone data, deduce the original curves of motion? A description of such problem was nicely stated by Carl Friedrich Gauss (1777-1855), the German true-polymath.</p>

<blockquote>
To determine the orbit of a heavenly body, without any hypothetical assumption, from observations not embracing a great period of time, and
not allowing a selection with a view to the application of special methods. [Gauss, 1809]
</blockquote>

<p>It was also Gauss who stepped in to solve the problem. From our current perspective, he used a type of <em>Maximum Likelihood Estimation</em> method, i.e., he tried to derive the defining parameters of the underlying orbit curve from a set of observational points without any previous knowledge or assumption. The method consists of minimizing some <em>error function</em> that depends on the distance from the observational points to the predicted curve. One might remember for example of the <em>least squares</em> method where the error function is evaluated as the sum of the distances squared. As mentioned, observational data carried errors, and to perform such methods Gauss would need to understand how to weight the distance of the observational points to some theoretical curve. Surely, points very far from a predicted curve should be few; this is assumption one: The error function must be decaying. Another assumption was that this error function was symmetric; it should not exist a bias to err in a direction-specific way, therefore the deviations from the <em>true-value</em> should result in an even function. These assumptions led Gauss to the <em>normal curve</em>, or what it sometimes called the <em>Gaussian distribution</em>.</p>

<p><img src="/images/posts/RMT/Gaussian.png" alt="Plot of the Gaussian distribution. \label{Figure: Gaussian}" /></p>

<p>Today, it is well-known among physicists and mathematicians alike that random independent phenomena share common characteristics when dealt in large quantities. The most important and known example is surely the convergence to the normal curve. We call a <em>random variable</em> the mathematical object that takes values depending on some type of random event. One can think of the realization of a coin toss as a random variable \(C\) that assumes values \(\{heads (H), tails (T)\}\) with probability \(0.5\) each. For <em>reasonable</em> random variables such as the coin toss, the distribution of the mean of multiple tosses should converge to a known curve: the normal. To avoid sounding too broad or mysterious on the “natural requirements” we mention what is a <em>reasonable</em> variable. The first main assumption taken is that you’re dealing with a variable which
distribution, the set of values it can realize, has a somehow contained tail-end - has sequences such as  \(\{H, H, H, H, H, H, ...\}\) less frequently, or in mathematical jargon, the variable has finite moments. The other assumption is that, contrary to what the Gambler’s fallacy <sup id="fnref:2" role="doc-noteref"><a href="#fn:2" class="footnote" rel="footnote">2</a></sup> may say, each sample you take, each toss, is independent - realizations should not interfere with each other’s probabilities.</p>

<p>This has been recognized as a very powerful result and may be the absolute core result of much of theoretical and applied probabilistic research. This is more formally expressed in terms of the central limit theorem: Take \(\{x_n\}_{n\geq1}\) independent and identically distributed random variables. Each of this variables may be for example a coin toss \(c_n\) and we may say that the variables take value is we get a heads, and if we get a tail. If we center, e.g.,  \(c_n - E(x_n) = c_n - (1-0)/2 = c_n - 0.5\) and re-scale the variables by its variance - a measure of the variable dispersion, e.g., \(c_n - E(c_n)) / \sqrt{Var(c_n)} =  (c_n - 0.5)/ \sqrt{0.5}\) then, the new variable \(c_n :=(c_n - E(c_n)) / \sqrt{Var(c_n)}\) should obey the following law</p>

\[lim_{n\rightarrow \infty} p\left( \frac{\sum_{k=1}^{n} y_k}{\sqrt{n}} \leq t \right) =F^{(G)}(t; 0, 1).\]

<p>What this equation is saying is that the limit (\(n \rightarrow \infty\))  probability that the sum of the re-scaled (by \(\sqrt{n}\)) variable \(y_k\) is less than or equal to some value \(t \in R\) is given by  \(F^{(G)}(t; 0, 1)\) - the <em>cumulative distribution</em> for the normal distribution. Albeit the convoluted wording, this simply means that the distribution of the re-scaled variable sum is as in Figure <a href="#Figure: Gaussian">1</a>. This in an amazing result as it appoints the Gaussian distribution as a universal distribution for a large number of uncorrelated random processes - note that this variable could be of many types as far as it is a <em>reasonable</em> random variable. There is an interesting point to be made here about <em>“the unreasonable effectiveness of mathematics in the natural sciences”</em>, a phrase coined by Eugene Wigner (1902-1995), a Hungarian-American theoretical physicist, when discussing the role of mathematics in physics. Wigner starts his text with a story that illustrates the conundrum.</p>

<blockquote>
There is a story about two friends, who were classmates in high school, talking about their jobs. One of them became a statistician and was working on population trends. He showed a reprint to his former classmate. The reprint started, as usual, with the Gaussian distribution and the statistician explained to his former classmate the meaning of the symbols for the actual population, for the average population, and so on. His classmate was a bit incredulous and was not quite sure whether the statistician was pulling his leg. "How can you know that?" was his query. "And what is this symbol here?" "Oh," said the statistician, "this is `pi`." "What is that?" "The ratio of the circumference of the circle to its diameter." "Well, now you are pushing your joke too far," said the classmate, "surely the population has nothing to do with the circumference of the circle." [Wigner, 1995]
</blockquote>

<p>There is nothing unnatural or weird about the reaction of the non-statistician friend. However used to the idea one is, it is hard to argue <em>a priori</em> that natural phenomena <em>should</em> follow some relatively simple mathematical law. This is precisely the point of Wigner’s work; to note that in many cases mathematical concepts and formulation seems to lead to a large and extensively accurate description of a large number of phenomena, and that it is moreover done in a unreasonably simple formulation for the relatively complexity of the natural world. This whole ordeal of the role of mathematics was already noted before and expresses in the quotation often attributed to Galileu Galilei (1564 - 1642), the Italian physicist, that “The Book of Nature is written in the language of mathematics”. Although otherworldly, there is a body of evidence that suggest, despite any justification one may come up with, that mathematics plays a major role in the way we chose to study the natural world. <sup id="fnref:3" role="doc-noteref"><a href="#fn:3" class="footnote" rel="footnote">3</a></sup></p>

<blockquote>
It is difficult to avoid the impression that a miracle confronts us here, quite comparable in its striking nature to the miracle that the human mind can string a thousand arguments together without getting itself into contradictions, or to the two miracles of the existence of laws of nature and of the human mind's capacity to divine them. The observation which comes closest to an explanation for the mathematical concepts' cropping up in physics which I know is Einstein's statement that the only physical theories which we are willing to accept are the beautiful ones. It stands to argue that the concepts of mathematics, which invite the exercise of so much wit, have the quality of beauty.
[Wigner, 1995]
</blockquote>

<p>There is however, many phenomena where the assumptions we took do not hold such that, in these cases, we must look for another universality law - indeed, naturally, there are non-symmetric distributions and correlated random variables. One can think of an interacting system of particles as an example of correlated phenomena and the position \(x_t\) for each particle in the system as the random variable of interest for each time \(t\). For these cases another universality result must be considered, one where the Gaussian distribution is substituted with a more appropriate distribution. An important historical example appeared in physics in the last century. When working with heavy nuclei, physicist around the 1950’s struggled a lot to properly understand what was going on with the system compared with the absolute success of
quantum mechanics in simpler nuclei such as hydrogen. This type of work was condemned to be impossible: Theoretically, these atoms are huge and the interactions and intern structures were barely known. Freeman Dyson (1923 - 2020), a British-American mathematician and physicist, described the situation as follows.</p>

<blockquote>
We picture a complex nucleus as a 'black box' in which a large number of particles are interacting according to unknown laws. The problem then is to define in a mathematically precise way an ensemble of systems in which all possible laws of interaction are equally probable.
[Dyson, 1962]
</blockquote>

<p>Physically, to understand a system one might want to write out its Hamiltonian - in a way, a expression of its energy. This takes the form of a matrix which size is of the order of the number of agents present in the system. For large nuclei, you would have to deal with huge matrices. If, analytically, these Hamiltonian were immensely complex to understand, describe and deal with; computationally, those were also essentially useless, computers were not at a point of evaluating meaningfully the evolution of such system, even if there was a good understanding of the elements and interactions in the system. There was, however, a typical experiment done to study properties of such nuclei and that physicists were very interested in understanding theoretically the results. The <em>nuclei scatter</em> is a technique of projecting neutrons (non-charged particles) in nuclei at multiple energies to detect what are called resonance energies. These energies are related to the internal structure and of much use to researches. In a conference on nuclear physics in 1956 Wigner, presented his work regarding the theoretical statistics of the spacing distribution of adjacent neutron resonances in heavy nuclei. He said the following.</p>

<blockquote>
Perhaps I am now too courageous when I try to guess the distribution of the distances between successive levels (of energies of heavy nuclei). Theoretically, the situation is quite simple if one attacks the problem in a simpleminded fashion. The question is simply what are the distances of the characteristic values of a symmetric matrix with random coefficients. [WIGNER, 1956]
</blockquote>

<p>The fact is that Wigner had had a breakthrough that would change the approach in correlated systems and introduce . He found a way to model scattering energies as eigenvalues of a specific model of random matrix - thought of simply as a matrix of random entries with some given distribution, correlated or not. For the purposes of this work one can think that matrices of size \((n,n)\) have \(n\) eigenvalues, or characteristic values. If one thinks of a matrix as a linear operator onto \(n\)-dimensional space, eigenvalues are a measure of the intensity of this operator in each of the \(n\) directions; an eigenvalue would mean that the direction remains same-scaled. In physics, eigenvalues of the Hamiltonian are called eigenenergies of the system, i.e., they are the allowed energy states that the given system can assume. However, to understand how Wigner could have compared matrices’ eigenvalues to energy levels, we must think of what it means to model a system by a random matrix. For that, Percy Deift (1945), a South-African mathematician, has a very nice analogy.</p>

<blockquote>
This procedure can be viewed as follows: A scientist wishes to investigate some statistical phenomenon. What he has at hand is a microscope and a handbook of matrix ensembles. The data $${a_k}$$ are embedded on a slide which can be inserted into the microscope. The only freedom that the scientist has is to center the slide,  $$a_k \rightarrow a_k - A$$ and then adjust the focus  $$a_k - A \rightarrow \tilde{a}_k = \gamma_a(a_k - A)$$ so that on average one data point $$\tilde{a}_k$$ appears per unit length on the slide. At that point the scientist takes out his handbook, and then tries to match the statistics of the $$\tilde{a}_k$$ with those of the eigenvalues of some ensemble. If the fit is good, the scientist then says that the system is well-modeled by RMT.
</blockquote>

<p>Wigner understood, by the procedure described by Deift, that the energies he was studying had the same statistic as the eigenvalues of random matrices from the so-called <em>Gaussian Ensemble</em>. <sup id="fnref:4" role="doc-noteref"><a href="#fn:4" class="footnote" rel="footnote">4</a></sup> The Gaussian Ensemble is nothing more than the set of hermitian matrices with independent random centralized and normalized Gaussian variables. Moreover, Wigner noted that modulo some symmetry considerations, all nuclei could be divided in symmetry classes and that, if in the same class, they exhibited universal behavior. Interestingly, in all cases, the energies appeared to exhibit repulsion, or, more precisely, the probability that two energy levels were close together was very small. After all, eigenvalues of such <em>Wigner matrices</em> were found to be distributed as the now famous <em>Wigner Semi-Circle</em>.</p>

<p><img src="/images/posts/RMT/SemiCircle.png" alt="Plot of the Wigner Semi-Circle distribution. \label{Figure: Semi-Circle}" /></p>

<p>There are two scales and regions we want to considering when studying the Semi-Circle distribution. If one takes a value in the bulk, between  \((-1,1)\) in Figure <a href="#Figure: Semi-Circle">2</a>, the density is given in terms of an object we call the <em>Sine Correlation Kernel</em>, the same statistic found in the atomic energies described by Wigner. This object, however, did not contain itself to these two examples. There is a well known story regarding Hugh Montgomery (1944), an American mathematician, and Dyson about this mathematical object. Montgomery works with analytical number theory and is better known for his <em>pair correlation conjecture</em> on the zeros of the Riemann zeta function  \(\zeta(s)\) - perhaps one of the best known of analysis open problems today. Montgomery found a way to re-scale the non-trivial zeros of the Riemann zeta function and find a <em>pair correlation</em> between these objects. That is, he found some statistical information on the distribution of such zeros; a very hard problem. During a visit in the 1970’s to the Institute for Advanced Study in Princeton he was suggested to present his result to Dyson. Before Montgomery could state his result however, Dyson took out a pen and predicted some function that looked like</p>

\[R(a, b) = \int_{a}^{b} \left[ 1 - \left( \frac{\sin(\pi r)}{\pi r}\right)^2 \right] d r.\]

<p>Of course, Montgomery should have felt nothing short of deep confusion as how his result should be that obvious for Dyson. The explanation for such a guess is that Dyson believed that the non-trivial zeros of the zeta function might behave like the eigenvalues of a random <em>Gaussian Unitary Ensemble</em> (GUE) matrix (composed of unitary matrix with Gaussian entries), and, were that the case, \(R(a, b)\) would be exactly the formula for the two-point correlation function. This was derived from the well known by the time, Sine Correlation Kernel. This type of approach to problems became better known and phenomena in the same universality class started to pup-up many times.</p>

<p>On the other hand, for some point in the edge of the distribution of Figure <a href="#Figure: Semi-Circle">2</a>, we get the other scaling of interest. Mathematically, the result would read</p>

\[lim_{N\rightarrow \infty} p\left(e + \frac{x}{c N^{2/3}} \leq t \right) = F_{TW}^{(2)}(x).\]

<p>Morally, this means that the outermost eigenvalue is distributed as a special function  \(F_{TW}^{(2)}\)  the Tracy-Widom distribution.</p>

<p><img src="/images/posts/RMT/TracyWidom.png" alt="Plot of &lt;spanclass=&quot;math inline&quot;&gt;&lt;em&gt;F&lt;/em&gt;&lt;sub&gt;&lt;em&gt;T&lt;/em&gt;&lt;em&gt;W&lt;/em&gt;&lt;/sub&gt;&lt;sup&gt;(2)&lt;/sup&gt;(&lt;em&gt;x&lt;/em&gt;)&lt;/span&gt;, the Tracy-Widom distribution.\label{Figure: Tracy-Widom}" /></p>

<p>An interest effect is in play at this region. The outermost eigenvaluefeels interactions asymmetrically; on the real line, it only has other particles to one of its sides. This results in an asymmetricdistribution with a long tail in the direction without interactions as can be seen in Figure <a href="#Figure: Tracy-Widom">3</a>. A very classical model to illustrate the importance of such distribution is the problem of the <em>maximal increasing sub-sequence</em>, also known by the name of one of its researchers, the Polish mathematician Stanislaw Ulam (1909 - 1984), as <em>Ulam’s problem</em>. Suppose you take a sequence of integer numbers and shuffle them in what we call a permutation. There are many possible permutations, and we will consider for this application that they are all equally likely. Naturally one can get for example</p>

\[\pi = ~5~4~1~7~2~3~8~6\]

<p>as a permutation of the numbers  \({1, 2, 3, 4, 5, 6, 7, 8}\). One can notice that the number are not necessarily increasing or decreasing globally, but that it may be the case locally and even more the case if one is willing to ignore the non-conforming numbers. That is, take for example the sub-sequence of \(\pi\) given by  \(\tau = ~1~2~3~6\)  Note that these numbers are not subsequent but, nevertheless, are an increasing sub-sequence of the original permutation. Suppose that we consider the distribution of increasing sub-sequences lengths. For many reasons one might be interested in the maximal increasing sub-sequence  \(l_N\)  Of course, calculating  \(l_N(\pi)\)  for the given  \(\pi\)  is a trivial exercise; and for larger given sequences, it would also only require patience and will power. However, in most applications one wants to understand the <em>typical size</em>  \(E[l_N]\) of such maximal large sequences, i.e., what size one might expect to get from a random sampled permutation of the numbers. Some direct assumptions can be made: this size must depend on a parameter the size of the initial sequence. Of course, it cannot be bigger than or smaller than nevertheless it stands to reason that this size must have some scaling with  \(N\).</p>

<p>The problem of increasing sub-sequences is highly linked with the problem of the <em>matching sequences</em> described by Majumdar (2007), or more descriptively, the problem of the <em>longest common sub-sequence</em>. We deal now with a permutation of some alphabet of possibly repeated symbols whereas before we used integers and only allowed each number to appear once. Note, we could still use numbers as the symbols, but for a <em>not-at-all-suspicious</em> motive we will use the four letter alphabet \(ATCG\) and allow repetition of symbols in the sequence. Consider for example the sequences  \(\alpha,\beta\) given by</p>

\[\begin{aligned} 
    \alpha \quad &amp; : \qquad A \quad C \quad G \quad C \quad T \quad A \quad C \\
    \beta \quad &amp; : \qquad C \quad T \quad G \quad A \quad C
\end{aligned}\]

<p>Again, we want to look for, non necessarily adjacent, sub-sequences of symbols. For example, a sub-sequence of alpha could be  \(CGAC\)  corresponding to the second, third, sixth and seventh letters. As it so happens, we chose a sub-sequence of length \(4\) that is common to both  alpha and  beta.  Moreover, as  beta is of size \(5\) this might just be the longest (one of) matching sequences as long as  beta is not contained as a sub-sequence in  alpha.  For the biology-interested reader, an application of this type of metric may have become clear. The fact is that DNA are sequences of a four lettered alphabet such as  alpha and  beta  It is our understanding that genes responsible for specific proteins evolve with time and that, finding this longest common sequences between genes of different species may indicate what is conserved through evolution. One may also be interested in checking that two genes are the same, or if they are considerably different. Just by chance, of course, one must expect the longest matching sub-sequence to be relatively large for a few-lettered alphabet. However, if one understands what is the expectation of such length and how lengths deviate from this mean expectation, it gets considerably easier to make statements that two sequences are evolutionary close or far apart.</p>

<p>Note that in both problems, of increasing and matching sub-sequences,these variables cannot be understood as independent random variables and that the classical central limit theorem is useless for their study in the enunciated form. For the longest increasing subsequence problem, historically, Ulam (1961) discussed the idea of using a <em>Monte Carlo</em> <sup id="fnref:5" role="doc-noteref"><a href="#fn:5" class="footnote" rel="footnote">5</a></sup> <sup id="fnref:6" role="doc-noteref"><a href="#fn:6" class="footnote" rel="footnote">6</a></sup> approach to study the asymptotic behavior of  \(E[l_N]\), the expectation of the longest increasing sub-sequence length when \(N \rightarrow \infty\). Based on his simulations, Ulam conjectured that there exists a constant such that \(E[l_N] = \sqrt{N}c\) when went to infinity. Later on, Hammersley (1972), introduced a Poissonized version of this problem and formally proved that the constant exists. Five years afterwards, Logan and Shepp (1977) and, independently, Vershik (1977), showed that \(c=2\) Much later, Odlyzko and Rains (2000), performed analytical simulations indicating that, when \(N \rightarrow \infty\) the variance of \(l_N\) - the dispersion around the mean, scaled as \(Var[l_N] \approx 0.82 N^{\frac{1}{3}}\) and the mean as \(E[l_N] - 2\sqrt{N} \approx -1.75 N^{\frac{1}{6}}\).  At this point, \(E[l_N]\) was well known. However, the proper variable had not been taken face on. Finally, Ulam’s problem was solved by Baik, Deift and Johansson (1999), who studied the convergence in distribution of the re-scaled variable \(\chi_N :=(l_N - 2\sqrt{N})/ N^{\frac{1}{6}}\) and discovered that it converges in distribution to</p>

\[lim_{N \rightarrow \infty} p\left( \frac{l_N - 2\sqrt{N}}{N^{\frac{1}{6}}} \leq x\right) = F_{TW}^{(2)}(x).\]

<p>The daunting resemblance to the central limit theorem should be noted. This cumulative distribution function \(F_{TW}^{(2)}(x)\) ended up being known today as the  <em>Tracy-Widom</em> distribution. By good measure we must also state a result from the matching sequence example. The result is only valid for a simplified model: <em>The Bernoulli matching model</em>; defined if one ignores some correlation that appears in the modeling. This is not completely bad as these correlations tend to zero when the number of letters in the alphabet increases. Call \(L^{(BM)}_{i,j}\) the size of the longest matching sequence where \(i,j\) are the size of the first and second sequences used. If  \(i=j=n\)  for large  \(n\)  one gets that</p>

\[F^{(BM)}_{n,n} \rightarrow \gamma^{(BM)}_c n + f(c) n^{1/3} \chi\]

<p>where \(\gamma_c^{(BM)} = 2/(1+\sqrt{c})\) \(\chi\) is a random variable with an \(n\)-independent distribution and \(p(\chi \leq x) = F_{TW}^{(2)}(x)\) is precisely the Tracy-Widom distribution, yet again.</p>

<p>This special function appears many other times in many other different models and phenomena. It appears to be related to the universality of phase transitions - such as the physical transition of water or superconductivity. One of the indications of this development was the work of Majumdar and Schehr (2014) that showed that for large  \(N\)  the Tracy-Widom to describe the crossover function between stable and unstable regimes of a random dynamical system - a phase transition, such as the ones observed in Kieburg, Verbaarschot and Zafeiropoulos (2014) work on two-dimensional Quantum Chromodynamics. Eventually physicists realized that the energy curves of certain strongly correlated systems have a kink at \(\sqrt{2N}\)  The associated peak for these systems is the Tracy-Widom distribution, which appears in the third derivative of the energy curve - that is, the rate of change of the rate of change of the
energy’s rate of change.</p>

<p>More importantly for this work, for a large class of random matrices called Wigner Matrices, independent of individual probability density of matrices, the eigenvalue distribution tends to the Wigner’s Semi-Circle distribution. It represents a class of universality in matrices. Interestingly enough, the eigenvalue dynamics can be often interpret as a physical gas of charged interacting particles submitted to some confining external potential known as a <em>Coulomb gas</em>. Note that such particles would repel each other because of the charges, however unnatural this might sound for eigenvalues of random matrices, this is what is observed: Eigenvalues configurations with two extremely close eigenvalues are much less likely. This creates a bridge to a theory of dynamical systems and point processes that lead us to consider what happens when such gases are taken to the thermodynamic limit. That is, what happens when we increase the number of charged particles, the mass number of an atomic nuclei or even the length of the sequences considered before. This lead us under some appropriate considerations, to asymptotic equilibrium configurations of the points; a major field of study in RMT. It also motivates ways of simulating these equilibrium measures, namely, using usual particle dynamics methods such as the ones described in Chafaï and Ferré (2018).</p>

<p><img src="/images/posts/RMT/CoulombGas.png" alt="Plot of a simulation of a Coulomb gas in two dimensions under a potential with threefold symmetry. In black crosses we plotted one sample from the simulation. In  shadowy dots, the “averaged” samples,suggesting the theoretical equilibrium region." /></p>

<p>A Coulomb gas can be thought of as a measure  mu - a mathematical probability distribution; especially, it can be thought of as the Gibbs measure. For the physics-inclined reader, the Gibbs measure may be well known as the probability distribution used in thermodynamics when dealing with the <em>Canonical Ensemble</em> - a thermalized closed system. If you take a random array of points \(\xi = \{x_1, x_2, \cdots, x_n\}\)  then this measure gives you a probability that your system is in such configuration. This distribution takes the well known form</p>

\[\mu(\xi) = \frac{e^{-\beta \mathcal{H}(\xi)}}{Z_n^{\beta}}.\]

<p>Here,  beta is just as usual in physics, a parameter that stands for the inverse temperature of the system. Higher  beta’s means the system is very cold, with less energy - the particles would be moving less. Alternatively, a lower  beta would give you an energetic system - the particles would likely spread more as they would be with higher energy. The function  \(H\) is related to the system static energy, it is called the Hamiltonian in the physics literature. It is a composition of the internal energy of the system, given by the potential energy of the Coulomb interactions between particles, and the potential energy of the particles by the application of an external field \(Q\). In two dimensions it reads as</p>

\[H(\xi) = n \sum_{i = 1}^{n} Q(x_i) - \frac{1}{2} \sum_{i \neq j}^{n} \log(x_i - x_j).\]

<p>This gives a mathematical interpretation for the idea that two particles, or eigenvalues, repel each other. Starting with a configuration with two particles at a point  \(x_c\) or very close points  \(x_c^+, x_c^-\)  the logarithm function would evaluate the distance between these particles as a infinitely negative number. In this way, \(H\) would be very positively large and therefore  mu would be extremely low, indicating low, or zero, probability of such configuration. The same reasoning applies to understanding why particles do not diffuse very far for a sufficiently fast growing external potential \(Q\) if a particle is very far from its minimum, the configuration would be rendered non-likely.</p>

<p>This of course, was incredibly interesting and was looked for in all sorts of phenomena. Another interesting result is the work of Abul-Magd (2006), that investigated the gap distances between parked cars to find that these distances behaved as the distances of eigenvalues for the GUE. The explanation given was that drivers tended to park near to each other but still tried to keep a reasonable distance to maneuver safely; in other words, they behaved just like a charged particle gas within a confining potential! Another instance of this type of result was in the 1990’s when two Czech Physicists took interest in the transportation system of the city of Cuernavaca, in Mexico. In this work Krbálek and Seba (2000),suspected that the peculiarities of the city’s buses could result in a result expressed in terms of known objects in RMT. There were no public buses in the city, they were private and did their own timetables only needing to follow the approved routes designed by the city. As there were no coordination for the buses times, sometimes buses were right before another line and could not take anyone. In light of this situation, the city installed sensors as bus’ stops and started to sell the information about buses leaving the stations. Now, with this information, drivers started to avoid each other but of course, still wanted to do the route as soon as possible to avoid loosing clients. This resulted in the same behavior noted before: buses were behaving as the aforementioned Coulomb gas!</p>

<p>This modeling was repeated for many other highly correlated processes and was very successful as a general theory of random correlated systems. This can now be observed in the plenitude of posterior system modeled with such statistics, for example: the previously cited Ulam’s Problem (ULAM, 1961) and Matching Random Sub-sequences (MAJUMDAR, 2007) but also in the Zeros of the Riemann Zeta Function (GOLDSTON; MONTGOMERY, 1987), Tiling problems (the Aztec Diamond, for instance) and Interacting Random Walks, to name a few.</p>

<p>There was an intentional omission so far, we have not discussed the fact that a probability measure should add up, summing all micro-states, to  \(1\).  This is the role of the function  \(Z_{n}^{\beta}\)  it is a normalizing function called the <em>partition function</em>. <sup id="fnref:7" role="doc-noteref"><a href="#fn:7" class="footnote" rel="footnote">7</a></sup> It works basically as any other normalization: Summing over all states such that, when divided, every state probability is normalized to sum to one.  More importantly, this is a very physically interesting function; the micro-state’s energy is a function of many thermodynamic variables. With a model of the system one can calculate the energy for each state and therefore calculate its partition function. As such, the partition function holds, in some way, the macro expression of the micro-states energy distribution. This is more direct if one is familiar with the usual way of thermodynamics and know that many macro-state quantities such as internal energy, entropy and the alike can be expressed as functions of the partition function.</p>

<p>However, explicitly knowing the expression for a partition function is no easy task, the summation over <em>all</em> micro-states can be quite an
elusive idea. A typical method in thermodynamics is to consider the thermodynamic limit, that is, the state of the system when the number of particles grows very large (the volume grows accordingly). The idea is that fluctuations of any quantity will become negligible when
considering a very large amount of particles, in this way, one can better say a system has some mean quantity without much deviation. This is the same technique used in mathematics, we will evaluate such function when the number of particles is very large. Even then, the
exact expression is a very hard task for many systems. We will perform an asymptotic analysis to get some approximate expression like</p>

\[\ln(Z_{N,\beta=2}^{Q}) = -I_Q N^2+\frac{1}{2} N\ln N+E_Q N+G\ln N+F^Q + o(1).\]

<p>Interestingly, these terms have very nice physical interpretations: The term  \(I_Q\) is given by the energy of the associated equilibrium
distribution and  \(E_Q\) is an entropy term! Other coefficients can also be useful although with less straightforward interpretations. The
evaluation at \(\beta=2\) was no accident. This case, associated with Unitary symmetry, simplifies immensely calculations and analytical treatment as it presents what is called a <em>determinantal structure</em> not present for other  beta.</p>

<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:1" role="doc-endnote">
      <p>Brahe also, in what can be considered usual mathematician
tradition, had a prosthetic metal nose result of a duel with a
fellow Danish nobleman about who was the better mathematician. <a href="#fnref:1" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:2" role="doc-endnote">
      <p>The Gambler’s fallacy is the idea behind the misconception that a lottery number or sequence of numbers, for example, is less likely  to be drawn than other number/sequence if it was already drawn before. <a href="#fnref:2" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:3" role="doc-endnote">
      <p>The interest reader may want to expand their knowledge on
Noether’s Theorems. There is reason to believe that the idea of
symmetry is the driving force of conserved quantities in nature and therefore of universality classes and physical laws. <a href="#fnref:3" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:4" role="doc-endnote">
      <p><em>Ensembles</em> in RMT are simply a set of matrix with some
distribution, the matrices itself are random variables; random
matrices. <a href="#fnref:4" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:5" role="doc-endnote">
      <p>Stanislaw Ulam actually developed the modern conception of Monte
Carlo methods while working on nuclear weapons at the Los Alamos
National Laboratory in the 1940’s. (METROPOLIS, 1987) <a href="#fnref:5" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:6" role="doc-endnote">
      <p>The Monte Carlo technique is way to study deterministic systems in a probabilistic manner. One can think of calculating  \(\pi\) by  placing \(n\) uniformly random points in the square of side \(l\) and counting how many pointsfall whiting the circumscribed circle. Then, \(\pi =\lim_{N\rightarrow \infty} (4 n l^2)/(N l^2)\) using the ratio between the area of the square and circle. <a href="#fnref:6" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:7" role="doc-endnote">
      <p>The letter  \({Z}\) stands for the German word <em>Zustandssumme</em>, meaning the "sum over states". <a href="#fnref:7" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>João V. A. Pimenta</name><email>joaovictorpi[...]@usp.br</email></author><category term="RMT" /><category term="Mathematics" /><category term="Research" /><summary type="html"><![CDATA[Our story starts with astronomy, one of the primordial sciences, and two prominent personalities from the sixteenth century; the astronomers Tycho Brahe (1546-1601) from Denmark and Johannes Kepler (1571-1630) from Germany. Brahe was perhaps the best observational astronomer we ever knew of, his observations were precise and all encompassing. His obsessive and careful note taking of the motion of celestial bodies was, and may still be, unheard of 1. On the other hand, Kepler had a more mathematical approach to astronomy; there is a reason to think of Kepler when we talk about the laws of orbiting bodies. As history would have it, Tycho later met Kepler and asked him to work as his assistant although unfortunately, not much time passed between this event and Brahe’s death. His last words, “Ne frusta vixisse vidar” (May I not seemed to have lived in vain) were recorded by Kepler. Indeed, the incredible amount of observations made during his lifetime would go on to empower Kepler to correctly deduce and improve his formulae of orbiting motions. The lasting gap between observational theory and mathematics was filled later on by Isaac Newton (1643-1727), the English most prolific physicist, astronomer and mathematician, who derived, by first principles, the laws of gravitation and fully explained the observational data gathered so far. Thenceforth, the motion of planets was well understood and there was a good idea on how to deal with other heavenly bodies. Brahe also, in what can be considered usual mathematician &#8617;]]></summary></entry><entry><title type="html">Who is checking my poster? Referees assignments in the SIFSC</title><link href="https://joao-vap.github.io//posts/2024/07/CongressAttributions/" rel="alternate" type="text/html" title="Who is checking my poster? Referees assignments in the SIFSC" /><published>2024-08-04T00:00:00-07:00</published><updated>2024-08-04T00:00:00-07:00</updated><id>https://joao-vap.github.io//posts/2024/07/SIFSC</id><content type="html" xml:base="https://joao-vap.github.io//posts/2024/07/CongressAttributions/"><![CDATA[<p>We don’t talk enough about referees allocations for posters sections.</p>

<p>I’ve been to a few local and national congresses by now. A lot of them, by the way we are accustomed to presenting scientific work, have had a poster session or some similar version of this model. In any case, there is a time when attendees are expected to present their work to other participants, especially to a handful of referees who will evaluate the merits of the presentation. This was the case during the scientific week of the Physics Institute of São Carlos (<a href="https://www.instagram.com/sifsc_usp/">SIFSC</a> - USP), the institute where I graduated. The event is called Integrated Physics Week of São Carlos SIFSC, and it is mainly organized by the students of the institute, a mix of undergrads, masters, and PhD students. In my first year as an organizer, I was part of the team in charge of systems and evaluations, which is responsible, among other things, for the poster section. That mainly means managing the entries of referees and participants, allocating to each of the latter a few of the former and a section of time to present their work.</p>

<p>This all sounded normal enough for me. After all, I am well aware that many events do the same thing. The first shock came when I was informed that this task was previously performed by hand by someone (most likely a saint) in the administration. This is a Herculian task. To do that, you would have to know, or research, all of the referees and have a basic idea of their research. Then you would have to read participants research and try to match them with referees. However, that would still be simpler than it usually is. You have a limited number of participants you can fit in each section, meaning a couple poster sections. Naturally, participants and referees will have time constraints, something you may want to consider. Of course, you wouldn’t want to allocate a referee to multiple sections throughout the whole event, nor would you want to allocate lots of participants in the same section to the same referee. That would make the referee’s job almost impossible and the evaluation poorer. Bear in mind that some referees will have less in common with participants than the average, and you can’t afford to not allocate them to some students. If you’re organizing a local event and have some kind of award, you may also want to guarantee that the referees are not evaluating their own students or someone too close to their laboratory. If doctoral students are being evaluated, you may want to avoid their evaluation of master students and, of course, of other doctoral students. The same goes for master students, which is more uncommon but still possible if short on referees. Not only that, but you have to reallocate participants constantly to accommodate referees that drop out or have some kind of unforeseen event.</p>

<p>This is to say: It is necessary to have an algorithm to deal with most of this. This is the problem we try to solve in this post. Many of the implementations are still being tested but have shown to facilitate the task very much. Knowing all of this, I’m actually very impressed with the organization of most events I’ve been to. Either they know something I don’t, or this is the fruit of a lot of sweat on their part. Either way, I’m sure many of the ideas can be used by someone trying to overcome a similar problem.</p>

<h1 id="approaching-the-problem">Approaching the problem</h1>

<p>We have many problems to solve to get to the final allocation. I will briefly describe the ideas we use to get a solution and in the next section explain how to implement it (in a somehow general manner). You can alternatively access the code used in <a href="/files/posts/SIFSC/TestAllocation.ipynb">Allocation</a>.</p>

<ol>
  <li>
    <p><strong>Correlation of Participant-Referee</strong>: We will to create a correlation matrix that give us how much a referee is related to a participants profile. This matrix is one of the main ideas of the algorithm but it is also easy to implement, given the correct dataset to work with. We will collect, from anyone registering, a list of words related to their research and then use a SVD approach to project them in a lower dimension. In this dimension, it is easier to define a distance between the vectors that represent participants and referees. This is how we build the correlation matrix.</p>
  </li>
  <li><strong>Allocation Matrix</strong>: We need to create a matrix, which we will call matrix of allocation, where each line is a participant and each column is a referee. If the participant is allocated to be evaluated by a referee, the cell in the crossing of the collumn and line has value 1, otherwise it is valued 0. We also need to impose some rules to the allocation, as discussed. This can be, for example, being a doctoral student and not being evaluated by a doctoral student or a referee not evaluting its own supervised students. This matrix of rules is used as a mask to create the allocation matrix. The allocation matrix will also have, however, to obbey some general rules we impose, those are:
    <ol>
      <li>Each student must have a defined number of referees (each line must have a defined number of 1’s and be zero elsewhere)</li>
      <li>Each teacher must have around the same defined number of students (each column must have about a defined number of 1’s and be zero elsewhere)</li>
      <li>The rules matrix must be respected (each 0 in the matrix of rules must be 0 in the allocation matrix)</li>
    </ol>
  </li>
  <li>
    <p><strong>Optimize Allocations and Section</strong>: Suposse we have a plausible allocation matrix. In order to have better evaluations and, overall experience, we should make sure it is optimized. The parameter to which we optimize it is a score function that evaluates the quality of the allocation. The optimization of this function shouold maximize the sum of allocated correlation of each participant and minimize its global variance. We also have to consider time constraints and the number of sections each referee has been located to. We will use a stochastic search to accomplish those goals. That is, we move randomly and use the gradient of the score function to generally guide the search.</p>
  </li>
  <li><strong>Reallocation of Participants</strong>: We’ll probably have to reallocate participants to accommodate referees that drop out or have some kind of unforeseen event. We also use the same ideal of a stochastic search to optimize this function, now bearing in mind that we should minimize interference with non-problematic allocatinons as to not cause confusion among other referees and participants.</li>
</ol>

<h1 id="implementation">Implementation</h1>

<h2 id="data-fields">Data fields</h2>

<p>We need to first think about what data we need from the participants and referees. The registering form must contain at least the following fields:</p>

<ol>
  <li><strong>Name</strong>: The name of the participant or some identificator;</li>
  <li><strong>Type</strong>: The type of participant (student or referee);</li>
  <li><strong>Research</strong>: A list of words, fields or concepts from wich a subset related to the research of the participant/referee can be chosen;</li>
  <li><strong>Class</strong>:
    <ol>
      <li><strong>Class of referee</strong>: If the participant is a referee, the type of referee (professor, researcher or phd student);</li>
      <li><strong>Class of student</strong>: If the participant is a student, the type of student (phd, master or undergrad);</li>
    </ol>
  </li>
</ol>

<p>Those are the main fields. Here, beacuse of the nature of our event, we consider that some participants don’t wish to run for the award. Furthermore, we also wish to avoid conflits of evaluation and time constraints, therefore we will add the following fields:</p>

<ol>
  <li><strong>Supervised</strong>: If the participant is a referee, a list of students supervised by him. If we wish to cross check, the students must also have a list of referees that supervise them;</li>
  <li><strong>Pypm</strong>: If the participant is a student, if he is running for the award (called here Pypm);</li>
  <li><strong>Time Restrictions</strong>: If the participant is a referee, the time he is available to be in a section. You can also allow for the participant to disclaim his preference for a section;</li>
</ol>

<h2 id="configurations-for-simulation">Configurations for simulation</h2>

<p>In this post however, and in the code provided, we won’t use the data provided from participants. Therefore we have to simulate our own data. Let’s define our simulated event. The fields marked as ‘Simulated’ are to be dismissed when using real data.</p>

<table>
  <thead>
    <tr>
      <th>Field</th>
      <th>Description</th>
      <th>Value</th>
      <th>Simulated</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>NStudents</td>
      <td>Number of Students</td>
      <td>250</td>
      <td>No</td>
    </tr>
    <tr>
      <td>NReferees</td>
      <td>Number of Referees</td>
      <td>100</td>
      <td>No</td>
    </tr>
    <tr>
      <td>Words</td>
      <td>Number of words to choose from</td>
      <td>30</td>
      <td>No</td>
    </tr>
    <tr>
      <td>Avl/Std</td>
      <td>Number of referees for each student</td>
      <td>3</td>
      <td>No</td>
    </tr>
    <tr>
      <td>Avl/Ref</td>
      <td>Number of participants for each referee</td>
      <td>~250//(100*3)</td>
      <td>No</td>
    </tr>
    <tr>
      <td>Groups</td>
      <td>Number of theoretical groups participants belong to</td>
      <td>5</td>
      <td>Yes</td>
    </tr>
    <tr>
      <td>Noise</td>
      <td>How likely to choose word from other group (1 is most)</td>
      <td>0.1</td>
      <td>Yes</td>
    </tr>
    <tr>
      <td>Related</td>
      <td>How likely to choose word from own group (1 is most)</td>
      <td>0.9</td>
      <td>Yes</td>
    </tr>
    <tr>
      <td>Rel</td>
      <td>Number of total orientations</td>
      <td>100</td>
      <td>Yes</td>
    </tr>
    <tr>
      <td>PropStd</td>
      <td>Proportion of each class of students (phd, master, undergrad)</td>
      <td>(1,1,1)</td>
      <td>Yes</td>
    </tr>
    <tr>
      <td>PropRef</td>
      <td>Proportion of each class of referees (professor, researcher, phd student)</td>
      <td>(1,1,1)</td>
      <td>Yes</td>
    </tr>
    <tr>
      <td>NSections</td>
      <td>Number of poster sections</td>
      <td>4</td>
      <td>No</td>
    </tr>
    <tr>
      <td>Std/Sec</td>
      <td>Number of students per section</td>
      <td>~250//4</td>
      <td>No</td>
    </tr>
  </tbody>
</table>

<p>We can of course change this parameter as we see fit for our own event specifications. Either way, the objects Referee and Students will be instantiated and, from then on, all processes are the same.</p>

<h1 id="creating-the-correlations">Creating the Correlations</h1>

<p>We now need to create a correlation matrix that will relate Referees to Students.</p>

<h2 id="a-simple-approach-svd">A simple approach: SVD</h2>

<p>Singular Value Decomposition, SVD, is a mathematical tool that gives us a matrix decomposition for a matrix \(A_{m,n}\) symmetric and semi-definite positive. We say that</p>

\[A = U \Sigma V^T\]

<p>where we say \(U\) to be a collumn matrix of eigenvectors of \(AA^T\) and \(V\) a collumn matrix of eigenvectors of \(A^TA\). The matrix \(\Sigma = \Lambda^{1/2}\) is diagonal with \(\Lambda\) being diagonal of eigenvalues of \(AA^T\) and \(A^TA\). How to interpret it and why is it important? We can think of the transformation as the following scheme</p>

\[\mathbf{y}=\mathbf{A}\mathbf{x}=(\underbrace{\mathbf{U}(\overbrace{\Sigma(\underbrace{\mathbf{V}^\top\mathbf{x}}_{\text{projection}}}^{\text{scale}}))}_{reconstruction})\]

<p>that is,</p>

<ul>
  <li>\(\mathbf{V}^\top\mathbf{x}\): Projection of vector \(\mathbf{x}\) in the basis \(\mathbf{v}_i\).</li>
</ul>

\[\begin{bmatrix}
\mathbf{v}_1^\top\mathbf{x} \\ \vdots \\ \mathbf{v}_n^\top\mathbf{x}
\end{bmatrix}=
\begin{bmatrix}
- &amp; \mathbf{v}_1 &amp; - \\
 &amp; \vdots &amp; \\
- &amp; \mathbf{v}_n &amp; - 
\end{bmatrix}
\begin{bmatrix}
x_1 \\ \vdots \\ x_n
\end{bmatrix}\]

<ul>
  <li>\(\mathbf{\Sigma}\mathbf{V}^\top\mathbf{x}\):
Scales each coefficient by \(\sqrt{\lambda_i}\)</li>
</ul>

\[\begin{bmatrix}
\sqrt{\lambda_1}\mathbf{v}_1^\top\mathbf{x} \\ \vdots \\ \sqrt{\lambda_n}\mathbf{v}_n^\top\mathbf{x}
\end{bmatrix}=
\begin{bmatrix}
\sqrt{\lambda_1} &amp; \cdots &amp; 0 \\
 &amp;  \ddots &amp; \\
 0 &amp;  \cdots &amp; \sqrt{\lambda_n}\\
\end{bmatrix}
\begin{bmatrix}
\mathbf{v}_1^\top\mathbf{x} \\ \vdots \\ \mathbf{v}_n^\top\mathbf{x}
\end{bmatrix}\]

<ul>
  <li>\(\mathbf{U}\mathbf{\Sigma}\mathbf{V}^\top\mathbf{x}\): \(\mathbf{y}\) is linear combination of \(\mathbf{u}_i\) with coefficients \(\sqrt{\lambda_i}\mathbf{v}_i^\top\mathbf{x}\)</li>
</ul>

\[\mathbf{y}=(\sqrt{\lambda_1}\mathbf{v}_1^\top\mathbf{x})
\begin{bmatrix}
| \\ \mathbf{u}_1 \\ |
\end{bmatrix}+\cdots+
(\sqrt{\lambda_n}\mathbf{v}_n^\top\mathbf{x})
\begin{bmatrix}
| \\ \mathbf{u}_n \\ |
\end{bmatrix}\]

<p>The big advantage of using this method is that we can reduce the dimensionality using a truncated version of the SVD. If we rank the eigenvalues and choose th most relevant dimensions we can work on a simpler problem with few dimension. It is possible indeed to show that this reduced matrix is in fact the best approximation for the original matrix. In our case, each dimension will be a linear combination of words such that each direction better describe the data. In that way, dimensions can be interpret as research groups in the data.</p>

<h2 id="how-to-apply-te-svd">How to apply te SVD</h2>

<p>We use the words collected from the participants and referees to create what we call a matrix of words. Every collum in our data must be a word and every line a participant. The same must be done for the referees. Now that we have a vector representation for each  (lines of 0’s and 1’s), we perform the SVD decomposition in the students matrix. That is, we will get from \( M_s \), matrix of words from sudents, the following</p>

\[M_s = U \Sigma V^T\]

<p>where we will actually work with the reduced form</p>

\[M_{sr} = U_r \Sigma_r V_r^T\]

<p>with \( r \) being the number of dimensions we will keep. Now, as we know that the directions that better describe our data are the collumns of \( U_r \), we can project both the referees and students in this new space. It is now only missing to define a distance between vectors. This can be simply the dot product of the vectors. The closer to 1, the more similar the vectors are - the closer to -1, the more different they are. We can now create a matrix of correlation between referees and students. This matrix, colored green when close to 1 and red when closer to -1, will look something like this</p>

<p style="text-align:center">
<a href="/files/posts/SIFSC/Corr.html">
<img src="/images/posts/SIFSC/Correlations.jpg" alt="SIFSC Corrrelation Matrix" title="SIFSC Corrrelation Matrix" style="width: 100%; margin=10px;" />
</a>
</p>

<p>Notice that I’ve clustered students and referees from the same group to be easier to visualize the correlation inside groups. This matrix will help us to determine who to pair up.</p>

<h1 id="allocations">Allocations</h1>

<p>We will first try to generate a possible solution for the problem, not necessarily a good one. The general rules we must follow for the allocation are</p>

<ol>
  <li>Each student must have a defined number of referees (each line must have a defined number of 1’s and be zero elsewhere);</li>
  <li>Each teacher must have the between a defined number of students and this number +1 (each column must have about a defined number of 1’s and be zero elsewhere);</li>
  <li>The matrix of rules must be respected (each 1 in the rulesMatrix must be 0 in the allocation matrix)</li>
</ol>

<h2 id="rules-and-initial-condition">Rules and initial condition</h2>

<p>What is the rules matrix? As we said before, we ma want to inforce whichever rules we see fit for the allocation. In this case, we will make so that doctoral students can’t evaluate other doctoral students and referees can’t supervise the students he evaluates. This will generate a matrix with ones where a allocation can’t happen and zero otherwise. Just like the following matrix, colored red for zero and green for one.</p>

<p style="text-align:center">
<a href="/files/posts/SIFSC/RulesMatrix.html">
<img src="/images/posts/SIFSC/Rules.png" alt="SIFSC Rules Matrix" title="SIFSC Rules Matrix" style="width: 100%; margin=10px;" />
</a>
</p>

<p>Every time we try to perform an allocation, this matrix must be checked. In this way we can impose any arbitrary rule.</p>

<p>We’re now missing an algorithm to get a possible configuration of the allocation matrix. Some problems can arise here if not enough referees are avaiable, especially when the rules for allocations are strict. If that’s the case, we need to increase the possible number of evaluations per referee or soften the rules. Assuming everything will go smoothly, we first try to allocate the referees to the students who have more restrictions, such as the doctoral students (can only the evaluated by teachers or researchers). This is because if we don’t, we may allocate too much of researches and teachers for undergraduates and miss those for the doctoral students. Depending on the situation you are working with, you may want to have different cicles such as the one described.</p>

<p>For each of these cicles - here, one for doctoral and one general for the yet non-allocated - we do the following. For each student, get every possible referee (noting the rules) and sort them for: The number of students they already have allocated and the correlation with the student, in this order. Now, allocate as many referees as needed to the student in the sorted order. If there is no referee to allocate, skip the student and change the settings or deal with that in the end. Keep going for the rest of students in the cycle and then, do the same in all other cycles. Hopefully, this will generate a possible configuration for the allocation matrix.</p>

<p style="text-align:center">
<a href="/files/posts/SIFSC/AllocMatrix.html">
<img src="/images/posts/SIFSC/InitialAlocation.png" alt="SIFSC Allocation Matrix" title="SIFSC Allocation Matrix" style="width: 100%; margin=10px;" />
</a>
</p>

<h2 id="improving-the-condition">Improving the condition</h2>

<p>We need to improve the allocation. How do we define ‘best’ in this scenario? We first need a function that associates each configuration of possible allocation matrix to a scalar. The bigger the scalar, the better we will consider the matrix to be - and equivalently the allocation. This can be, given the goals in mind, any arbitrary function. We will use the following evaluation</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">#@title Function Score
</span><span class="k">def</span> <span class="nf">scoreMatrix</span><span class="p">(</span><span class="n">vec</span><span class="p">):</span>
    <span class="c1"># parameter of the score
</span>    <span class="n">alpha</span> <span class="o">=</span> <span class="mi">3</span>
    <span class="n">beta</span> <span class="o">=</span> <span class="mi">5</span>
    <span class="n">idealVector</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">array</span><span class="p">([</span><span class="mi">3</span> <span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">nStd</span><span class="p">)])</span> <span class="o">/</span> <span class="n">np</span><span class="p">.</span><span class="n">linalg</span><span class="p">.</span><span class="n">norm</span><span class="p">(</span><span class="n">np</span><span class="p">.</span><span class="n">array</span><span class="p">([</span><span class="mi">3</span> <span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">nStd</span><span class="p">)]))</span>

    <span class="c1"># calcute the variance of the score
</span>    <span class="n">var</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">var</span><span class="p">(</span><span class="n">vec</span><span class="p">)</span>

    <span class="c1"># normalize the vector
</span>    <span class="n">vec</span> <span class="o">=</span> <span class="n">vec</span> <span class="o">/</span> <span class="n">np</span><span class="p">.</span><span class="n">linalg</span><span class="p">.</span><span class="n">norm</span><span class="p">(</span><span class="n">vec</span><span class="p">)</span>
    <span class="c1"># calculate the dot product with the vector of 3's
</span>    <span class="n">dot</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">dot</span><span class="p">(</span><span class="n">vec</span><span class="p">,</span> <span class="n">idealVector</span><span class="p">)</span>

    <span class="c1"># calculate the score
</span>    <span class="n">score</span> <span class="o">=</span> <span class="n">alpha</span><span class="o">*</span><span class="n">var</span> <span class="o">-</span> <span class="n">beta</span><span class="o">*</span><span class="n">dot</span>

    <span class="k">return</span> <span class="n">score</span><span class="p">,</span> <span class="n">var</span><span class="p">,</span> <span class="n">dot</span>
</code></pre></div></div>

<p>The idea is to create a vector with the sum of the allocated correlations of each student as entries. We then define the distance of this vectors to an ideal vector. This can be, for example, a vector full of the max sum possible - m, if there is m allocations. The other metric we consider is to minimize the variance of the sum of the allocated correlations. We don’t want students to have largely different ‘quality’ of evaluations. Those two metrics can be weighted as we wish for different results.</p>

<p>We now want to swap students between referees if that improves the allocation score. This can be exausthing to perform by hand, of course. Therefore, we implement an estochastic algorithm. The idea is very much insired by spin simulations, that is, Monte Carlo simulations. We perform a random swap and check how the new score \(S_f\) changes in relation to \(S_i\). If the score improves, this swap is done with probabiliy one. Otherwise, we perform the swap with probability</p>

\[p = f(S_f)/f(S_i).\]

<p>It is usual in physics simulations for this function \(f\) to be an exponential. We can, however, change it to better fit our purpose and score function. The great difficulty of this algorithm is usually that it can get stuck in local minima. To conter that effect, we should allow for non-optimal steps with a reasonable probability. We also, instead of proposing the change of state step by step, can propose a couple of steps together, to allow for larger exploration in each proposition. All this parameters are highly personal to each situation and must be tinkered with.</p>

<p>A reasonable thing to do is to guide the random steps. This is equivalent to a Hamiltonian approach to Monte Carlo methods. If you wish, you can random select the possible steps with weights proportional to some measure, for example, correlation with the student. This is also done in our simulation.</p>

<p style="text-align:center">
  <img src="/images/posts/SIFSC/dotproduct_iteration.png" width="40%" />
  <img src="/images/posts/SIFSC/variance_iteration.png" width="40%" />
  <img src="/images/posts/SIFSC/score_iteration.png" width="40%" />
</p>

<p>The meaning of these graphs are direct. The dot product is the correlation of the sum of the allocated correlations of students with an ‘ideal vector’. The variance is the variance of the sum of the allocated correlations of the students. The score is the score function we defined before. We can see in the first graph that the dot product is increasing; in the second that the variance is decreasing and in the third that the score is decreasing. This is a good sign that the algorithm is working. Note that here, the score is negative because of the definition. The more negative, the better the allocation. We get a new allocation matrix that looks like</p>

<p style="text-align:center">
<a href="/files/posts/SIFSC/SellectedMatrixBest.html">
<img src="/images/posts/SIFSC/SellectedAlloc.png" alt="SIFSC Best Allocation Matrix" title="SIFSC Best Allocation Matrix" style="width: 100%; margin=10px;" />
</a>    
</p>

<p>Notice that allocations gather around the groups areas. The score function, parameters and running time will radically change results. If sections didn’t matter, this would be the whole algorithm. If we study the distribution of allocated correlations we get something like</p>

<p style="text-align:center">
<img src="/images/posts/SIFSC/correlationdist.png" alt="SIFSC Best Allocation Dist" title="SIFSC Best Allocation Dist" style="width: 60%; margin=10px;" />   
</p>

<p>However, we go further.</p>

<h1 id="time-allocations">Time allocations</h1>

<p>To go further we now try to associate students with poster sections. Our main interests in doing so is to garantee that</p>

<ol>
  <li>Every session has, at most, some number of students arbitrated by the venue size. If we can, it is good to keep sessions with more or less the same amount of people presenting;</li>
  <li>Guarantee that every student has a single session and that referees have the minimun amount of sessions as possible. Bear in mind that too many allocation in one section can be a bad thing;</li>
  <li>Acomodate possible time restrictions from students but mainly from referees.</li>
</ol>

<p>We perform here a similar process as we did in the allocation scheme. We will first create a matrix similar to the allocation matrix but with time sessions instead of ones. The cells tahn can take any value in the range of 0 to n, with n being the number of sections and zero a non-allocation. To create a possible configuration is simpler here as we don’t have many rules except for the limitations we may want to accomodate. For the restrictions, we again use a rules matrix, now with restricted sessions instead of ones. If we have our first possible matrix of poster session allocations, we need to improve it by the parameters we set before. This will be done using again: A score function to associate each configuration with a scalar and a estochastic algorithm to improve it.</p>

<p>However, some details are worth mentioning. The way we’re doing the swaps is the following: We first select a referees randomly with probability based on how many sessions they have to attend (the more sessions, the more likely). Then, we need to select the student to swap. This can be done in the following manner: Select the section time based on how many students of the referee are allocated in each (the less the better - also look for students allocated alone in a section) and then, from this section, select one of the allocated students. Now we neeed someone to swap with. We look for a student in the main (if not full of students) section of the first referee - better if in a low frequency section of someome else - and especially good if with good correlation. One of the things we can make sure is that no one has to be in above a certain number of sections. This is done be tinkering the score function and penalizing a lot giving referees more sections than that. The implementation is a bit involved but the idea is simple. We try to swap students with like-correlated students in better sessions mutually. The progress is, again, guided with the evaluation of the score function.</p>

<p>In doing so, we can get results like the following for the number of sections a referee has to attend</p>

<table>
  <thead>
    <tr>
      <th>Number of sections</th>
      <th>Before Optimization</th>
      <th>After Optimization</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>0</td>
      <td>0</td>
      <td>0</td>
    </tr>
    <tr>
      <td>1</td>
      <td>0</td>
      <td>3</td>
    </tr>
    <tr>
      <td>2</td>
      <td>0</td>
      <td>56</td>
    </tr>
    <tr>
      <td>3</td>
      <td>0</td>
      <td>41</td>
    </tr>
    <tr>
      <td>4</td>
      <td>100</td>
      <td>0</td>
    </tr>
  </tbody>
</table>

<p>without a major change to the quality of the allocation.</p>

<h2 id="a-bit-of-improvement">A bit of improvement</h2>

<p>This can be a tricky part. A nice work around the hard parts in this section would be to integrate the main allocation with the poster section allocation. In this manner we gain a little more flexibility. This won’t, however, be discussed as it would be more of a implementation issue.</p>

<h1 id="final-process-the-emails-arrive">Final process: The emails arrive</h1>

<p>You will, very surely, get e-mails from students and referees saying that some allocation or poster section won’t work for them for some reason. By personal experience the registration is not always well done and information may be mixed up. Now you have a problem at your hands: To reallocate arbitrary students to a suited different poster section or referee. You can of course rerun the algorithm. However this will create chaos. Reassigning all students is a sure way to create a huge mess. Be sure to create a like-minded algorithm as the ones we implemented that will create the minimum of changes as possible to the previous allocations.</p>

<p>A possible way to deal with this is to only reallocate the students who have some problem, not changing others. This means ignoring number of allocations per referee and adding those students as needed. This is tipically a easier way to solve the problem. Otherwise you will need to perform multiple swaps and weight in the score function the fact that you made a change to a previous allocation. This is a bit more involved but can also be done.</p>]]></content><author><name>João V. A. Pimenta</name><email>joaovictorpi[...]@usp.br</email></author><category term="Medium" /><category term="Congress" /><category term="Computational" /><summary type="html"><![CDATA[We don’t talk enough about referees allocations for posters sections.]]></summary></entry><entry><title type="html">Intransitive Dice: How to express mathematics</title><link href="https://joao-vap.github.io//posts/2024/07/IntransitiveDice/" rel="alternate" type="text/html" title="Intransitive Dice: How to express mathematics" /><published>2024-07-25T00:00:00-07:00</published><updated>2024-07-25T00:00:00-07:00</updated><id>https://joao-vap.github.io//posts/2024/07/IntransitiveDice</id><content type="html" xml:base="https://joao-vap.github.io//posts/2024/07/IntransitiveDice/"><![CDATA[<p>How to discuss a intransitive dice problem in a mathematical way and what can we prove about it?</p>

<p>I’ve recentently took part in a work that discusses the problem of intransitive dice and I wnated to share some of the insights we had and how we dealt with the problem. We did arrive in some interesting results but left a lot of questions untouched. In sharing this, I hope to leave the door for someone else who’s intesrested to use from our work and advanced it. You can check the mathematical details directly at <a href="/publication/CLT-Intransitive-Dice">Intransitive Dice</a>.</p>

<h2 id="paper-rock-scissors">Paper, Rock, Scissors</h2>

<p><img src="/images/posts/IntransitiveDices/Comparing.png" alt="Comparing two dices" title="Comparing two dices" style="float:right; width: 40%; margin=10px;" /></p>

<p>Here is a far fetched question you may have encountered before: Can we play rock, paper or scissors with dice? On the first level, this question is asking us if we can have a set of three dice such that each die beat each other circularly. In other words, if we have three dice, A, B and C, can we have a set such that A beats B, B beats C and C beats A? This hints us at a set of intransitive dice; and I’ll say now that they do exist. But first, we need to know how to compare dice. Suppose two dice A and B such as the ones in the image. A has faces 1, 2, 4 and B has faces 1, 2, 3. We will say that A beats B if, from the nine possible outcomes of throwing both dice, A wins B more times than B wins over A. Otherwise, we say that B beats A. In this case, A beats B four out of nine times and B beats A three out of nine times - the rest of outcomes are ties. We say, in this case, that \( A \triangleright B\). So ok, to prove this first affirmation - that such intransitive set exists - we only need an example. Consider the following set</p>

<p style="text-align:center">
<img src="/images/posts/IntransitiveDices/ExemploTres.png" alt="Example" title="Comparing two dices" style="block; width: 70%; margin=10px;" />
</p>

<p>Here, it is still easy enough to see, by going over all possible outcomes, that \(A \triangleright B \triangleright C \triangleright A\). Which means that we have an intransitive set of three dice. This is enough to assert about the existence of an intransitive set. However, there is still an alternative interpretation to the rock, paper and scissors question: Is there a set of three dice such that A always beats B, B always beats C and C always beats A? This is a bit trickier. Of course we can see that, for dice with three side, this can not be the case. But what if we take dice with infinetely many faces? Are you sure this is still the case? Well, if you are, congratulations. We indeed can not have such set of dice. This results follows directly from the fact that if \(p(A)\) is a realization of the random variable that represents the face of dice A, then for an arbitrary \(\epsilon &gt; 0\), if</p>

\[\mathbb{P}(p(A) &gt; p(B)) = 1 - \epsilon,\]

<p>and</p>

\[\mathbb{P}(p(B) &gt; p(C)) = 1 - \epsilon,\]

<p>we must have that</p>

\[\mathbb{P}(p(A) &gt; p(C)) &lt; 2\epsilon.\]

<p>which is a shame. However, we can still do some interesting things. There is an alternative game of rock, paper and scissors called rock, paper, scissors, lizard, Spock. In this game, we have five elements and the rules are the following: Rock crushes scissors, scissors cuts paper, paper covers rock, rock crushes lizard, lizard poisons Spock, Spock smashes scissors, scissors decapitates lizard, lizard eats paper, paper disproves Spock, Spock vaporizes rock. Well…. ok, some weird rules. We can still have a set of dice that emulates the behaviour of those characters, although not deterministicaly. This is illustrated in the image below.</p>

<p style="text-align:center">
<img src="/images/posts/IntransitiveDices/PedraPapelTesoura.png" alt="Rock Paper Scissors" title="Area Estimation" style="display: block; width: 100%; margin=10px;" />
</p>

<h2 id="the-dice-are-getting-complicated">The dice are getting complicated</h2>

<p>Maybe you trusted me when I said the former dice had the properties I said they would have. Maybe you checked this result, however I wouldn’t assume so. The dice are getting complicated and counting all possible encounters is getting out of hand. Suppose for example the following set of dice</p>

<p style="text-align:center">
<img src="/images/posts/IntransitiveDices/Example.png" alt="Example of cicle" title="Example of cicle" style="width: 60%; margin=10px;" />
</p>

<p>Howto check if it is intransitive? Counting encounters by hand would be hellish. Well, a way to do it is to simulate the dice.</p>

<p><img src="/images/posts/IntransitiveDices/HistogramaExemplo.png" alt="Example Simulation" onmouseover="this.src='/files/posts/IntransitiveDice/ABCDices.gif'" onmouseout="this.src='/images/posts/IntransitiveDices/HistogramaExemplo.png'" title="Example Simulation" style="float:right; width: 50%; margin=10px;" /></p>

<p>We can throw the dice a large number of times and count the number of times each dice wins over the other. This is illustrated in the simulation below. I don’t think this will be enough to convince you of the intransitivity of the set of dice, much less of the results I want to show you next. Although this will be an usefull tool, I promise we won’t relie on it. We need some mathematical language as to model this dice and its interactions. With this tool, I hope to be able to clarify when does these sets of dice exists and how many of them there are. This is the goal of the next sections.</p>

<h1 id="words-or-how-to-express-dice-set">Words or how to express dice set</h1>

<p>We first set the model of dice we want to consider. We will consider sets of fair dice, that is, dice which the faces are equally likely to be thrown.  Also, we won’t allow for faces to be shared between two dice neither for a die to have repeating faces. The restriction of no
repeated faces is of particular interest since it enables the use the here denominated string representation.</p>

<h2 id="a-little-note-on-fair-dice">A little note on fair dice</h2>

<p>Although we are considering fair dice, it is not difficult to adapt some results for unfair dice. This is because we can think of the weights of faces as a repetition. If a die with three faces a, b and c has weights 1, 1.2 and 1.5 we can think of it, without loss of generality, as a die with with 10 a’s + 12 b’s + 15 c’s, all equally likely to be thrown.</p>

<p style="text-align:center">
<img src="/images/posts/IntransitiveDices/weights.png" alt="Example of weighted dice" title="Example of weighted dice" style="width: 80%; margin=10px;" />
</p>

<p><img src="/images/posts/IntransitiveDices/weightsTable.png" alt="weights table" title="weights table" style="float: right; width: 40%; margin=10px;" /></p>

<p>With this idea we can actually prove the existence (or non existence) of all sets of intransitive dice with weighted faces. If \(m\) is the number of dice and \(n\) the number of faces, we can prove the existence of sets of intransitive dice for all \(m\) and \(n\) except for the case where \(n = 1, 2, 3\), when it does not exist a set of intransitive dice. Those cases are illustrades in the table to the right.</p>

<h2 id="getting-back-on-strings">Getting back on strings</h2>

<p>Suppose that \(D^{(1)}, D^{(2)}, \dots, D^{(m)}\) are honest \(n\)-sided dice such that there are no repeating values on the faces through all dice. Therefore, it is possible to sort all the faces of the dice by its value and create a descending sequence that is given by some permutation of the faces of \(D^{(1)}, D^{(2)}, \dots, D^{(m)}\). This process can generate a unique string that represents the set of dice. This process, for three 4-sided dice, is represented in the following figure.</p>

<p style="text-align:center">
<img src="/images/posts/IntransitiveDices/Palavras.png" alt="Words" title="Words representation" style="width: 80%; margin=10px;" />
</p>

<p>Note that this sequence makes explicit that, when comparing the faces of the dice, one only cares about the relative position of the value in this sequence created. Therefore it is possible to exchange values by some symbolic representation of the dice the value belongs to without losing the information necessary to compare the dice. With the string, to compare die \(D^{(2)}\) to \(D^{(1)}\) is to sum how many letters \(s^{(1)}\) are to the right of every letter \(s^{(2)}\). The result is how many possible victories \(D^{(2)}\) has over \(D^{(1)}\). This relation \(D^{(1)} \triangleright D^{(2)}\) has a natural translation when comparing strings; therefore, the same notation may also be used in this context.</p>

<p>In the depiction, the obtained string uses a, b, and c to represent values of the respective  A, B, and C die. This gives \(abccabbcaabc\). It is possible to extend this process to any number of dice with any number of faces, given that they fulfill the requirement of not repeating values between them or in themselves.</p>

<p>To compare only two dice of the string, it is enough to remove all letters that are not representative of the dice of interest, and without loss, one can compare the two within the sub-sequence created. In the example given, to compare the dice A and B, analyze the sub-sequence generated by removing the c’s: \( ab\textcolor{red}{c}\textcolor{red}{c}abb\textcolor{red}{c}aab\textcolor{red}{c}\) \(\to\) \(ababbaab\). Again, the problem is resolved by comparing the relative position of the letter in the string. Sum how many b’s are to the right of every a to obtain the number of victories of a over b and vice-versa.</p>

<p>This is enough to understand what follows.</p>

<h1 id="when-does-it-exist">When does it exist?</h1>

<p>We first try to determine when does such a set exists. We need to establish a few results before we can answer this question. I won’t mathematically prove the results as it is already well established in our work, I will however give a general idea.</p>

<ol>
  <li>
    <p><strong>Symmetry</strong>: If the string representing the set of dice is symmetric, then, no dice beats any other and they all tie. This is very natural because if a string is symmetric, it can be written as the concatenation of a string and what we call it’s inverse. This means that the number of victories of one die over the other is the same as the number of victories of the other die over the first. Therefore, they tie.</p>
  </li>
  <li>
    <p><strong>Extension on the number of faces</strong>: If we have a set of dice that is intransitive, then we can add two faces to each of the dice and still have an intransitive set. This is because we can add two extra letters of each die concatenating a neutral string to the main word. Note that a neutral string is composed of this two extra letters of each die.</p>
  </li>
  <li>
    <p><strong>Extension on the number of dice</strong>: If we have a set of dice that is intransitive, then we can add a dice to the set and still have an intransitive set. This is because we can add a new letter in the string (other die) to the rigth of every ‘a’, for example. In this way, this new letter will have the same relation as ‘A’ to the rest of the set but will loose to ‘A’. Creating, thus, a new intransitive set.</p>
  </li>
  <li>
    <p><strong>Non-existence</strong>: there are no intransitive sets of three dice with two faces. This is straightforward to see.</p>
  </li>
</ol>

<p><img src="/images/posts/IntransitiveDices/BaseExistencia.png" alt="Existence Examples" title="Existence Example" style="float: left; width: 60%; margin=10px;" /></p>

<p>We now only need two examples to deermine the existence of sets of intransitive dice for all number of faces and all number of dice. Using the image displayed with examples, we can see that there is a set with three dice with three faces. This is enough to prove that there is a set of three-sided intransitive dice for all possible number of dice using the result 3. We can also use the result 2 to prove that all set of odd-sided intransitive dice must exist, for every number of dice. In the same manner, we use the second example to show that all sets of even-sided intransitive dice must exist, for every number of dice. This is enough to prove the existence of all sets of intransitive dice but the ones with two faces.</p>

<p><img src="/images/posts/IntransitiveDices/tableExistencia.png" alt="Existence" title="Existence" style="float: right; width: 40%; margin=10px;" /></p>

<p>We therefore show, using simple techniques, that there are sets of intransitive dice for all possible number of dice and faces, except for the case where the dice have two faces. This is a very interesting result and comes directly from the representation we choose to use. This is one of the many advantages of a good model or representation when trying to prove a result in mathematics. However, we do not stop here. We can also determine how many sets of intransitive dice there are for each number of dice and faces. This is the goal of the next section.</p>

<h1 id="how-many-are-there">How many are there?</h1>

<p>This is harder. To count how many strings can be classified as intransitive, we would have to identify some properties in the strings that we couldn’t so far see. So far as we know, this isn’t straightforward. However, we do have some results in this direction. To get a feeling of the behaviour of the number of intransitive sets, we can simulate the number of intransitive sets for a given number of dice and faces. This is only possible for sets with few faces as the number of possible outcomes quickly gets out of hand. The table shows how many intransitive sets \(I(n)\) ouof the total amount of sets \(D(n)\) of three dice with a given number of faces we can have up to 10 faces.</p>

<p><img src="/images/posts/IntransitiveDices/RatioIntransitivee.png" alt="Quantidade" title="Quantidade" style="float: right; width: 50%; margin=10px;" /></p>

<p>This give us two main informations about the sequence \(I(n)/D(n)\): Firstly that it decreases fast as the number of faces increment. Secondly that it has two distinct curves of behaviour that seem to converge, one for the dice with odd-number of faces and other for the dice with even-number of faces. This is mostly bacause of the symmetry properties of a string that can’t express in odd-faced dice. Iw we wish to see how this behaviour extends to larger number of faces, we can’t compute deterministically the quantities. We will have to perform a stochastic orientered simulation of these dice. This is easy enough if we know how to mount and compare strings. Using this idea we extract the following curve.</p>

<p style="text-align:center">
<img src="/images/posts/IntransitiveDices/curves.jpg" alt="Curves" title="Curves" style="width: 90%; margin=10px;" />
</p>

<p>This strongly suggests that the ratio of intransitive sets to the total amount of sets of dice with a given number of faces converges to zero. Mathematically we can show that \(I(m+n) \geq I(m)I(n)\) by a combinatorial argument. This gives us, by feketes lemma, that</p>

\[\lim_{n \to \infty} \frac{\log(I(n))}{n} = L\]

<p>or equivalently that</p>

\[I(n) = e^{nL + o(n)}\]

<p>This, plus knowing the expression for \(D(n)\) gives us the following result</p>

\[\frac{I(n)}{D(n)} = (k + o(1))e^{-n(L - 3\log(3) + o(1))}\]

<p>where \(L\) determines the decaiment of the expression. The deterministic simulations gives us \( L \leq 3,23 \leq 3 \log(3)\). Stochastically, it goes to \(3\log(3)\) when we grow the number of faces. A later analysis indeed shown that \(L = 3\log(3)\) for the surprise of no one but to our satisfaction.</p>

<h2 id="a-note-on-random-graphs">A note on random graphs</h2>

<p>Someone may have noted at this point that the diagrams we used to represent the set of dice can be interpret as directed graphs. This is very interesting and a questions that might pop up is: Can we represent any graph with a set of dice: The answer is yes and the explication is surprisingly simple. Lets create a random graph such as the one below.</p>

<p style="text-align:center">
<img src="/images/posts/IntransitiveDices/graph.png" alt="graph" title="graph" style="width: 80%; margin=10px;" />
</p>

<p>The way we interpret the graph is: Every node is a die and every edge is a relation of victory of one die over the other. When there is a directed edge from node A to node B, it means that A beats B. If there isn’s an edge, this means the dice tie.</p>

<p>The proof is by procedure. We take a symmetric string such that it has the same number of dice as the graph has of nodes. At this point, we have no edges. To generate an edge we can concatenate a symmetric string to the main string and swap the position of the letters of the two nodes we want the relation to change. This can always be done leaving the two letter in the middle of the symmetric string concatenated. In this manner, we don’t change the relation of the other dice. This is enough to show that we can represent any graph with a set of dice. An open question, however, would be the minimum number of faces we need to represent a graph with a set of dice.</p>

<hr style="height:1px;border-width:0;color:gray;background-color:gray" />

<h1 id="a-central-limit-theorem-for-intransitive-dice">A central limit theorem for intransitive dice</h1>

<p>This section is here to simply enunciate the main result of our work that was: A central limit theorem for the vector of normalized victories of a die against the next one in the list when the faces of a die are i.i.d. random variables and all dice are independent. This is a very elegant and interesting result that I definetely won’t go into detail in this post. However I do feel you can get an idea for the result by the simple enunciation of it. The main corollary of the central limit theorem is that, for the dice we considered,</p>

\[\lim_{n\to\infty}\frac{I(n)}{D(n)} = p(X, Y, Z&gt;0)+p(X, Y, Z&lt;0) \le p((X, Y, Z)\in G^c) = 0.\]

<p>Let me explain. First, the variables \(X, Y, Z\) are the normalized victories of a die against the next one. This means that it keeps, respectively, how many more victories A has over B, B has over C and C has over A. If \(X\) is positive, it means that A has more victories over B than B has over A. The same goes for \(Y\) and \(Z\). The set \(G^c\) is such that</p>

\[(x, y, z) \in G^c \Leftrightarrow x + y + z \neq 0.\]

<p>The corollary then is saying to us that the probability of the sets being intransitive is less than, or equal, the probability of the set of dice belonging to the set \(G^c\). With three dice this corresponds to two octants of the space of the variables \(X, Y, Z\). In fact, our main theorem shows that the mulvariate distribution converges to the plane \(x + y + z = 0\) with distribution</p>

\[\frac{1}{3\pi} e^{-\frac{2}{9} (x^2 + y^2 + z^2-xy-yz-zx)},\]

<p>as the number of faces grows, as shown in the image below. With this, we can say that the probability of the set of dice being intransitive goes to zero when the number of faces grows.</p>

<p style="text-align:center">
<img src="/images/posts/IntransitiveDices/Octantes.png" alt="Octantes" onmouseover="this.src='/files/posts/IntransitiveDice/Octantes.gif'" onmouseout="this.src='/images/posts/IntransitiveDices/Octantes.png'" title="Simulation Octantes" style="width: 50%" />
<img src="/images/posts/IntransitiveDices/hyperplane.png" alt="Hyperplane" title="Hyperplane" style="width: 40%" />
</p>

<p>The same idea is confirmed in the simulations performed. This can be seen in the GIF above.</p>

<hr style="height:1px;border-width:0;color:gray;background-color:gray" />

<p>If you speak Portuguese, you can also watch the video below as a complement to this post.</p>

<iframe width="560" height="315" src="https://www.youtube.com/embed/fHEBWL0weVk?si=ymxzfrxzZuzFXN0E" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen=""></iframe>]]></content><author><name>João V. A. Pimenta</name><email>joaovictorpi[...]@usp.br</email></author><category term="Easy" /><category term="Probability" /><category term="Analytical" /><summary type="html"><![CDATA[How to discuss a intransitive dice problem in a mathematical way and what can we prove about it?]]></summary></entry><entry><title type="html">N-dimensional Spheres: Monte Carlo Estimation</title><link href="https://joao-vap.github.io//posts/2024/07/MonteCarlo/" rel="alternate" type="text/html" title="N-dimensional Spheres: Monte Carlo Estimation" /><published>2024-07-20T00:00:00-07:00</published><updated>2024-07-20T00:00:00-07:00</updated><id>https://joao-vap.github.io//posts/2024/07/MonteCarlo</id><content type="html" xml:base="https://joao-vap.github.io//posts/2024/07/MonteCarlo/"><![CDATA[<p>What is the volume of an n-dimensional sphere?</p>

<p>Let’s start on the basics. Consider the famous 2-dimensional sphere, the circle. We know that its area is given by the formula</p>

\[A = \pi r^2\]

<p>where \(r\) is the radius of the circle. The volume (in this case the area, of course) of a circle depends therefore on its radius squared and is proportional to \(\pi\). To simplify the discussion, and without loss of generality, let’s consider spheres with radius 1. The volume of a 2-dimensional sphere is then \(\pi\). Of course we could perform the integration in polar coordinates</p>

\[V_2 = \int_0^{2\pi} \int_0^1 r dr d\theta = \pi\]

<p>to determine the volume. This is easy enough, and we could, equivalently, perform it for 1 and 3-dimensional spheres, whose volumes are</p>

\[V_1 = \int_{-1}^1 dx = 2\]

<p>and</p>

\[V_3 = \int_0^{2\pi} \int_0^\pi \int_0^1 r^2 \sin(\theta) dr d\theta d\phi = \frac{4}{3}\pi\]

<p>respectively. But what about higher dimensions? We won’t perform the integration for those spheres, not analytically at least. Instead, we will use an numerical approach.</p>

<h1 id="estimating-volumes">Estimating Volumes</h1>

<p><img src="/images/posts/MonteCarlo/gridIlustration.png" alt="Illustration Grid Method" title="Illustration Grid Method" style="float:right; width: 40%; margin=10px;" /></p>

<p>Let’s take the 2-dimensional case for the sake of visualization. We can of course determine the area of the unit circle by the following procedure: Divide the unit square into a equally divided grid of \(N \times N\) points, and count the number of points that fall inside the circle. The ratio of points inside the circle to the total number of points give us an estimate of the area of the circle, that is</p>

\[\frac{N_{\text{inside}}}{N_{\text{total}}} = \frac{A_{\text{circle}}}{A_{\text{square}}}\]

<p>where we know \(A_{\text{square}} = 4\). This estimative takes the computing of \(N^2\) points. More generally, in \(D\) dimensions, it would take \(N^D\) points. Let’s check how precise it is and how much time it takes to compute its estimation.</p>

<p style="text-align:center">
<img src="/images/posts/MonteCarlo/graphsGrid.png" alt="Area Estimation" title="Area Estimation" style="display: block; width: 100%; margin=10px;" />
</p>

<p>In the top row we see the estimated volume of the 2-dimensional sphere for a progression of values of \(N\) and the respective time it took to estimate it. Here, the measure of time is not that important and is mostly affected by the computer fluctuations in computing. Nevertheless we can see the value approaching \(pi\) is a somewhat monotonous manner. Where things get interesting is when we extend to higher dimensions. The bottom row shows the estimated volume of the n-dimensional unit sphere for \(N = 100\) and the respective time it took to estimate it. First, as one could expect, the volume increases up to the fourth dimension. Furthermore, we can also more clearly see that times gets progressively impeditive. This is beacuse the amount of computing grows exponentially with the dimension. Ok, time is definitely a problem. The way to solve this problem is to use the Monte Carlo method.</p>

<h1 id="monte-carlo-method">Monte Carlo Method</h1>

<p>The idea behind the Monte Carlo method is to sample estochastically the space of interest based on some distribution. In this way we can numerically integrate some function of interest by using the resulting samples. A bit more formally the Monte Carlo method is of help to calculating the following expectation value</p>

\[\mu = E[f(x)] = \int f(x) p(x) dx\]

<p>where \(f(x)\) is some function of interest and \(x\) is a random variable based on some distribution of interest. If for some reason we can’t perform the integral analytically, be that because of the complexity or randomness of the system at hand, we can use the Monte Carlo method to estimate the expectation value. Of course, if you can sample the variable \(x\) from the distribution you can simply calculate</p>

\[\mu \approx \frac{1}{N} \sum_{i=1}^N f(x_i)\]

<p>where \(x_i\) are independent and identically distributed samples from the distribution of interest. To prove the conversion is a matter of fundamental statistics, it relies heavily on the law of large numbers. This simple idea is very powerfull and allows us to sample from some very complex distributions asociated for example with the solution for coupled differential equations or the partition function of a system of particles. To illustrate this idea, let’s return to the simulation of the volume of the unit sphere. Hovewer we will now sample uniformly from the unit cube and count how many of the points fall inside the unit sphere. As before, the ratio of points inside the sphere to the total number of points gives us an estimate of the volume of the sphere. For this visualization, I’ll run the Monte Caro method untill I get an as good estimation of the volume and regster the amount of samples it took to get there. The results of the ratio of poins needed before and with this method are shown in the following figure for some dimensions.</p>

<p style="text-align:center">
<img src="/images/posts/MonteCarlo/Comparison.png" alt="Volume Comparison" title="Volume Estimation" style="display: block; width: 100%; margin=10px;" />
</p>

<p>The main point is that we need to use a incredible smaller quantity of points to get the same precision. This idea can be explored to overcome the problem of the dimensionality increase of complexity in our program. All results can be replicated with the following (not very organized) code resource <a href="/files/posts/MonteCarlo/SphereVolum.py">Sphere Volume</a>. The Monte Carlo method returns the following results for the volumes of the unit spheres</p>

<p><img src="/images/posts/MonteCarlo/SphereVolumes.png" alt="Volume Estimation d-dimensions" title="Volume Estimation" style="display: block; width: 100%; margin=10px;" /></p>

<p>Well, first of all, my choosing of the quantity of points was half-arbitrary. I was interested in the general behavior of the curve and you may guess why now. There is a peak in the volumes of the n-dimensional unit spheres. This is weird but not too much. You can think of it as the effect of the volume of the cube that contains the sphere simply growing faster than the volume of the sphere. This is the effect of the high-dimensionality. I’ve been holding on to this, but there is a explicit formula for the volume of the n-dimensional sphere. It is given by</p>

\[V_n = \frac{\pi^{n/2}}{\Gamma(n/2 + 1)}\]

<p>where \(\Gamma\) is the gamma function. With this we can be more explicit about this volume and calculate the curve to be</p>

<p><img src="/images/posts/MonteCarlo/SphereVolumesExplicit.png" alt="Volume Estimation d-dimensions" title="Volume Estimation" style="display: block; width: 100%; margin=10px;" /></p>

<p>where we can clearly see the peak to be in \(n = 5\). This always baffled me. I may just enjoy too much maximums in these ‘natural’ situations. Nature and Mathematics are usually so equal on its dimensions, I find it amusing when it decides to have some weird behavior.</p>]]></content><author><name>João V. A. Pimenta</name><email>joaovictorpi[...]@usp.br</email></author><category term="Medium" /><category term="Monte Carlo" /><category term="Numerical" /><summary type="html"><![CDATA[What is the volume of an n-dimensional sphere?]]></summary></entry><entry><title type="html">What is the BuddhaBrot after all?</title><link href="https://joao-vap.github.io//posts/2024/07/BuddhaBrot/" rel="alternate" type="text/html" title="What is the BuddhaBrot after all?" /><published>2024-07-17T00:00:00-07:00</published><updated>2024-07-17T00:00:00-07:00</updated><id>https://joao-vap.github.io//posts/2024/07/BuddhaBrot</id><content type="html" xml:base="https://joao-vap.github.io//posts/2024/07/BuddhaBrot/"><![CDATA[<p>The Buddhabrot is weird. I don’t understand it.</p>

<p style="text-align:center">
  <img src="/images/posts/BuddhaBrot/b1.png" width="30%" />
  <img src="/images/posts/BuddhaBrot/b2.png" width="30%" />
  <img src="/images/posts/BuddhaBrot/b3.png" width="30%" />
</p>

<p>Although there is not much ground to cover until we get to the BuddhaBrot, we need to first understand and learn how to simulate the so called Mandelbrot set. Which is interesting by itself. There is much to be said about its connections with other sets, fractal theory, and even chaos in general, particularly the relation to the logistic map. I will not, however, talk about many of those, as I said, I do not understand the BuddhaBrot. Nevertheless, I feel compelled to it. There is something to be said about the other driving forces of a mathematician. Beauty, sometimes, is enough.</p>

<p><img src="/images/posts/BuddhaBrot/butterfly.jpeg" width="100%" /></p>

<h1 id="the-mandelbrot-set">The Mandelbrot Set</h1>

<p><img src="/images/posts/BuddhaBrot/Mandelbrot.png" alt="Mandelbrot Set" style="float: right; width: 30%; margin-left: 10px;" /></p>

<p>We shall then start at the Mandelbrot set. This is nothing more than a set of complex numbers bounded by some rule. This is done in the same way we would do to define a circle in the plane, that is, defining a set such as</p>

\[\{z \in \mathbb{C} : |z| \leq 1\}\]

<p>that represents the unit circle. In a similar sense, the Mandelbrot set is defined as the set of complex numbers \(c\) for which the sequence \((z_n)\), defined by</p>

\[z_{n+1} = z_n^2 + c\]

<p>is bounded. That is, if you iterate on \(z_k\), you will get an finite number when \(k\) goes to infinity. If you then plot this set of points you end up with what we call the Mandelbrot set.</p>

<p><img src="/files/posts/BuddhaBrot/gifMandelbrot.gif" alt="Mandelbrot Set Gif" style="float: left; width: 30%; margin-right: 10px;" onmouseover="this.src='/files/posts/BuddhaBrot/gifMandelbrot.gif'" /></p>

<p>There are some considerations if we wish to simulate it. We, of course, do not iterate every point of the grid to infinity. Among those arbitrary points of the grid we choose to iterate, we say that they diverge if, after a certain threshold, they have an absolute value greater than 2. Selecting a threshold is a matter of art and intent. We also choose to color the set (mainly its borders) by how many iterations it took to ‘diverge’. That is, for those that don’t diverge, we will plot the threshold value, and for the rest, we will plot the number of iterations it took to surpass the radius defined previously. If you’re anything like me, you already defied some definitions here: What happens if we use something other than \(z^2\)? What is the set appearance for different constants \(z_0\)? I won’t explicitly answer those, but the GIF nearby illustrate one of this situations. Feel free to explore, the code necessary to do it is in <a href="/files/posts/BuddhaBrot/Mandelbrot.py">Mandelbrot</a>. Here are some close-ups of the Mandelbrot set.</p>

<p style="text-align:center">
  <img src="/images/posts/BuddhaBrot/Mz1.png" width="30%" />
  <img src="/images/posts/BuddhaBrot/Mz3.png" width="30%" />
  <img src="/images/posts/BuddhaBrot/Mz2.png" width="30%" />
</p>

<p>The amount of programming it takes to simulate the Mandelbrot is minimal. But somehow, this is a very interesting mathematical object. Mainly, we will discuss it as a fractal. A fractal is a set with a fractal dimension. Well, that doesn’t help very much. How can something have a fractal dimension? We know about lines with dimension 1, and we know about planes with 2 dimensions. How can some objects have 1.4 dimensions? Well, first, we need to be sure about the meaning of a line having 1 dimension or the plane having 2. We could talk about the orthogonal basis, but that’s too sophisticated. Another way to define dimensions is using self-similarity.</p>

<p><img src="/images/posts/BuddhaBrot/Mz4.png" alt="Zoom of Mandelbrot" style="float: block; width: 100%;" /></p>

<p>If we take a line and divide it into 2 equal parts, we get 2 lines. Each of those can be scaled by 2 to get the original line. If we, instead, divide it into 3 parts, we should scale each of those parts by 3 to get the original line. That is, diving by \(N\) demands a scale of \(N\). What about a square? We now can’t divide the square by 2 or 3 self-similar parts. But we can divide it by 4, and each of those squares must be scaled by 2 to get the original square. Generally, we can divide by \(N^2\) parts, and each of those must be scaled by \(N\) to get the original square. This introduces the idea that those objects have different dimensions. Dimension is simply the exponent of the scale factor. That is, a line is of dimension 1, a square is of dimension 2. What about the following set?</p>

<p><img src="/images/posts/BuddhaBrot/serpiensky.png" alt="Serpiensky Triangle" style="float: right; width: 50%;" /></p>

<p>This is the Serpiensky Triangle, a fractal of dimension 1.58. Actually, producing this set is very interesting. We start with 3 points in the complex plane. We then choose a random point on the plane and plot it. We select one of the 3 points at random and plot the point in the middle of the line between the random point and the chosen point. Repeat this process. Somehow, this generates this fractal.</p>

<p>How do we calculate its dimension?</p>

\[\text{dimension} = \frac{\log(\text{#self-similar pieces})}{\log(\text{scale factor})}\]

<p>In this case</p>

\[\text{dimension} = \frac{\log(3)}{\log(2)} = 1.58\]

<p>The Mandelbrot set has dimension 2 somehow, this is just so interesting. About its borders, if you search for an infinite dive into the details of the Mandelbrot, you will find an infinitude of videos. Otherwise, if you wish to test this fact and focus on any specific area of the border, no matter how small (respected the limits of the computer, of course) you can use the code provided. You will find more and more details for a nausiating and fascinating amount to whatever interval you end up in.</p>

<h1 id="the-buddhabrot">The Buddhabrot</h1>

<p>We have so far overlooked a set of numbers complementary to the Mandelbrot set. This is the Buddhabrot. This set is defined by the set of complex numbers \(c\) for which the sequence defined by</p>

\[z_{n+1} = z_n^2 + c\]

<p>diverges. We won’t plot the set, however. What is the path of the diverging points? The density of those paths is represented in the Buddhabrot visualization. In this way, we simply get random points in the complex plane and iterate them. If they diverge, we plot the path they take. There are some optimizations to be made, like excluding points that are obviously inside the Mandelbrot set. The code to do this is in <a href="/files/posts/BuddhaBrot/Buddhabrot.py">Buddhabrot</a> and the plot file is the <a href="/files/posts/BuddhaBrot/plotBuddha.py">Plot</a>. There is no secret to this part.</p>

<h2 id="some-artistic-liberties">Some Artistic Liberties</h2>

<p>Clearly, a 2D array with numbers doesn’t transform itself in these cool pictures simply plotting the numbers. You can simply plot it with a nice colormap, this will be fine. However, if you’re trying to add a little more flare to the image, here’s what you can do: Firstly, get comfortable with the variables in the generation process, those are going to define which characteristics will be clear in your plot. Mainly, worry about the quantity of points you’re using and how many iterations you’re recording. As the points diverge, if you record long paths, you will see some semi-stable orbits highlighted. If you record short paths, you will get a more blurry image.</p>

<p style="text-align:center">
  <img src="/images/posts/BuddhaBrot/baseR.png" width="30%" />
  <img src="/images/posts/BuddhaBrot/baseB.png" width="30%" />
  <img src="/images/posts/BuddhaBrot/baseG.png" width="30%" />
</p>

<p>The second step is composing. We will generate an RGB image composing the three channels, each with any characteristic of the Buddhabrot you choose to highlight. Then, in any editing software, you will superpose those images and merge them with one of the many blending modes. With this, you can create any of these images.</p>

<p style="text-align:center">
  <img src="/images/posts/BuddhaBrot/b21.png" width="30%" />
  <img src="/images/posts/BuddhaBrot/b22.png" width="30%" />
  <img src="/images/posts/BuddhaBrot/b23.png" width="30%" />
</p>

<p>I do not understand the Buddhabrot, but look at it. This time, beauty is enough.</p>]]></content><author><name>João V. A. Pimenta</name><email>joaovictorpi[...]@usp.br</email></author><category term="Easy" /><category term="Mandelbrot" /><category term="Artsy" /><summary type="html"><![CDATA[The Buddhabrot is weird. I don’t understand it.]]></summary></entry><entry><title type="html">The drawings of Fourrier</title><link href="https://joao-vap.github.io//posts/2024/07/FourrierDrawing/" rel="alternate" type="text/html" title="The drawings of Fourrier" /><published>2024-07-16T00:00:00-07:00</published><updated>2024-07-16T00:00:00-07:00</updated><id>https://joao-vap.github.io//posts/2024/07/FourrierDrawing</id><content type="html" xml:base="https://joao-vap.github.io//posts/2024/07/FourrierDrawing/"><![CDATA[<p>My long obsession: the Fourries Series.</p>

<p><img src="/images/posts/Fourrier/eu.png" alt="Fourrier Drawing" style="float: right; width: 30%;" /></p>

<p>There is something ming boggling about the theory behind Fourrier Series, and more generally, the Fourrier Transform. It is a simple and elegant theory that allows us to represent functions in terms of the frequencies of oscilating basis that compose them. I cannot overstate how many application this theory has. We will, however, use it do draw some fun pictures. To get there, let’s very briefly go through the theory, although in our application we will simply use a python library. Maybe next time we can implement it with a fun twist: The Fast Fourrier Transform. More importantly, as I would never make a bettet job than 3Blue1Brown in the theory aspect, I will leave the following important links if you’re interested.</p>

<ul>
  <li><a href="https://www.youtube.com/watch?v=r6sGWTCMz2k&amp;list=PLZHQObOWTQDN52m7Y21ePrTbvXkPaWVSg">Fourrier Series</a></li>
  <li><a href="https://www.youtube.com/watch?v=spUNpyF58BY&amp;list=PLZHQObOWTQDN52m7Y21ePrTbvXkPaWVSg&amp;index=6">Fourrier Transform</a></li>
</ul>

<p>With the context set, let’s work some background on the math. Don’t worry too much about this section, I just want to set some context.</p>

<h1 id="fourrier-series">Fourrier Series</h1>

<p>Consider a function \(f(x)\) defined in the interval \([-T, T]\). We say that</p>

<p>\[ f(x) = \frac{a_0}{2} + \sum_{k=1}^{\infty} a_k \cos\left(\frac{\pi k x}{T}\right) + b_k \sin\left(\frac{\pi k x}{T}\right) \]</p>

<p>is the Fourrier Series of \(f(x)\) in the interval \([-T, T]\). The coefficients \(a_k\) and \(b_k\) say how much of the frequency \(k\) is in the function \(f(x)\), note that every different frequency is orthogonal to each other. This is simply representing the function in term of its geometric components. Similar in a way to a Taylor Series, wich expands the function in a polynomial basis. Notice that the resulting function is periodic with period \(2T\) because of the properties of the sines and cosines. How do we get the value of the coeficients?</p>

<p>Fact is that we can find the coefficients by multiplying both sides of the Fourrier Series by \(\cos\left(\frac{\pi l x}{T}\right)\) or \(\sin\left(\frac{\pi l x}{T}\right)\) and integrating over the interval \([-T, T]\). This has a nice interpretation. When we integrate the function multiplied by alternating cosines and sines, we know to expect something other than zero if the function alternates signs along with the cosine or sine. Otherwise, it would generally go to zero as we integrate the interval. As of this scenario This is beacause the area would be positive, of course. This is equivalent to say that the function has a component of that frequency, or that is expressed with non zero coeficient in that basis vector.</p>

<p>We then know that multiplying the function by those sines and cosines we would be filtering orthogonal vectors, that is, frequencies. We wont go through the details of the calculations, but it is elucidative to see how it is done. For that, we have should remember the propeties of the trigonometric functions. That is</p>

\[\int_{-T}^{T} \cos\left(\frac{\pi k x}{T}\right) \cos\left(\frac{\pi l x}{T}\right) dx = \begin{cases} 0 &amp; \text{if } k \neq l \\ T &amp; \text{if } k = l \end{cases}\]

\[\int_{-T}^{T} \sin\left(\frac{\pi k x}{T}\right) \sin\left(\frac{\pi l x}{T}\right) dx = \begin{cases} 0 &amp; \text{if } k \neq l \\ T &amp; \text{if } k = l \end{cases}\]

<p>e</p>

\[\int_{-T}^{T} \cos\left(\frac{\pi k x}{T}\right) \sin\left(\frac{\pi l x}{T}\right) dx = 0\]

<p>Therefore, multiplying both sides of the Fourrier Series by \(\cos\left(\frac{\pi l x}{T}\right)\) and integrating over the interval \([-T, T]\) we get</p>

\[\begin{eqnarray}
  \int_{-T}^{T} f(x) \cos\left(\frac{\pi l x}{T}\right) dx &amp;=&amp; \frac{a_0}{2} \int_{-T}^{T}  \cos\left(\frac{\pi l x}{T}\right) dx  \\
  &amp;+&amp; \sum_{k=1}^{\infty} a_k \int_{-T}^{T} \cos\left(\frac{\pi k x}{T}\right) \cos\left(\frac{\pi l x}{T}\right) dx \\
  &amp;+&amp; \sum_{k=1}^{\infty} b_k \int_{-T}^{T} \sin\left(\frac{\pi k x}{T}\right) \cos\left(\frac{\pi l x}{T}\right) dx
  \end{eqnarray}\]

<p>The first and third terms of the right hand side are always zero. The second term however is equal to \(a_l T\) only when \(l = k\). Therefore, we get</p>

\[a_k = \frac{1}{T} \int_{-T}^{T} f(x) \cos\left(\frac{\pi k x}{T}\right) dx \ \ \text{,for} \ n \neq 0\]

<p>The same can be done for the sine, and we get</p>

\[b_k = \frac{1}{T} \int_{-T}^{T} f(x) \sin\left(\frac{\pi k x}{T}\right) dx \ \ \text{,for} \ n \neq 0\]

<p>The coefficient \(a_0\) is given by</p>

\[a_0 = \frac{1}{T} \int_{-T}^{T} f(x) dx\]

<p>We have now a way to find the coefficients of the Fourrier Series. We can decompose any function in terms of its frequencies.</p>

<h1 id="note-about-the-discrete">Note about the discrete</h1>

<p><img src="/images/posts/Fourrier/angela.png" alt="Fourrier Drawing" style="float: right; width: 30%;" /></p>

<p>We neew to have some care if we want to be precise in this case. Naturally, we are testing for a finite number of frequencies. This means that if we were, for example, expressing a cosine function with a frequency that is not being used for the composition, this would be expressed as a distribution of frequencies around the one we are testing. When using discrete data, we cannot either identify frequencies that are higher than the so called Nyquist frequency. That is, the sampling rate of the data used. This is natural as the detail of those oscillations would e lost inbetween the data points. The Nyquist theorem is a highly important theorem in signal processing and deserves much more thought than I am giving here, however, it won’t be our focus.</p>

<h1 id="a-complex-extension">A complex extension</h1>

<p>Assume a time series that takes values in the complex plane. We can extend the Fourrier Series to complex numbers. That is, we can write</p>

\[f(x) = \sum_{n=-\infty}^{\infty} c_n e^{i \frac{2 \pi n x}{T}}\]

<p>where the coefficients are given by</p>

\[c_n = \frac{1}{T} \int_{-T}^{T} f(x) e^{-i \frac{2 \pi n x}{T}} dx\]

<p><img src="/images/posts/Fourrier/paulita1.png" alt="Fourrier Drawing" style="float: left; width: 30%;" /></p>

<p>The idea is the same as we discussed previously. We are representing the function in terms of its frequencies. The difference is that now we are using complex exponentials and summing over the negative frequencies as well. This is a natural way to represent a complex time series. Now we can take any arbitrary curve (well, maybe not any, but all we’re dealing) and write it in term of its frequencies.</p>

<p>Wen we talk about these complex time series, as these that are illustrating the post, we say we want to decompose its frequecies components. What does that mean visually? The links I’ve exposed in the begining of the text say this too well. We can think of the complex numbers as vectors in the complex plane. The complex exponential is a vector that rotates in the complex plane. The frequency of the complex exponential is the frequency of the rotation. The coefficients \(c_n\) are the amplitudes of the rotations. The Fourrier Series is then a sum of rotations of different frequencies and amplitudes. In te end, we have a multitude of rotating vectors that write our curve. This is simply beautiful.</p>

<h1 id="going-beyond-and-having-fun">Going beyond and having fun</h1>

<p>If we can choose an arbitrary curve, nothing stop us from having fun with it. The idea for this post is to draw photographs and do some cool art.</p>

<p><img src="/images/posts/Fourrier/ambos.png" alt="Fourrier Drawing" style="display: block;  margin: auto; width: 90%;" /></p>

<p>The first challenge is to get a complex time series from the picture we start with. The first aspect of the project is then to have an appropriate picture. This, for me, was solved drawing my own pictures. There is a change you can do this to some easy simple pictures, I have tried some and had some success but this will depend highly on the next step. The process now depends on your image. If you have a png or anything like it, we will need to extract by force the series. This is, at least for me, a hard task. The idea is to first diminish the quality of the picture so that we can start to see the single pictures in the curve. This is beacause now we can interpret the points/pixels as data from a time series. However the points are not ordered, it is not yet a time series. This is the hard part. A way to order would be to interpret those points as vertices of a graph and then find the shortest path that connects all the vertices (or at least most of them). This is basically the Traveling Salesman Problem. A highly non-trivial problem that you can try and find partial solutions around. If that’s to much, for some curves it is possible to just find the closest point untill the last one. This won’t suffice for most curves. If youre doing your own drawings, you can facilitate the process separating it into pieces and then tying them together afterwards. This is what I do when I want to intersect curves.</p>

<p>The other option is to know the order of the points. We will use SVGs files.</p>

<h1 id="inserting-svgs-and-finishing-up">Inserting SVGs and Finishing up</h1>

<p>SVGs are vectorial images. This means that the image is decomposed in many components. Those components can be mathematical curves, lines, circles, etc. An exemple of a SVG file is the following where I (very skyllfully may I add ;) ) drew a person holding a board.</p>

<p style="text-align:center">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1"> 
<circle cx="50" cy="50" r="10" stroke="black" stroke-width="3" />
<line x1="30" y1="100" x2="30" y2="70" style="stroke:black;stroke-width:2" />
<line x1="30" y1="100" x2="50" y2="70" style="stroke:black;stroke-width:2" />
<line x1="70" y1="100" x2="50" y2="70" style="stroke:black;stroke-width:2" />
<line x1="50" y1="130" x2="50" y2="50" style="stroke:black;stroke-width:2" />
<line x1="50" y1="130" x2="30" y2="160" style="stroke:black;stroke-width:2" />
<line x1="50" y1="130" x2="70" y2="160" style="stroke:black;stroke-width:2" />
<ellipse cx="80" cy="75" rx="15" ry="75" style="fill:white;stroke:black;stroke-width:2" />
</svg>
</p>

<p>The elements of the image are as follows:</p>

<pre>
〈svg xmlns="http://www.w3.org/2000/svg" version="1.1" 〉 
〈circle cx="50" cy="50" r="10" stroke="black" stroke-width="3"/〉
〈line x1="30" y1="100" x2="30" y2="70" style="stroke:black;stroke-width:2" /〉
〈line x1="30" y1="100" x2="50" y2="70" style="stroke:black;stroke-width:2" /〉
〈line x1="70" y1="100" x2="50" y2="70" style="stroke:black;stroke-width:2" /〉
〈line x1="50" y1="130" x2="50" y2="50" style="stroke:black;stroke-width:2" /〉
〈line x1="50" y1="130" x2="30" y2="160" style="stroke:black;stroke-width:2" /〉
〈line x1="50" y1="130" x2="70" y2="160" style="stroke:black;stroke-width:2" /〉
〈ellipse cx="80" cy="75" rx="15" ry="75" style="fill:white;stroke:black;stroke-width:2" /〉
〈/svg〉
</pre>

<p>Here I didn’t use very complex elements, but as long as they are in the SVG format, we can extract the points from the curves. A full guide of the elements can be found on <a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Element">Mozilla Guide</a>. This is the best way to get the time series. We can just extract the points from the curves cause we know how to construct these objects.</p>

<p><img src="/images/posts/Fourrier/JIP.svg" alt="Fourrier Drawing" style="display: block;  margin: auto; width: 70%;" /></p>

<p>From that on the program is very easy. We first take the elements on te SVG and extract points from the construction of each of those in order. The interpretation of the elements can be done with a parser from a python library named svgpathtools. This is done in <a href="/files/posts/Fourrier/svgPathToSeries.py">Svg -&gt; Path</a>.</p>

<p style="text-align:center">
<img src="/images/posts/Fourrier/JIPgif.png" alt="Fourrier Drawing" onmouseover="this.src='/files/posts/Fourrier/JIP.gif'" onmouseout="this.src='/images/posts/Fourrier/JIPgif.png'" style="width: 50%" />
</p>

<p>The only thing remaining now is to take the time series and apply the Fourrier Transform. This is done in <a href="/files/posts/Fourrier/FourrierTransform.py">Fourrier Transform</a>. We won’t go through the implementation of the series calculation. Instead, we will use numpy to that for us better than I ever could. In this way we get a function of sines and cosines that render such as the GIF displayed above.</p>

<h1 id="some-results">Some Results</h1>

<p>For completness, here are some of the images shown and it’s series. Have fun with it!</p>

<p style="text-align:center">
<p style="text-align:center">
  <img src="/images/posts/Fourrier/feu.png" width="30%" />
  <img src="/images/posts/Fourrier/fpaulina.png" width="30%" />
  <img src="/images/posts/Fourrier/fangela.png" width="30%" />
</p>
<p style="text-align:center">
  <img src="/images/posts/Fourrier/fambos.png" width="90%" />
</p>
<p style="text-align:center">
  <img src="/images/posts/Fourrier/JIP.png" width="90%" />
</p>
</p>]]></content><author><name>João V. A. Pimenta</name><email>joaovictorpi[...]@usp.br</email></author><category term="Medium" /><category term="Fourrier" /><category term="Artsy" /><summary type="html"><![CDATA[My long obsession: the Fourries Series.]]></summary></entry><entry><title type="html">The Voyager and our Golden Record</title><link href="https://joao-vap.github.io//posts/2024/07/VoyagerGoldenRecord/" rel="alternate" type="text/html" title="The Voyager and our Golden Record" /><published>2024-07-15T00:00:00-07:00</published><updated>2024-07-15T00:00:00-07:00</updated><id>https://joao-vap.github.io//posts/2024/07/VoyagerGoldenRecord</id><content type="html" xml:base="https://joao-vap.github.io//posts/2024/07/VoyagerGoldenRecord/"><![CDATA[<p>I can’t get over the Voyager mission.</p>

<h1 id="context">Context</h1>

<p>Ok, maybe I should start with some context of what I’m talking about. The Voyager mission consisted of two spacecraft launched by NASA in the 1970s. On paper, the main mission was to explore Jupiter and Saturn by hovering close by. Voyager 2 extended its route to Uranus and Neptune and is still the only spacecraft to have approached those planets. This, by itself, is already pretty impressive and a major achievement for NASA and all of humanity. More details can be found on <a href="https://voyager.jpl.nasa.gov/mission/">NASA’s website</a>. However, that part of the mission won’t be the focus of this post.</p>

<p><img src="/images/posts/Voyager/voyager.png" alt="Artistic Conception of Voyager" width="50%" style="float: right; margin-right: 5px;" /></p>

<p>There are some monumental moments that mark history. Legend has it that one of them was produced by the brilliant Carl Sagan. Once the Voyager 1 mission had surpassed Pluto’s orbit, it turned around its cameras and took pictures of the solar system as seen by an outsider. It is said that it was Sagan who was responsible for that decision. Either way, it produced one of the most impressive media I’ve seen, a picture that has been called the <a href="https://science.nasa.gov/mission/voyager/voyager-1s-pale-blue-dot/">“pale blue dot”</a>  in reference to the appearance of the Earth from the spacecraft perspective. This picture, as discussed in the incredible documentary ‘Cosmos’, by Sagan itself, was intended to give perspective on the magnitude of our planet (and ourselves) in the infinitude of the Cosmos.</p>

<p>Today, those spacecraft are still traveling and making sporadic contact with us. They are, as of now, the furthest from Earth that any man-made object has ever been, and they are still distancing themselves. Someday they will no longer be in contact or active, but they will still be wandering the Cosmos. This is the intent. Intentionally I have not, so far, commented on the most interesting aspect of this mission: <a href="https://voyager.jpl.nasa.gov/golden-record/">The Golden Record</a>. This is a vinyl that accompanies the spacecraft, containing recordings of sounds and images of Earth and its inhabitants. Why? The hope is that the spacecrafts survive traveling in space for an enormous amount of time, convering a long distamce. By cointaining in themselves a snapshot of our planet, they could then be found by some other civilization that would be able to learn about us. If you’re not familiar with the Golden Record, one of your questions may be how such a civilization would go about interpreting a mysterious object from space. This is what they tried to solve with the instructions on the record’s cover. Of course, such instructions couldn’t be done in written language, so they used a mix of depictions of mathematical and physical concepts that we think are natural for any scientifically driven civilization to stumble upon. There are many assumptions made here. Firstly, we suppose that whoever finds it will be interested in the object at all. This is because we like to think that they should; we would be, wouldn’t we? The second assumption is that those concepts are universal and should compose the basic understanding of every scientific community in any corner of the universe.</p>

<p><img src="/images/posts/Voyager/VoyagerCoverDiagram.jpg" alt="Golden Record Cover" width="65%" style="float: left; margin-left: 3px;" /></p>

<h1 id="decoding">Decoding</h1>

<p>The cover then describes how the information is encoded. The main idea is: Images are codified in audio in such a way that it has the profile shown in the upper right corner of the image displayed (courtesy of NASA). Each image using 512 lines of resolution. The separation between frames is done by a prominent negative value, and between images, we have the zig-zag patterns. I haven’t found one good source as to how to decode the audio in its entirety. I think I am then responsible to write a short how-to and make the source code avaible. However, there is a very good blog post done by <a href="https://boingboing.net/2017/09/05/how-to-decode-the-images-on-th.html">Ron Barry</a>, where he goes through the process of understanding the cover and plotting some images. But of course, I’m not satisfied with manually selecting the sections of the audio for each of the images and reconstructing them according to the cover; that would take me an hour! I have therefore spent a few days automating this process in a sometimes reliable program. Isn’t generalizing the instinct of every mathematician? ;)</p>

<p style="text-align:center">
  <audio controls="1" controlslist="nodownload nofullscreen noremoteplayback" src="/files/posts/Voyager/Voyager-Golden-Record.mp3">
    Your browser does not support the audio element.
  </audio>
</p>

<p>As far as I know, this is the only recording available on the internet of the Golden Record. And it’s kind of bad. First, it is sped up 2x from the intended record velocity. Second, the microphone used introduces a lot of noise and artifacts into the audio. As an example, the zig-zag pattern appears somehow damped; this may manifest in weird ways on the image. However, it is not incapacitating and we may continue.</p>

<p style="text-align:center">
  <img src="/images/posts/Voyager/Voyager-zig-zag.png" alt="Golden Record Audio" width="70%" />
</p>

<p>Our first challenge is to identify the zig-zag regions and separate the recording into sections, one for each of the images that it should contain. One possible approach is to identify the main frequencies in each region, as the images sections will have a wider range than the separators. However, a more direct way is to check for the density of peaks above a certain threshold (arbitrary and empirical). This is because the separators have, in general, a higher intensity than the images, although they are not consistent. Using this density approach we can damp the noise.</p>

<p>If we divide the recording into sections of short length (also arbitrary and empirical), we can determine the densities of the high peaks in each of those sections. This would be enough. However, if we then group these sections and calculate the ‘densities of sections determined to have higher densities of high peaks’, we can determine regions of high densities with more consistency. This double-density approach is a good way to avoid false positives. This is what is done in <a href="/files/posts/Voyager/audio_to_txt.py">Audio -&gt; txt</a>. We could of course apply more layers and do the density of the densities of densities… I think I lost myself, you get the idea. Note that there are two channels in the audio, and it is necessary to apply the same approach to both. We get the following (very good may I add) division:</p>

<p style="text-align:center">
  <img src="/images/posts/Voyager/Voyager-divided.png" alt="Golden Record Audio Divided" width="100%" />
</p>

<p>For the last stretch, we need a way to display each image. The idea is quite simple and based on how the images are encoded. We need to find the first big valley in our data, which is the beginning of an image line. By the end, we should encounter 512 of those lines, but generally, we can’t count on that. The cuts we made are imperfect, and we may be missing a line or two or the valleys may be ill defined. Starting from the first identified valley, we can find the next one knowing the mean distance we expect and looking for a valley around that point. All points inbetween will be one line of our matrix. There is something we should notice. As we’re dealing with imprecise data, we may have some lines with more points than others. That will be a problem when plotting the matrix. We can, however, compete with the lines in an arbitrary empty space, so we have a margin to wobble around. I found that 1100 points (enough for a double line) is a nice enough number to use. All of this process is done in <a href="/files/posts/Voyager/txt_to_image.py">txt -&gt; Img</a>. After this, we can plot the matrix, and we should have the image. Such images are shown (with cutted borders) below.</p>

<p>
<p style="text-align:center">
  <img src="/images/posts/Voyager/Voyager-rocket.png" width="30%" />
  <img src="/images/posts/Voyager/Voyager-concha.png" width="30%" />
  <img src="/images/posts/Voyager/Voyager-earth.png" width="30%" />
</p>
<p style="text-align:center">
  <img src="/images/posts/Voyager/Voyager-inside.png" width="30%" />
  <img src="/images/posts/Voyager/Voyager-men.png" width="30%" />
  <img src="/images/posts/Voyager/Voyager-text.png" width="30%" />
</p>
</p>

<p>There are some pictures that appear three times, indicating RGB channels. If we want, we can compose those pictures and have colorful images! Anyway, all the code and results are available on my <a href="https://github.com/Joao-vap/Decoding_Golden-Record_Images/tree/main">GitHub</a>.</p>

<h1 id="tying-the-knot">Tying the knot</h1>

<p>Sometimes I do wonder about the work that was put into the Golden Record. That is, a team of really invested people took uncountable hours to work on the instructions and the recording. For what? Really, how likely is it that someone encounters these spacecraft? I mean, Sagan itself has made a point about the size of our universe in comparison to what we have influenced. Suppose you agree with the argument that there should be another civilization somewhere. Even more, you are prepared to say that there should be some other civilization that is as curious and alone as we are, craving a message. Honestly, I can consider that. I even find it likely for some form of life to be in the Cosmos somewhere, looking for signs of company. After all, for us to be alone would be a mathematical wonder.</p>

<p>Even then, what is the chance that our tiny piece of metal gets in the hands of such a life form? Even if it is going straight to somewhere it can be found, how long until this happens? The Cosmos is vast, and we are small. No, we can’t think of the Golden Record as a message to someone out there, nor directly or mainly, at least. I think all the people involved in the project knew this, I know this. The Golden Record is a message to oneself. It is an exercise to categorically explicit what is valuable to us. To understand what would be our image to an imaginary outer civilization; it is a way to reflect not on the distant unknown but on the close-known self.</p>

<p>In more than one way, I can’t stop coming back to this concept. It is no coincidence that I’ve chosen this to be the first post on the blog. In a less subtle way, I guess this text itself is one of the records I’m putting on this Golden Blog. There is no instruction to read through this, I wouldn’t know how to make those. I can only hope I use a common language that we both understand. Regardless of who is going to be the decoder of the message, and for all of those I wish the best of luck, this, in itself, will hold all that is dear and personal to me. I truy hope, however, that we don’t live on a mathematical wonder.</p>]]></content><author><name>João V. A. Pimenta</name><email>joaovictorpi[...]@usp.br</email></author><category term="Basics" /><category term="Voyager" /><category term="Golden Record" /><summary type="html"><![CDATA[I can’t get over the Voyager mission.]]></summary></entry></feed>