<?xml version="1.0" encoding="UTF-8"?>
<rss  xmlns:atom="http://www.w3.org/2005/Atom" 
      xmlns:media="http://search.yahoo.com/mrss/" 
      xmlns:content="http://purl.org/rss/1.0/modules/content/" 
      xmlns:dc="http://purl.org/dc/elements/1.1/" 
      version="2.0">
<channel>
<title>Anderson M. Amaral — Blog</title>
<link>https://amamaral.github.io/blog/</link>
<atom:link href="https://amamaral.github.io/blog/index.xml" rel="self" type="application/rss+xml"/>
<description>Physicist — nonlinear &amp; quantum optics, structured light, nanophotonics (UFPE)</description>
<generator>quarto-1.6.42</generator>
<lastBuildDate>Mon, 16 Jan 2023 00:00:00 GMT</lastBuildDate>
<item>
  <title>Multiprocess performance of linear algebra and FFTs in Python</title>
  <dc:creator>Anderson M. Amaral</dc:creator>
  <link>https://amamaral.github.io/blog/posts/multiprocessing-linalg-fft/</link>
  <description><![CDATA[ 




<p>Numpy may use several backends for improving the calculation speed. Which one is currently active? Also, let’s see how faster can we improve the numpy calculations using more optimized routines. In particular, it should be noticed that after installing Intel’s MKL optimized numpy there was a significant improvement in the speed. While the number of cores used in the computation must be set before loading numpy (as in the examples below), the examples below do not use all cores at once.</p>
<section id="basic-implementation" class="level2">
<h2 class="anchored" data-anchor-id="basic-implementation">Basic implementation</h2>
<div id="6246d46d-53d1-4344-adde-4a42744d452c" class="cell" data-execution_count="12">
<div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># See http://mitrocketscience.blogspot.com/2018/11/automatic-mulit-threading-with-python.html</span></span>
<span id="cb1-2"></span>
<span id="cb1-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Also notice that I've installed Intel's mkl as suggested at</span></span>
<span id="cb1-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># https://www.intel.com/content/www/us/en/developer/articles/technical/using-intel-distribution-for-python-with-anaconda.html</span></span>
<span id="cb1-5"></span>
<span id="cb1-6"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> os</span>
<span id="cb1-7"></span>
<span id="cb1-8">NTHREADS <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'12'</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Value set as string</span></span>
<span id="cb1-9"></span>
<span id="cb1-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Export system variables before loading numpy</span></span>
<span id="cb1-11"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'OMP_NUM_THREADS'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'OPENBLAS_NUM_THREADS'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'MKL_NUM_THREADS'</span>]:<span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#,</span></span>
<span id="cb1-12">          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#'VECLIB_MAXIMUM_THREADS', 'NUMEXPR_NUM_THREADS']:</span></span>
<span id="cb1-13">    os.environ[i] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> NTHREADS</span>
<span id="cb1-14"></span>
<span id="cb1-15"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb1-16"></span>
<span id="cb1-17"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Defining two big matrices for testing</span></span>
<span id="cb1-18"></span>
<span id="cb1-19">matrix_shape <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2048</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2048</span>)</span>
<span id="cb1-20">a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.random.random(matrix_shape) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">1j</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.random.random(matrix_shape)</span>
<span id="cb1-21">b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.random.random(matrix_shape) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">1j</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.random.random(matrix_shape)</span>
<span id="cb1-22"></span>
<span id="cb1-23">np.show_config()</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>blas_mkl_info:
    libraries = ['mkl_rt']
    library_dirs = ['C:/Users/Anderson/anaconda3\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['C:/Users/Anderson/anaconda3\\Library\\include']
blas_opt_info:
    libraries = ['mkl_rt']
    library_dirs = ['C:/Users/Anderson/anaconda3\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['C:/Users/Anderson/anaconda3\\Library\\include']
lapack_mkl_info:
    libraries = ['mkl_rt']
    library_dirs = ['C:/Users/Anderson/anaconda3\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['C:/Users/Anderson/anaconda3\\Library\\include']
lapack_opt_info:
    libraries = ['mkl_rt']
    library_dirs = ['C:/Users/Anderson/anaconda3\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['C:/Users/Anderson/anaconda3\\Library\\include']</code></pre>
</div>
</div>
<section id="basic-numpy-after-adding-intels-mkl-using-single-core" class="level3">
<h3 class="anchored" data-anchor-id="basic-numpy-after-adding-intels-mkl-using-single-core">Basic numpy (after adding Intel’s MKL) using single core</h3>
<p>While I don’t have the record for the benchmarks below before adding <a href="https://www.intel.com/content/www/us/en/developer/articles/technical/using-intel-distribution-for-python-with-anaconda.html">Intel’s MKL</a>, some of the operations below were already significantly improved at single-core level with Intel’s optimizations.</p>
<div id="653fbf09-3908-4d9b-9846-6e08ca16a962" class="cell" data-execution_count="7">
<div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># How long does it take to calculate the dot product?</span></span>
<span id="cb3-2"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>timeit np.dot(a, b)</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>1.27 s ± 4.66 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)</code></pre>
</div>
</div>
<p>Looking at Windows’ resources monitor, it can be clearly seen that only a single core is working at a time.</p>
<div id="a36a12ac-8692-4119-b875-7be602cae42f" class="cell" data-execution_count="4">
<div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>timeit np.fft.fft(a)</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>37.1 ms ± 449 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)</code></pre>
</div>
</div>
<div id="858ed028-a2b9-4c53-91de-2a30d9cd02cb" class="cell" data-execution_count="5">
<div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>timeit np.fft.ifft(a)</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>38.9 ms ± 590 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)</code></pre>
</div>
</div>
<div id="7b941b52-4566-47a0-bec0-96869ae7c32c" class="cell" data-execution_count="6">
<div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>timeit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>n <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>17.3 ms ± 1.18 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)</code></pre>
</div>
</div>
</section>
<section id="pyfftw" class="level3">
<h3 class="anchored" data-anchor-id="pyfftw">pyfftw</h3>
<p>pyfftw is an interface to FFTW, which claims to be a very fast FFT library. Below we can see how fast does it perform without optimization. It should be noticed that pyfftw states that significant improvements can be seen by tuning the library calls.</p>
<div id="82777e97-34b4-4499-84a8-dd84044ae487" class="cell" data-execution_count="2">
<div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pyfftw</span>
<span id="cb11-2"></span>
<span id="cb11-3">pyfftw.config.NUM_THREADS <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span></code></pre></div>
</div>
<div id="efa0a54c-d684-41e6-bc49-2e6e5ec16cf8" class="cell" data-execution_count="9">
<div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>timeit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>n <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> pyfftw.interfaces.numpy_fft.fft(a)</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>63.3 ms ± 1.4 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)</code></pre>
</div>
</div>
<p>so it seems that Intel’s optimized numpy is faster than pyfftw.</p>
</section>
<section id="numpy-and-pyfft" class="level3">
<h3 class="anchored" data-anchor-id="numpy-and-pyfft">Numpy and pyfft</h3>
<p>Now let’s consider increasing the MKL and pyfftw number of threads to 12 (the max in my current cpu) and running again the tests</p>
<div id="05aa75bd-c4cb-4be1-a6a7-46bfc0702bb7" class="cell" data-execution_count="6">
<div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>timeit np.dot(a, b)</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>322 ms ± 8.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)</code></pre>
</div>
</div>
<div id="8cb52c8f-1f1b-47ed-a9c3-39823acf6e5a" class="cell" data-execution_count="2">
<div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"An improvement of </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">322</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1270</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">%"</span></span></code></pre></div>
<div class="cell-output cell-output-display" data-execution_count="2">
<pre><code>'An improvement of 74.65%'</code></pre>
</div>
</div>
<div id="25b33d3a-3590-414d-9596-7e247a48ff6d" class="cell" data-execution_count="7">
<div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>timeit np.fft.fft(a)</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>33.4 ms ± 620 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)</code></pre>
</div>
</div>
<div id="3a45bf11-238a-48ce-9aa2-49328d302097" class="cell" data-execution_count="3">
<div class="sourceCode cell-code" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb20-1"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"An improvement of </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">33.4</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">37.1</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">%"</span></span></code></pre></div>
<div class="cell-output cell-output-display" data-execution_count="3">
<pre><code>'An improvement of 9.97%'</code></pre>
</div>
</div>
<div id="261cbb29-3aab-4e5f-a741-b1758c19c9d1" class="cell" data-execution_count="8">
<div class="sourceCode cell-code" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb22-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>timeit np.fft.ifft(a)</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>35.1 ms ± 337 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)</code></pre>
</div>
</div>
<div id="87e8e68f-a1eb-4a6c-bbbd-64f55bd38b13" class="cell" data-execution_count="4">
<div class="sourceCode cell-code" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb24-1"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"An improvement of </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">35.1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">38.9</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">%"</span></span></code></pre></div>
<div class="cell-output cell-output-display" data-execution_count="4">
<pre><code>'An improvement of 9.77%'</code></pre>
</div>
</div>
<div id="32297339-0614-40d0-863d-3a0f8a0f10e6" class="cell" data-execution_count="9">
<div class="sourceCode cell-code" id="cb26" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb26-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>timeit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>n <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>13.2 ms ± 242 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)</code></pre>
</div>
</div>
<div id="e6c79900-a915-478c-a19e-1c18c2bc4c84" class="cell" data-execution_count="5">
<div class="sourceCode cell-code" id="cb28" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb28-1"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"An improvement of </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">13.2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">17.3</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">%"</span></span></code></pre></div>
<div class="cell-output cell-output-display" data-execution_count="5">
<pre><code>'An improvement of 23.70%'</code></pre>
</div>
</div>
<div id="7e1b97fe-7b7e-4e1b-a4e6-b6590b0faf7c" class="cell" data-execution_count="10">
<div class="sourceCode cell-code" id="cb30" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb30-1">pyfftw.config.NUM_THREADS <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pyfftw.config.multiprocessing.cpu_count()</span>
<span id="cb30-2"></span>
<span id="cb30-3"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>timeit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>n <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> pyfftw.interfaces.numpy_fft.fft(a)</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>46.4 ms ± 259 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)</code></pre>
</div>
</div>
<div id="a7cb06bd-f67d-4ea0-8f62-ed67c37b9964" class="cell" data-execution_count="6">
<div class="sourceCode cell-code" id="cb32" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb32-1"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"An improvement of </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">46.4</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">63.3</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">%"</span></span></code></pre></div>
<div class="cell-output cell-output-display" data-execution_count="6">
<pre><code>'An improvement of 26.70%'</code></pre>
</div>
</div>
<p>Some operations as the dot product have become significantly faster, but the speed increase in other expressions was not so significant. Perhaps the array size is too small for significant improvements and the process creation/destruction overhead dominates in this case. pyfftw became faster, but the numpy’s fft remains faster.</p>
</section>
</section>
<section id="numba" class="level2">
<h2 class="anchored" data-anchor-id="numba">Numba</h2>
<p>Numba is a python library that often speeds up numerical calculations by using just-int-time compilation and avoiding the overhead of dynamic types in python scripts. Here we install it and perform some benchmarks. Unfortunately it does not support ffts, which would be a significant improvement for algorithms as split-step propagation method.</p>
<div id="ad46a578-fd2a-4e4a-a9c0-d5b07e99989b" class="cell" data-execution_count="13">
<div class="sourceCode cell-code" id="cb34" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb34-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span>pip install numba</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>Requirement already satisfied: numba in c:\users\anderson\anaconda3\lib\site-packages (0.54.1)
Requirement already satisfied: llvmlite&lt;0.38,&gt;=0.37.0rc1 in c:\users\anderson\anaconda3\lib\site-packages (from numba) (0.37.0)
Requirement already satisfied: numpy&lt;1.21,&gt;=1.17 in c:\users\anderson\anaconda3\lib\site-packages (from numba) (1.20.3)
Requirement already satisfied: setuptools in c:\users\anderson\anaconda3\lib\site-packages (from numba) (58.0.4)</code></pre>
</div>
</div>
<div id="523536c0-d19f-4368-a2af-3700f62dbeb4" class="cell" data-execution_count="38">
<div class="sourceCode cell-code" id="cb36" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb36-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> numba <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> jit, njit, objmode</span></code></pre></div>
</div>
<div id="56e50cb6-4757-4c64-98bb-f5b217092319" class="cell" data-execution_count="46">
<div class="sourceCode cell-code" id="cb37" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb37-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>timeit np.dot(a, b) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> np.exp(a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>586 ms ± 8.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)</code></pre>
</div>
</div>
<div id="1e82fbc9-117e-43b5-8bbf-e4a98b4ed468" class="cell" data-execution_count="47">
<div class="sourceCode cell-code" id="cb39" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb39-1"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@njit</span></span>
<span id="cb39-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> example():</span>
<span id="cb39-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.dot(a, b) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> np.exp(a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb39-4"></span>
<span id="cb39-5"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>timeit example()</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>396 ms ± 11.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)</code></pre>
</div>
</div>
<div id="5b7f31d9-4ef2-422d-beeb-db79c592f028" class="cell" data-execution_count="55">
<div class="sourceCode cell-code" id="cb41" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb41-1"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"An improvement of </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">396</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">586</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">%"</span></span></code></pre></div>
<div class="cell-output cell-output-display" data-execution_count="55">
<pre><code>'An improvement of 32.42%'</code></pre>
</div>
</div>
<div id="0e36aa6f-8a07-4223-8ff9-0255a4892a30" class="cell" data-execution_count="18">
<div class="sourceCode cell-code" id="cb43" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb43-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> example():</span>
<span id="cb43-2">    np.fft.fft2(a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.conj(b))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>np.conj(b)</span>
<span id="cb43-3">    np.fft.ifft2(a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>b</span>
<span id="cb43-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb43-5"></span>
<span id="cb43-6"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>timeit example()</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>336 ms ± 3.62 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)</code></pre>
</div>
</div>
<div id="95608176-face-49f7-b405-0cb43dba050b" class="cell" data-execution_count="35">
<div class="sourceCode cell-code" id="cb45" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb45-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb45-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">Since numba does not have native support for fft,</span></span>
<span id="cb45-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">there is a workaround suggested at</span></span>
<span id="cb45-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">https://github.com/numba/numba/issues/5864#issuecomment-690838747</span></span>
<span id="cb45-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb45-6"></span>
<span id="cb45-7"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@jit</span>(nopython<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb45-8"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> example2():</span>
<span id="cb45-9">    d <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.conj(b)</span>
<span id="cb45-10">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> objmode(d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'complex128[:]'</span>):</span>
<span id="cb45-11">        d <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.fft.fft2(d)        </span>
<span id="cb45-12">    d <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> d <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.conj(b)</span>
<span id="cb45-13">    </span>
<span id="cb45-14">    d <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b</span>
<span id="cb45-15">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> objmode(d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'complex128[:]'</span>):</span>
<span id="cb45-16">        d <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.fft.ifft2(d)        </span>
<span id="cb45-17">    d <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> d <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b    </span>
<span id="cb45-18">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb45-19"></span>
<span id="cb45-20"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>timeit example2()</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>277 ms ± 8.44 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)</code></pre>
</div>
</div>
<div id="d3f0cc6d-3970-44ca-afc1-abd3238b49c7" class="cell" data-execution_count="53">
<div class="sourceCode cell-code" id="cb47" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb47-1"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"An improvement of </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">277</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">336</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">%"</span></span></code></pre></div>
<div class="cell-output cell-output-display" data-execution_count="53">
<pre><code>'An improvement of 17.56%'</code></pre>
</div>
</div>
<div id="fe6125b3-540c-4b0a-94f0-e83a1a32da02" class="cell" data-execution_count="56">
<div class="sourceCode cell-code" id="cb49" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb49-1"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@jit</span>()</span>
<span id="cb49-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> example3():</span>
<span id="cb49-3">    np.fft.fft2(a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.conj(b))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>np.conj(b)</span>
<span id="cb49-4">    np.fft.ifft2(a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>b</span>
<span id="cb49-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb49-6"></span>
<span id="cb49-7"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>timeit example3()</span></code></pre></div>
<div class="cell-output cell-output-stderr">
<pre><code>C:\Users\Anderson\AppData\Local\Temp/ipykernel_22088/3408064900.py:1: NumbaWarning: 
Compilation is falling back to object mode WITH looplifting enabled because Function "example3" failed type inference due to: Unknown attribute 'fft2' of type Module(&lt;module 'numpy.fft' from 'C:\\Users\\Anderson\\anaconda3\\lib\\site-packages\\numpy\\fft\\__init__.py'&gt;)

File "..\..\..\..\AppData\Local\Temp\ipykernel_22088\3408064900.py", line 3:
&lt;source missing, REPL/exec in use?&gt;

During: typing of get attribute at C:\Users\Anderson\AppData\Local\Temp/ipykernel_22088/3408064900.py (3)

File "..\..\..\..\AppData\Local\Temp\ipykernel_22088\3408064900.py", line 3:
&lt;source missing, REPL/exec in use?&gt;

  @jit
C:\Users\Anderson\anaconda3\lib\site-packages\numba\core\object_mode_passes.py:151: NumbaWarning: Function "example3" was compiled in object mode without forceobj=True.

File "..\..\..\..\AppData\Local\Temp\ipykernel_22088\3408064900.py", line 1:
&lt;source missing, REPL/exec in use?&gt;

  warnings.warn(errors.NumbaWarning(warn_msg,
C:\Users\Anderson\anaconda3\lib\site-packages\numba\core\object_mode_passes.py:161: NumbaDeprecationWarning: 
Fall-back from the nopython compilation path to the object mode compilation path has been detected, this is deprecated behaviour.

For more information visit https://numba.pydata.org/numba-doc/latest/reference/deprecation.html#deprecation-of-object-mode-fall-back-behaviour-when-using-jit

File "..\..\..\..\AppData\Local\Temp\ipykernel_22088\3408064900.py", line 1:
&lt;source missing, REPL/exec in use?&gt;

  warnings.warn(errors.NumbaDeprecationWarning(msg,</code></pre>
</div>
<div class="cell-output cell-output-stdout">
<pre><code>343 ms ± 10.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)</code></pre>
</div>
</div>
<div id="de0d098f-b0b7-4a7d-bf54-f3b06623b50c" class="cell" data-execution_count="57">
<div class="sourceCode cell-code" id="cb52" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb52-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>timeit example3()</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>344 ms ± 13.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)</code></pre>
</div>
</div>
<div id="a0784956-ea17-4f7e-8d1e-ac32736fe341" class="cell" data-execution_count="58">
<div class="sourceCode cell-code" id="cb54" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb54-1"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"An improvement of </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">344</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">336</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">%"</span></span></code></pre></div>
<div class="cell-output cell-output-display" data-execution_count="58">
<pre><code>'An improvement of -2.38%'</code></pre>
</div>
</div>
<p>Thus, while numba is able to deliver improvements around 20-30%, it’s lack of fft support slows down the computation significantly. In particular the <code>nopython=True</code> option is critical to have significant performance gains, otherwise it can even make the code slower as in the example 3 above.</p>
</section>
<section id="tensorflow" class="level2">
<h2 class="anchored" data-anchor-id="tensorflow">Tensorflow</h2>
<p>Since tensorflow has native support for ffts, some tests were also performed using the code below. I’ve tested it using my GPUless PC and also google colab’s cloud computing service. Since it’s not feasible to show the timeit results inline with so many configurations, the data is summarized at the end.</p>
<div id="3062f33a-974b-47d1-8746-745893daf1f8" class="cell">
<div class="sourceCode cell-code" id="cb56" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb56-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> tensorflow <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> tf</span>
<span id="cb56-2"></span>
<span id="cb56-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> tensorflow.experimental.numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> tnp</span>
<span id="cb56-4">tnp.experimental_enable_numpy_behavior()</span>
<span id="cb56-5"></span>
<span id="cb56-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Gerando matrizes equivalentes ao teste anterior, no tensorflow</span></span>
<span id="cb56-7"></span>
<span id="cb56-8">matrix_shape <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2048</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2048</span>)</span>
<span id="cb56-9"></span>
<span id="cb56-10">a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.random.uniform(matrix_shape, dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>tf.dtypes.float64)</span>
<span id="cb56-11">b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.random.uniform(matrix_shape, dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>tf.dtypes.float64)</span>
<span id="cb56-12"></span>
<span id="cb56-13">c <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.cast(a, tf.dtypes.complex128) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">1j</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> tf.cast(b, tf.dtypes.complex128)</span>
<span id="cb56-14">d <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.cast(b<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> a<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, tf.dtypes.complex128) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">1j</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> tf.cast(a<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>b, tf.dtypes.complex128)</span>
<span id="cb56-15"></span>
<span id="cb56-16">a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> c</span>
<span id="cb56-17">b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> d</span></code></pre></div>
</div>
<div id="c69b2e79-fa38-4ce0-8777-d4c9228df45f" class="cell">
<div class="sourceCode cell-code" id="cb57" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb57-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Shows if a gpu is available</span></span>
<span id="cb57-2">tf.config.list_physical_devices()</span></code></pre></div>
</div>
<div id="bb73cc5f-9369-44c0-b9aa-ed2f257db11e" class="cell">
<div class="sourceCode cell-code" id="cb58" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb58-1">tf.debugging.set_log_device_placement(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb58-2"></span>
<span id="cb58-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Example 0</span></span>
<span id="cb58-4"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>timeit tf.experimental.numpy.dot(a, b)</span></code></pre></div>
</div>
<div id="2c9ccb64-ec36-4e1e-9e8b-44d3c3d93ab6" class="cell">
<div class="sourceCode cell-code" id="cb59" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb59-1">tf.debugging.set_log_device_placement(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb59-2"></span>
<span id="cb59-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Example 1</span></span>
<span id="cb59-4"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>timeit tf.signal.fft2d(a)</span></code></pre></div>
</div>
<div id="4fb1d476-0858-42db-a2e8-e324cbd3a18a" class="cell">
<div class="sourceCode cell-code" id="cb60" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb60-1">tf.debugging.set_log_device_placement(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb60-2"></span>
<span id="cb60-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Example 2</span></span>
<span id="cb60-4"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>timeit tf.signal.ifft2d(a)</span></code></pre></div>
</div>
<div id="c5b297f3-73f0-4211-a457-628d250cc948" class="cell">
<div class="sourceCode cell-code" id="cb61" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb61-1">tf.debugging.set_log_device_placement(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb61-2"></span>
<span id="cb61-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Example 3</span></span>
<span id="cb61-4"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>timeit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>n <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b</span></code></pre></div>
</div>
<div id="ad2a7c4b-0821-4469-a9b7-0b491c881cbb" class="cell">
<div class="sourceCode cell-code" id="cb62" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb62-1">tf.debugging.set_log_device_placement(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb62-2"></span>
<span id="cb62-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Example 4</span></span>
<span id="cb62-4"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>timeit tf.signal.fft( a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> tf.signal.ifft( a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b</span></code></pre></div>
</div>
<div id="98db014d-25fe-4271-90bb-5cdfdecc65e0" class="cell" data-execution_count="14">
<div class="sourceCode cell-code" id="cb63" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb63-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd</span>
<span id="cb63-2"></span>
<span id="cb63-3">df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame()</span>
<span id="cb63-4"></span>
<span id="cb63-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#times in ms</span></span>
<span id="cb63-6"></span>
<span id="cb63-7">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Home (CPU)'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">783</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">140</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">173</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">14.9</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">218</span>]</span>
<span id="cb63-8">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Colab (CPU)'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3460</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">477</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">605</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">18.1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">503</span>]</span>
<span id="cb63-9">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Colab (GPU-fastest)'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.23</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.266</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.51</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.093</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.94</span>]</span>
<span id="cb63-10">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Colab (GPU-slowest)'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.23</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">14.63</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.266</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1515</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.51</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.093</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">97.98</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.94</span>]</span>
<span id="cb63-11"></span>
<span id="cb63-12">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Colab GPU </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">% i</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">mprovement'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Colab (CPU)'</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>(df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Colab (GPU-fastest)'</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Colab (GPU-slowest)'</span>]) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span></span>
<span id="cb63-13"></span>
<span id="cb63-14">df</span></code></pre></div>
<div class="cell-output cell-output-display" data-execution_count="14">
<div>


<table class="dataframe caption-top table table-sm table-striped small" data-quarto-postprocess="true" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">Home (CPU)</th>
<th data-quarto-table-cell-role="th">Colab (CPU)</th>
<th data-quarto-table-cell-role="th">Colab (GPU-fastest)</th>
<th data-quarto-table-cell-role="th">Colab (GPU-slowest)</th>
<th data-quarto-table-cell-role="th">Colab GPU % improvement</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td data-quarto-table-cell-role="th">0</td>
<td>783.0</td>
<td>3460.0</td>
<td>1.230</td>
<td>17.99490</td>
<td>35994.985670</td>
</tr>
<tr class="even">
<td data-quarto-table-cell-role="th">1</td>
<td>140.0</td>
<td>477.0</td>
<td>0.266</td>
<td>402.99000</td>
<td>236.574285</td>
</tr>
<tr class="odd">
<td data-quarto-table-cell-role="th">2</td>
<td>173.0</td>
<td>605.0</td>
<td>3.510</td>
<td>3.51000</td>
<td>17236.467236</td>
</tr>
<tr class="even">
<td data-quarto-table-cell-role="th">3</td>
<td>14.9</td>
<td>18.1</td>
<td>0.093</td>
<td>9.11214</td>
<td>393.258549</td>
</tr>
<tr class="odd">
<td data-quarto-table-cell-role="th">4</td>
<td>218.0</td>
<td>503.0</td>
<td>2.940</td>
<td>2.94000</td>
<td>17108.843537</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
<p>It’s worth to mention that the CPU available on colab performs slower than the one I have at home, but tensorflow shows a significant performance improvement when executed on the GPU. Also, when executing locally it can be seen that tensorflow code is very optimized to use all cores. While this strategy may not be optimal for a processor with a few cores, it’s certainly interesting for GPUs with their massive number of parallel processing cores.</p>
<p>Something to be aware of is that timeit on colab works differently, such that it reports the best time, while on jupyter lab it reports the mean time. When the calculation can buffer some sections of the calculus for speedup, the reported value may be an optimistic view of the true computation time. Is it time for a GPU?</p>
<p>Also, the timeit results from colab are inconsistent. Depending on the run, the values may become significantly larger or smaller. However, it seems reasonable to expect at least one order of magnitude speedup factor when using tensorflow+gpu for these calculations. However it should be possible to speedup up to 4 orders of magnitude, depending on the operations used. This would be very consistent with the performance gains of up to 1000x reported in</p>
<p>https://arxiv.org/abs/2010.08895</p>
<p>https://www.technologyreview.com/2020/10/30/1011435/ai-fourier-neural-network-cracks-navier-stokes-and-partial-differential-equations/</p>
<p>but without the need for NNs to solve these PDEs, but it’s just related with the TF’s improved speed when using gpus.</p>
</section>
<section id="pytorch" class="level2">
<h2 class="anchored" data-anchor-id="pytorch">Pytorch</h2>
<p>Notice that pytorch also has a native fft library, and it probably should be interesting to benchmark it as well.</p>


</section>

 ]]></description>
  <category>python</category>
  <category>data analysis</category>
  <category>signal processing</category>
  <guid>https://amamaral.github.io/blog/posts/multiprocessing-linalg-fft/</guid>
  <pubDate>Mon, 16 Jan 2023 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Python for experimental sciences — chapter II</title>
  <dc:creator>Anderson M. Amaral</dc:creator>
  <link>https://amamaral.github.io/blog/posts/python-for-experimental-sciences-2/</link>
  <description><![CDATA[ 




<!---

Refazer o texto para que as tabelas sejam preenchidas no modo CSV do pandas... da forma atualmente colocada fica pouco intuitivo para quem é leigo, e já existe uma barreira razoável à linguagem de programação e outros aspectos que aparecem na atividade... Preencher os dados deveria ser algo mais simplificado.

Outra coisa importante disto é respeitar o separation of concerns dos arquivos... Fica mais organizado.

--->
<section id="data-analysis-and-reports" class="level1">
<h1>Data analysis and reports</h1>
<p>The previous chapter gave an overview of Python and Numpy, which allowed us to learn the language, manipulate data, evaluate and plot functions. In this chapter we will see how to represent data tables in Python, how to save and load data from files and also how to fit the data to theoretical models. Besides Numpy (numeric manipulation) and Matplotlib (plots), we will use other Python libraries as Pandas (tables) and Scipy (data fitting). Later on it will be shown how to use Jupyter notebook to write reports. There is a short description on how to use the Markdown syntax to compose a document and an later there is an overview of syntax to write mathematical expressions.</p>
<section id="data-tables-in-pandas" class="level2">
<h2 class="anchored" data-anchor-id="data-tables-in-pandas">Data tables in Pandas</h2>
<p>Suppose that the position and velocity of a particle are measured as a function of time. The measured data is represented below and we want to represent this table in Python.</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th style="text-align: center;"></th>
<th style="text-align: center;">time</th>
<th style="text-align: center;">position</th>
<th style="text-align: center;">velocity</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: center;">0</td>
<td style="text-align: center;">1</td>
<td style="text-align: center;">1</td>
<td style="text-align: center;">2</td>
</tr>
<tr class="even">
<td style="text-align: center;">1</td>
<td style="text-align: center;">2</td>
<td style="text-align: center;">4</td>
<td style="text-align: center;">4</td>
</tr>
<tr class="odd">
<td style="text-align: center;">2</td>
<td style="text-align: center;">3</td>
<td style="text-align: center;">9</td>
<td style="text-align: center;">6</td>
</tr>
<tr class="even">
<td style="text-align: center;">3</td>
<td style="text-align: center;">4</td>
<td style="text-align: center;">16</td>
<td style="text-align: center;">8</td>
</tr>
<tr class="odd">
<td style="text-align: center;">4</td>
<td style="text-align: center;">5</td>
<td style="text-align: center;">25</td>
<td style="text-align: center;">10</td>
</tr>
</tbody>
</table>
<p>The first column indicates the corresponding line number of the table. Python starts counting from 0 by default.This data can be represented using the code below. Explaining line by line, first we ensure that the <code>%pylab inline</code> magic is called. We also import the Pandas library to handle tables. Pandas is imported with the nickname <code>pd</code> to simplify some expressions that will be used later. The table data itself is stored in what Pandas calls a DataFrame which we will call <code>df</code>. After a clean dataframe <code>df</code> is created, we may generate it’s columns with the definition of a column label and the data directly. The data itself in our case is a Python list, which as previously stated is an ordered set of values between <code>[]</code> and separated by commas <code>,</code>. The spaces are optional and can be used to make easier to see the data being written, but remember that the decimal separator is always a period <code>.</code>. Also, the first element in each column list correspond to the first table line (first measurement). For example, the third measurement (third line) corresponds to the time <code>3</code>, position <code>9</code> and velocity <code>6</code>. After setting the table contents, we may show the dataframe contents as a table using <code>df</code> in the last line.</p>
<div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>pylab inline</span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd</span>
<span id="cb1-3"></span>
<span id="cb1-4">df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame()</span>
<span id="cb1-5">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'time'</span>]     <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>,  <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>,  <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>]</span>
<span id="cb1-6">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'position'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span>]</span>
<span id="cb1-7">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'velocity'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>,  <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>]</span>
<span id="cb1-8"></span>
<span id="cb1-9">df</span></code></pre></div>
<p>If we want to plot the position as a function of time, it is possible to use simply the code below. <code>df.plot</code> uses the column labels to identify the data points horizontal and vertical coordinates. It is often a good practice to represent experimental data as a <code>scatter</code> plot, where each measurement is represented by an isolated point. Also, while <code>df.plot</code> accepts several specific arguments (see the documentation pressing <code>SHIFT+TAB</code> keys or the <a href="https://pandas.pydata.org/pandas-docs/version/0.14.0/generated/pandas.DataFrame.plot.html">documentation</a>), the matplotlib commands to adjust plot properties as the title and label axis described in the last chapter still can be used. <strong>Always remember to place adequate axis labels (containing the relevant units) and an explanatory title.</strong></p>
<div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1">df.plot(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'time'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'position'</span>, kind<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'scatter'</span>)</span>
<span id="cb2-2">title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Position vs time'</span>)</span>
<span id="cb2-3">xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Time (s)'</span>)</span>
<span id="cb2-4">ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Position (m)'</span>)</span>
<span id="cb2-5">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'assets\pes_pos_scatter_plot.png'</span>)</span></code></pre></div>
<p><img src="https://amamaral.github.io/blog/assets/pes_pos_scatter_plot.png" class="img-fluid"></p>
<p>It is quite simple to perform calculations over <code>DataFrame</code> columns. Whenever we call a column as <code>df['time']</code>, we may consider that we are performing mathematical operation simultaneously over each element. For example, to create a new column containing <img src="https://latex.codecogs.com/png.latex?%5Csqrt%7Bt%7D%20+%201"> we can use simply that</p>
<div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'sqrt(t) + 1'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sqrt(df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'time'</span>]) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb3-2"></span>
<span id="cb3-3">df</span></code></pre></div>
<table class="caption-top table">
<thead>
<tr class="header">
<th style="text-align: center;"></th>
<th style="text-align: center;">time</th>
<th style="text-align: center;">position</th>
<th style="text-align: center;">velocity</th>
<th style="text-align: center;">sqrt(t) + 1</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: center;">0</td>
<td style="text-align: center;">1</td>
<td style="text-align: center;">1</td>
<td style="text-align: center;">2</td>
<td style="text-align: center;">2.000000</td>
</tr>
<tr class="even">
<td style="text-align: center;">1</td>
<td style="text-align: center;">2</td>
<td style="text-align: center;">4</td>
<td style="text-align: center;">4</td>
<td style="text-align: center;">2.414214</td>
</tr>
<tr class="odd">
<td style="text-align: center;">2</td>
<td style="text-align: center;">3</td>
<td style="text-align: center;">9</td>
<td style="text-align: center;">6</td>
<td style="text-align: center;">2.732051</td>
</tr>
<tr class="even">
<td style="text-align: center;">3</td>
<td style="text-align: center;">4</td>
<td style="text-align: center;">16</td>
<td style="text-align: center;">8</td>
<td style="text-align: center;">3.000000</td>
</tr>
<tr class="odd">
<td style="text-align: center;">4</td>
<td style="text-align: center;">5</td>
<td style="text-align: center;">25</td>
<td style="text-align: center;">10</td>
<td style="text-align: center;">3.236068</td>
</tr>
</tbody>
</table>
<p>The operations performed with <code>df['column']</code> are performed for each element in the column, such we can use a single line to calculate over several numbers. If we want to select a given line, we may use <code>df.iloc[i]</code>, where <code>i</code> is the corresponding line number. Also notice that we can add columns whenever we want. If there is some <code>column</code> that we want to remove completely we may apply the instruction line <code>del df['column']</code>. Raising the column to a power of 0.5, as in <code>df['time']**0.5</code>, is an alternative to use <code>sqrt</code>. Also, the basic operations (<code>+-*/</code>) are supported. The <code>%pylab inline</code> magic also allows us to use several mathematical functions as <code>sin, cos, tan</code>, their inverses, <code>arcsin, arccos, arctan</code>, exponentials and natural logarithms as <code>exp, log</code>. For example, we can use the code below to evaluate <img src="https://latex.codecogs.com/png.latex?%5Csin%20x"> at 10 equally spaced points along <code>x</code>.</p>
<div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1">df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame() <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Clears df</span></span>
<span id="cb4-2"></span>
<span id="cb4-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># x contains 101 equally spaced values from 0 to 15</span></span>
<span id="cb4-4">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">101</span>)</span>
<span id="cb4-5">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'sin x'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sin(df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>])</span>
<span id="cb4-6"></span>
<span id="cb4-7">df.plot(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'sin x'</span>)</span>
<span id="cb4-8">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'assets\pes_sine_plot.png'</span>)</span></code></pre></div>
<p><img src="https://amamaral.github.io/blog/assets/pes_sine_plot.png" class="img-fluid"></p>
<p>The graphical representation (and the dataframe itself) can be used to find (or approximate) roots of transcendental equations. For instance, suppose that we want to find the solutions of <img src="https://latex.codecogs.com/png.latex?A%20x%20=%20%5Csin%20x">. The previous problem can be expressed as finding the zeros of <img src="https://latex.codecogs.com/png.latex?%5Csin%20x%20-%20A%20x">. Suppose that we want to evaluate the solutions for both <img src="https://latex.codecogs.com/png.latex?A=0.2">, we may use Pandas to evaluate that</p>
<div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'A=0.2'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sin(df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>]) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>]</span>
<span id="cb5-2">df.plot(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'A=0.2'</span>)</span>
<span id="cb5-3">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'assets\pes_transcendental_sol_plot.png'</span>)</span></code></pre></div>
<p><img src="https://amamaral.github.io/blog/assets/pes_transcendental_sol_plot.png" class="img-fluid"></p>
<p>We can see that there is a trivial solution at <code>x=0</code> but there also should be a solution around <code>x=2</code>, where the function becomes zero again. How to find the best value? We can directly look out for the values in <code>df['A=0.2']</code>, but there are just too many values. A simpler way however is to ask Pandas to filter the <code>DataFrame</code> and consider only values which are sufficiently close to 0. This way we have to look only in a smaller subset of the data. The condition <code>abs(df['A=0.2']) &lt; 0.1</code> asks Pandas to filter the table rows where the <code>abs</code>olute value of <code>df['A=0.2']</code> is smaller than <code>0.1</code>, and shows only these values.</p>
<div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1">df[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">abs</span>(df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'A=0.2'</span>]) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>]</span></code></pre></div>
<table class="caption-top table">
<thead>
<tr class="header">
<th style="text-align: center;"></th>
<th style="text-align: center;">x</th>
<th style="text-align: center;">sin x</th>
<th style="text-align: center;">A=0.2</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: center;">0</td>
<td style="text-align: center;">0.00</td>
<td style="text-align: center;">0.000000</td>
<td style="text-align: center;">0.000000</td>
</tr>
<tr class="even">
<td style="text-align: center;">17</td>
<td style="text-align: center;">2.55</td>
<td style="text-align: center;">0.557684</td>
<td style="text-align: center;">0.047684</td>
</tr>
</tbody>
</table>
<p>The table above implies that <img src="https://latex.codecogs.com/png.latex?x=2.55"> has <img src="https://latex.codecogs.com/png.latex?%5Csin%20x%20-%200.2%20x%20=%200.05"> which, although not being an exact solution, is a reasonable approximation. The quality of the approximation improves if the spacing between <code>x</code> values becomes smaller, which can be achieved by reducing the range of <code>x</code> values or increasing the number of points. There are more accurate methods to find roots which will be discussed later.</p>
<p>Let’s now consider a new <code>DataFrame</code> where we will see some plotting capabilities. We will create a column <code>x</code> which contains numbers from 1 to 10 using a Numpy’s <code>arange</code> and then create some powers of <code>x</code> as</p>
<div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1">df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame() <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Clears df</span></span>
<span id="cb7-2"></span>
<span id="cb7-3">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> arange(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#Array of integers from 1 to 10=11-1</span></span>
<span id="cb7-4">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x**2'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb7-5">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x**3'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span></span>
<span id="cb7-6">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x**0.5'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span></span>
<span id="cb7-7"></span>
<span id="cb7-8">df</span></code></pre></div>
<table class="caption-top table">
<thead>
<tr class="header">
<th style="text-align: center;"></th>
<th style="text-align: center;">x</th>
<th style="text-align: center;">x**2</th>
<th style="text-align: center;">x**3</th>
<th style="text-align: center;">x**0.5</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: center;">0</td>
<td style="text-align: center;">1</td>
<td style="text-align: center;">1</td>
<td style="text-align: center;">1</td>
<td style="text-align: center;">1.000000</td>
</tr>
<tr class="even">
<td style="text-align: center;">1</td>
<td style="text-align: center;">2</td>
<td style="text-align: center;">4</td>
<td style="text-align: center;">8</td>
<td style="text-align: center;">1.414214</td>
</tr>
<tr class="odd">
<td style="text-align: center;">2</td>
<td style="text-align: center;">3</td>
<td style="text-align: center;">9</td>
<td style="text-align: center;">27</td>
<td style="text-align: center;">1.732051</td>
</tr>
<tr class="even">
<td style="text-align: center;">3</td>
<td style="text-align: center;">4</td>
<td style="text-align: center;">16</td>
<td style="text-align: center;">64</td>
<td style="text-align: center;">2.000000</td>
</tr>
<tr class="odd">
<td style="text-align: center;">4</td>
<td style="text-align: center;">5</td>
<td style="text-align: center;">25</td>
<td style="text-align: center;">125</td>
<td style="text-align: center;">2.236068</td>
</tr>
<tr class="even">
<td style="text-align: center;">5</td>
<td style="text-align: center;">6</td>
<td style="text-align: center;">36</td>
<td style="text-align: center;">216</td>
<td style="text-align: center;">2.449490</td>
</tr>
<tr class="odd">
<td style="text-align: center;">6</td>
<td style="text-align: center;">7</td>
<td style="text-align: center;">49</td>
<td style="text-align: center;">343</td>
<td style="text-align: center;">2.645751</td>
</tr>
<tr class="even">
<td style="text-align: center;">7</td>
<td style="text-align: center;">8</td>
<td style="text-align: center;">64</td>
<td style="text-align: center;">512</td>
<td style="text-align: center;">2.828427</td>
</tr>
<tr class="odd">
<td style="text-align: center;">8</td>
<td style="text-align: center;">9</td>
<td style="text-align: center;">81</td>
<td style="text-align: center;">729</td>
<td style="text-align: center;">3.000000</td>
</tr>
<tr class="even">
<td style="text-align: center;">9</td>
<td style="text-align: center;">10</td>
<td style="text-align: center;">100</td>
<td style="text-align: center;">1000</td>
<td style="text-align: center;">3.162278</td>
</tr>
</tbody>
</table>
<p>Now we want to plot the columns involving <img src="https://latex.codecogs.com/png.latex?x%5E2"> and <img src="https://latex.codecogs.com/png.latex?%5Csqrt%7Bx%7D"> in the same plot. We can use the following instructions.</p>
<div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1">ax1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df.plot(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x**2'</span>  , color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'red'</span> , kind<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'scatter'</span>)</span>
<span id="cb8-2">ax2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df.plot(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x**0.5'</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'blue'</span>, kind<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'scatter'</span>,</span>
<span id="cb8-3">              ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax1)</span>
<span id="cb8-4"></span>
<span id="cb8-5">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'assets\multiple_scatter_plot.png'</span>)</span></code></pre></div>
<p><img src="https://amamaral.github.io/blog/assets/multiple_scatter_plot.png" class="img-fluid"></p>
<p>In the above plot we have set the colors for each scatter plot. <a href="https://matplotlib.org/stable/gallery/color/named_colors.html">several named colors are available</a>, with common names in English being available. To ensure that they are in the same figure it is necessary to be explicit by defining that both share their plot axes through <code>ax=ax1</code>. If this instruction is removed, we will obtain two separate plots.</p>
<p>Notice that in the previous combined plot it is not possible to see how <img src="https://latex.codecogs.com/png.latex?%5Csqrt%7Bx%7D"> varies. When the data varies by orders of magnitude it is often interesting to use logarithmic scales. Below we repeat the previous plot, but now ensuring that both axes are logarithmic by setting <code>logx=True</code> and <code>logy=True</code>. Notice that the log scaling in each axis is set separately.</p>
<div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1">ax1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df.plot(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x**2'</span>  , color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'red'</span> , kind<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'scatter'</span>,</span>
<span id="cb9-2">              logx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, logy<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb9-3">ax2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df.plot(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x**0.5'</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'blue'</span>, kind<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'scatter'</span>,</span>
<span id="cb9-4">              ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax1)</span>
<span id="cb9-5"></span>
<span id="cb9-6">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'assets\multiple_scatter_plot_logxy.png'</span>)</span></code></pre></div>
<p><img src="https://amamaral.github.io/blog/assets/multiple_scatter_plot_logxy.png" class="img-fluid"></p>
<p>Whenever we see a linear curve with logarithmic axes the data must be described by a curve like <img src="https://latex.codecogs.com/png.latex?y%20=%20a%20x%5En">, since the relation between <img src="https://latex.codecogs.com/png.latex?%5Clog%20x"> and <img src="https://latex.codecogs.com/png.latex?%5Clog%20y"> in <img src="https://latex.codecogs.com/png.latex?%5Clog%20y%20=%20%5Clog%20a%20+%20n%20%5Clog%20x"> is equivalent to that of a straight line with intercept at <img src="https://latex.codecogs.com/png.latex?%5Clog%20a"> and slope <img src="https://latex.codecogs.com/png.latex?n">. Suppose that we want to find a model that closely describes our data. The straight line in the log-log plot indicates the general relation, <img src="https://latex.codecogs.com/png.latex?y=ax%5En">, but we still have to determine the values of <img src="https://latex.codecogs.com/png.latex?a"> and <img src="https://latex.codecogs.com/png.latex?n">. We will perform this in the next section</p>
</section>
<section id="data-fitting" class="level2">
<h2 class="anchored" data-anchor-id="data-fitting">Data fitting</h2>
<p>To fit experimental data to a proposed model, we will use another library. Scipy provides several numerical methods useful in scientific computing. In particular, <a href="https://docs.scipy.org/doc/scipy/reference/optimize.html">it has several optimization methods</a> to minimize, find roots and curve fitting. To add such capabilities to our program, we have to import Scipy’s <code>optimize</code> in our program as follows.</p>
<div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>pylab inline</span>
<span id="cb10-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd</span>
<span id="cb10-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> scipy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> optimize</span>
<span id="cb10-4"></span>
<span id="cb10-5">df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame()</span>
<span id="cb10-6"></span>
<span id="cb10-7">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> arange(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#Array of integers from 1 to 10=11-1</span></span>
<span id="cb10-8">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x**2'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb10-9">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x**3'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span></span>
<span id="cb10-10">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x**0.5'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pi <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span></span></code></pre></div>
<p>The data generated above behaves as a power law, <img src="https://latex.codecogs.com/png.latex?y=%20A%20x%5En">. To use Scipy’s <code>curve_fit</code>, we have to define a power law function as is given below. Notice that both the independent variable <code>x</code> and the parameters <code>A</code> and <code>n</code> are given as function input parameters, and the function returns the value associated with <code>A * x **n</code>. It’s remarked that <code>curve_fit</code> requires that the parameters to be fit (<code>A</code>, <code>n</code>) must be given after the independent variable <code>x</code>.</p>
<div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> power_law(x, A, n):</span>
<span id="cb11-2">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> A <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span> n</span></code></pre></div>
<p>Now we can fit the data present in the dataframe <code>df</code>. <code>optimize</code> gives two outputs. The first, <code>popt</code>, gives the optimal parameter values. <code>popt[0]</code> gives the best estimate for the first parameter of <code>power_law</code> (<code>A</code>), while <code>popt[1]</code> is associated with the value of <code>n</code>. <code>pcov</code> gives the covariance matrix between the fitting parameters, and is particularly relevant when the parameters are correlated. The error associated with the statistical uncertainty of the data can be obtained from <code>pcov</code> by taking the square root of its diagonal. As given below, <code>error[0]</code> is related to the uncertainty in <code>A</code> while <code>error[1]</code> corresponds to <code>n</code>.</p>
<div class="sourceCode" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1">popt, pcov <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> optimize.curve_fit(power_law, df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>], df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x**0.5'</span>])</span>
<span id="cb12-2">error <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sqrt(pcov.diagonal())</span>
<span id="cb12-3">popt, error</span></code></pre></div>
<pre><code>(array([3.14159265 0.5       ]), array([3.05923019e-16 5.08058315e-17]))</code></pre>
<p>From the example above is it possible to state that <img src="https://latex.codecogs.com/png.latex?A%20=%203.14159265%20%5Cpm%203.05923019%20%5Ccdot%2010%20%5E%20%7B-16%7D"> and <img src="https://latex.codecogs.com/png.latex?n%20=%200.5%20%5Cpm%205.08058315%5Ccdot%2010%5E%7B-17%7D">? These small uncertainty levels are limited to the machine accuracy, such they are meaningless in the real world. Statistical errors are often reported with at most 1 or 2 significant digits. Do not report all of the numbers shown from the fitting procedure above when considering real world data. You must round the uncertainty to 1 or 2 significant digits and then see how many significant digits there are in your mean value. Round the reported mean values from the adjusted error. For example, the uncertainty in <code>A</code> should be rounded to <img src="https://latex.codecogs.com/png.latex?3%20%5Ccdot%2010%20%5E%20%7B-16%7D">, which indicates that we could report the value of <img src="https://latex.codecogs.com/png.latex?A"> up to <img src="https://latex.codecogs.com/png.latex?10%20%5E%20%7B-16%7D">. Since the mean value for <code>A</code> shows only the significant digits up to <img src="https://latex.codecogs.com/png.latex?10%5E%7B-8%7D">, we can state that <img src="https://latex.codecogs.com/png.latex?A=3.14159265"> with no significant uncertainty. Application of the same reasoning to <img src="https://latex.codecogs.com/png.latex?n"> implies that <img src="https://latex.codecogs.com/png.latex?n=0.5">. Therefore, the data set above corresponds to <img src="https://latex.codecogs.com/png.latex?y%20=%203.14159265%20x%5E%7B0.5%7D">, as it should be. Change the code above to fit the other columns, <code>x**2</code> and <code>x**3</code> and see that you obtain the correct values for <img src="https://latex.codecogs.com/png.latex?A"> and <img src="https://latex.codecogs.com/png.latex?n">.</p>
<p>We may represent the original data and the fitted curve in the same plot to visually inspect the quality of the fitting procedure and the model suitability. The procedure is similar to the one showed in the end of the previous section, but here we will create another <code>DataFrame</code> to show the proposed model at a higher resolution than the original data. Also notice that we added an option to remove the plot legend of <code>df2</code>, which is on by default.</p>
<div class="sourceCode" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1">df2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame()</span>
<span id="cb14-2"></span>
<span id="cb14-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># x contains 101 equally spaced points from 1 to 10</span></span>
<span id="cb14-4">df2[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">101</span>)</span>
<span id="cb14-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Remember that popt[0] corresponds to A and popt[1] to n</span></span>
<span id="cb14-6">df2[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> power_law(df2[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>], popt[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], popt[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb14-7"></span>
<span id="cb14-8">ax1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df.plot(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x**0.5'</span>, kind<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'scatter'</span>,</span>
<span id="cb14-9">              logx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, logy<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb14-10">ax2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df2.plot(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y'</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax1, legend<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb14-11">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'assets\scatter_plot_fitting_data.png'</span>)</span></code></pre></div>
<p><img src="https://amamaral.github.io/blog/assets/scatter_plot_fitting_data.png" class="img-fluid"></p>
<p>Let’s now work on a more challenging fit. Consider the hypothetical data set below associated with the measurements of the signal normalized amplitude versus frequency (in rad/s) for a resonating circuit. The table is transposed (<code>df.T</code>) for a better visualization.</p>
<div class="sourceCode" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1">df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame()</span>
<span id="cb15-2">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Frequency'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">300</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">400</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">600</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">700</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">800</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">900</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>]</span>
<span id="cb15-3">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Amplitude'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.11</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.32</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.96</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.54</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.31</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.22</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.18</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.15</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.12</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.11</span>]</span>
<span id="cb15-4"></span>
<span id="cb15-5">df.T</span></code></pre></div>
<table class="caption-top table">
<colgroup>
<col style="width: 15%">
<col style="width: 8%">
<col style="width: 8%">
<col style="width: 8%">
<col style="width: 8%">
<col style="width: 8%">
<col style="width: 8%">
<col style="width: 8%">
<col style="width: 8%">
<col style="width: 8%">
<col style="width: 8%">
</colgroup>
<thead>
<tr class="header">
<th style="text-align: center;"></th>
<th style="text-align: center;">0</th>
<th style="text-align: center;">1</th>
<th style="text-align: center;">2</th>
<th style="text-align: center;">3</th>
<th style="text-align: center;">4</th>
<th style="text-align: center;">5</th>
<th style="text-align: center;">6</th>
<th style="text-align: center;">7</th>
<th style="text-align: center;">8</th>
<th style="text-align: center;">9</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: center;">Frequency</td>
<td style="text-align: center;">100</td>
<td style="text-align: center;">200</td>
<td style="text-align: center;">300</td>
<td style="text-align: center;">400</td>
<td style="text-align: center;">500</td>
<td style="text-align: center;">600</td>
<td style="text-align: center;">700</td>
<td style="text-align: center;">800</td>
<td style="text-align: center;">900</td>
<td style="text-align: center;">1000</td>
</tr>
<tr class="even">
<td style="text-align: center;">Amplitude</td>
<td style="text-align: center;">0.11</td>
<td style="text-align: center;">0.32</td>
<td style="text-align: center;">0.96</td>
<td style="text-align: center;">0.54</td>
<td style="text-align: center;">0.31</td>
<td style="text-align: center;">0.22</td>
<td style="text-align: center;">0.18</td>
<td style="text-align: center;">0.15</td>
<td style="text-align: center;">0.12</td>
<td style="text-align: center;">0.11</td>
</tr>
</tbody>
</table>
<p>The model for the resonating circuit amplitude response is given by <img src="https://latex.codecogs.com/png.latex?y%20=%20%20%5Cfrac%7B1%7D%7B%5Csqrt%7B1%20+%20A%20%5Cleft(%5Cfrac%7Bx%7D%7Bw_r%7D%20-%20%5Cfrac%7Bw_r%7D%7Bx%7D%5Cright)%5E2%7D%7D,"> which has two parameters, <img src="https://latex.codecogs.com/png.latex?A"> and <img src="https://latex.codecogs.com/png.latex?w_r">. Let’s try to repeat the previous procedure to fit this data. We have to define the fitting function model, <code>ressonant</code>, and use <code>optimize.curve_fit</code> to find the best values of <img src="https://latex.codecogs.com/png.latex?A"> and <img src="https://latex.codecogs.com/png.latex?w_r">. Later we try to represent both the original dataset and the model in the same plot. Everything is done at one in the block of code below.</p>
<div class="sourceCode" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> ressonant(x, A, wr):</span>
<span id="cb16-2">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> sqrt( <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> A <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>wr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> wr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>x)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> )</span>
<span id="cb16-3"></span>
<span id="cb16-4">popt, pcov <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> optimize.curve_fit(ressonant,</span>
<span id="cb16-5">                df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Frequency'</span>], df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Amplitude'</span>])</span>
<span id="cb16-6">error <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sqrt(pcov.diagonal())</span>
<span id="cb16-7"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(popt, error)</span>
<span id="cb16-8"></span>
<span id="cb16-9">df2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame()</span>
<span id="cb16-10">df2[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">101</span>)</span>
<span id="cb16-11">df2[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ressonant(df2[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>], popt[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], popt[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb16-12"></span>
<span id="cb16-13">ax1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df.plot(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Frequency'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Amplitude'</span>, kind<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'scatter'</span>)</span>
<span id="cb16-14">ax2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df2.plot(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y'</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax1, legend<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb16-15">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'assets\scatter_plot_fitting_resonant_data_attempt1.png'</span>)</span></code></pre></div>
<p><img src="https://amamaral.github.io/blog/assets/scatter_plot_fitting_resonant_data_attempt1.png" class="img-fluid"></p>
<p>The fit fails miserably. What has gone wrong? The fitting procedure indeed has found a solution which goes through the middle of the data, but it could not adjust the peaking behavior close to 300. Numerically this is a very unstable problem and we must give an initial guess to <code>optimize.curve_fit</code>. To that purpose, we must understand the meaning of the initial parameters and try to inform an initial estimate for <img src="https://latex.codecogs.com/png.latex?A"> and <img src="https://latex.codecogs.com/png.latex?w_r">. Notice that the present model for the resonant circuit amplitude has <img src="https://latex.codecogs.com/png.latex?y=1"> when <img src="https://latex.codecogs.com/png.latex?x=w_r">, such that <img src="https://latex.codecogs.com/png.latex?w_r"> is associated with the position where the data becomes maximum. As an initial guess, we can try to use <img src="https://latex.codecogs.com/png.latex?w_r%20=%20300">. The parameter <img src="https://latex.codecogs.com/png.latex?A"> is related with the width of the peak, such that we may consider an initial estimate of <img src="https://latex.codecogs.com/png.latex?A=100">. To inform this initial guess to <code>optimize.curve_fit</code> we add these guesses to <code>initial_guess</code> and inform this as <code>p0</code> to <code>curve_fit</code>. The remaining of the code is essentially identical.</p>
<div class="sourceCode" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1">initial_guess <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">300</span>]</span>
<span id="cb17-2"></span>
<span id="cb17-3">popt, pcov <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> optimize.curve_fit(ressonant,</span>
<span id="cb17-4">                df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Frequency'</span>], df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Amplitude'</span>], p0<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>initial_guess)</span>
<span id="cb17-5">error <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sqrt(pcov.diagonal())</span>
<span id="cb17-6"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(popt, error)</span>
<span id="cb17-7"></span>
<span id="cb17-8">df2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame()</span>
<span id="cb17-9">df2[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">101</span>)</span>
<span id="cb17-10">df2[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ressonant(df2[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>], popt[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], popt[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb17-11"></span>
<span id="cb17-12">ax1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df.plot(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Frequency'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Amplitude'</span>, kind<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'scatter'</span>)</span>
<span id="cb17-13">ax2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df2.plot(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y'</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax1, legend<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb17-14">title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Signal amplitude after a resonant circuit"</span>)</span>
<span id="cb17-15">xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Frequency (rad/s)"</span>)</span>
<span id="cb17-16">ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Amplitude (normalized)"</span>)</span>
<span id="cb17-17">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'assets\scatter_plot_fitting_resonant_data_attempt2.png'</span>)</span></code></pre></div>
<p><code>[ 10.06551017 313.950265  ] [0.10765985 0.44215353]</code></p>
<p><img src="https://amamaral.github.io/blog/assets/scatter_plot_fitting_resonant_data_attempt2.png" class="img-fluid"></p>
<p>Now it is clear that the best fit parameters closely follow the initial data. Some instructions were added to set the plot title and axis labels. From the values of <code>popt</code> and <code>error</code>, the best values now are <img src="https://latex.codecogs.com/png.latex?A=10.1%20%5Cpm%200.1">, while <img src="https://latex.codecogs.com/png.latex?w_r=313.9%20%5Cpm%200.4"> rad/s. Notice that even though our fist estimate for <img src="https://latex.codecogs.com/png.latex?A"> was wrong by an order of magnitude, the fitting procedure was successful. Therefore, sometimes we have to try several values for <code>initial_guess</code>. Instead of guessing blindly, we can try to compare the initial guess with the experimental data by replacing the parameters in <code>df2['y']</code> to use the initial guess. After we are sufficiently satisfied with our initial guess we replace to the previous code. An example of how to achieve this is given below. When <code>plotInitialGuess = True</code>, the plot will ignore the fitted data. Then you may tune the values within <code>initial_guess</code> until you see a curve that somewhat follows the data. Then you may set <code>plotInitialGuess = False</code> and the code will automatically show the final plot result. Curve fitting needs some trial and error, so you may need to tune the parameters a few times.</p>
<div class="sourceCode" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1">plotInitialGuess <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span>
<span id="cb18-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> plotInitialGuess:</span>
<span id="cb18-3">  df2[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ressonant(df2[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>], initial_guess[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], initial_guess[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb18-4"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb18-5">  df2[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ressonant(df2[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>], popt[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], popt[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span></code></pre></div>
<p>The full code for fitting the curve is given below for convenience. Notice that it is visible how the curve width is too small with the initial guess for <img src="https://latex.codecogs.com/png.latex?A">. With the code below you can tune <code>initial_guess</code> until the curve given by <code>model</code> has a pattern similar to the data. Then you should set <code>plotInitialGuess = False</code> and see if the best fit model seems to describe the data correctly. If the fit is satisfactory, extract the fit parameters. Otherwise you should set <code>plotInitialGuess = True</code> again and try to use a different <code>initial_guess</code>.</p>
<div class="sourceCode" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb19-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># model(x, parameters separated by commas)</span></span>
<span id="cb19-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> model(x, A, wr):</span>
<span id="cb19-3">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># return y(x) expressed in terms of the fitting parameters</span></span>
<span id="cb19-4">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> sqrt( <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> A <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>wr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> wr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>x)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> )</span>
<span id="cb19-5"></span>
<span id="cb19-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Initial guess for the parameter values (ordered as in the model)</span></span>
<span id="cb19-7">initial_guess <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">300</span>]</span>
<span id="cb19-8"></span>
<span id="cb19-9">popt, pcov <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> optimize.curve_fit(model,</span>
<span id="cb19-10">                df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Frequency'</span>], df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Amplitude'</span>], p0<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>initial_guess)</span>
<span id="cb19-11">error <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sqrt(pcov.diagonal())</span>
<span id="cb19-12"></span>
<span id="cb19-13">df2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame()</span>
<span id="cb19-14">df2[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">101</span>)</span>
<span id="cb19-15"></span>
<span id="cb19-16">plotInitialGuess <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span>
<span id="cb19-17"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> plotInitialGuess:</span>
<span id="cb19-18">  df2[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model(df2[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>], initial_guess[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], initial_guess[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb19-19"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb19-20">  df2[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model(df2[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>], popt[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], popt[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb19-21">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Outputs the best fit params and associated errors</span></span>
<span id="cb19-22">  <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Fit parameters"</span>)</span>
<span id="cb19-23">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i, (p, e) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(popt, error)):</span>
<span id="cb19-24">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'p[</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%d</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">] ='</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span> i, p, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">' +- '</span>, e)</span>
<span id="cb19-25"></span>
<span id="cb19-26">ax1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df.plot(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Frequency'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Amplitude'</span>, kind<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'scatter'</span>)</span>
<span id="cb19-27">ax2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df2.plot(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y'</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax1, legend<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb19-28">title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Output signal amplitude"</span>)</span>
<span id="cb19-29">xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Frequency (rad/s)"</span>)</span>
<span id="cb19-30">ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Amplitude (normalized)"</span>)</span>
<span id="cb19-31">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'assets\scatter_plot_fitting_resonant_data_final.png'</span>)</span></code></pre></div>
<p><img src="https://amamaral.github.io/blog/assets/scatter_plot_fitting_resonant_data_final.png" class="img-fluid"></p>
<!---
An alternative to the implementation above would be to set two subplots, one with the initial guess, the other one with the fitted curve.

The idea below maybe could be used as an exercise. Put the data available online and set as an exercise.
## Fitting experimental data

## Examples with real data
### Diode current-voltage curve
### RLC circuit frequency response
### Harmonic distortion in a sinusoid (?)
--->
<!---
## Reading and writing data from files

### CSV/dat/txt files

- Reading text files
- Caveat: `.` or `,`?

### Excel/ODT spreadsheets

### Text and string manipulations

## Statistical error propagation in some simple datasets (?)

Maybe add this to the first data analysis section. This is important since given the dataset it becomes easier to perform calculations over a large dataset.
--->
</section>
<section id="using-the-jupyter-notebook-for-scientific-writing" class="level2">
<h2 class="anchored" data-anchor-id="using-the-jupyter-notebook-for-scientific-writing">Using the Jupyter notebook for scientific writing</h2>
<p>With our previous discussion it is possible to analyze data. But how to write a report? It is possible to use common tools as a word processor, but we also can use our Jupyter notebook to produce reports in PDF format, slideshows and HTML webpages. While the standard PDF output is somewhat limited, it is possible to export to other formats (as LaTex) and edit the result to achieve professional looking documents. This is interesting because the data analysis and its analysis are condensed in the same file, making it easier to correct mistakes during the work. Also, the compatibility means that the document can be exported to a document format commonly used in the publication of scientific documents.</p>
<p>The Jupyter notebook is separated in cells. The default cells are for code, such we can execute portions of code separately and perform exploratory studies. We can add more cells (using the <code>+</code> button close to the save button in the snapshot below), split or join cells (see the Edit menu). However, the Jupyter screenshot below shows a menu where the type of the current cell can be chosen. The Markdown mode is adequate to type descriptive texts and can be placed anywhere within the notebook, such it is possible to mix explanations and the code necessary to achieve the results reported.</p>
<p><img src="https://amamaral.github.io/blog/assets/jupyter_select_markdown.png" class="img-fluid"></p>
<p><a href="https://daringfireball.net/projects/markdown/">Markdown</a> is a simple syntax developed to express document formatting in plain text. It is aimed at being simple and readable, such that it can be learned much more quickly than LaTex for example. Also, an interesting characteristic is that it allows the writer to focus on content instead of text formatting. This document is written using Markdown, and this syntax is recognized by several web tools. For example, to put emphasis in a text block we can write it between single asterisks <code>*text*</code> to obtain the <em>text</em> in italics. Writing between double asterisks around <code>**some text**</code> gives <strong>some text</strong> in bold. The table below shows some examples of what can be done.</p>
<!---
~~~{.python}
from collections import OrderedDict
# Generates Markdown tables with example commands

commands = OrderedDict()
commands['Italics'] = '*italics*'
commands['Bold'] = '**bold**'
# commands['Strike through'] = '~corrected text~' #does not work in pandoc, just jupyter notebook...
commands['Inline code'] = ' `some code` '
commands['Math'] = '$x = \sin\pi/2$'
commands['Link'] = '[link label](https://commonmark.org)'
commands['Image'] = '![Image](/blog/assets/markdown-mark.png){width=40px}'

print("| To obtain | type | to get |")
print("|:----------|:----:|:------:|")
for key, value in commands.items():
  print("| %s | ``%s`` | %s |"%(key, value, value))
~~~
--->
<table class="caption-top table">
<thead>
<tr class="header">
<th style="text-align: left;">To obtain</th>
<th style="text-align: center;">type</th>
<th style="text-align: center;">to get</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: left;">Italics</td>
<td style="text-align: center;"><code>*italics*</code></td>
<td style="text-align: center;"><em>italics</em></td>
</tr>
<tr class="even">
<td style="text-align: left;">Bold</td>
<td style="text-align: center;"><code>**bold**</code></td>
<td style="text-align: center;"><strong>bold</strong></td>
</tr>
<tr class="odd">
<td style="text-align: left;">Inline code</td>
<td style="text-align: center;"><code>`some code`</code></td>
<td style="text-align: center;"><code>some code</code></td>
</tr>
<tr class="even">
<td style="text-align: left;">Math</td>
<td style="text-align: center;"><code>$x = \sin\pi/2$</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?x%20=%20%5Csin%5Cpi/2"></td>
</tr>
<tr class="odd">
<td style="text-align: left;">Link</td>
<td style="text-align: center;"><code>[link label](https://commonmark.org)</code></td>
<td style="text-align: center;"><a href="https://commonmark.org">link label</a></td>
</tr>
<tr class="even">
<td style="text-align: left;">Image</td>
<td style="text-align: center;"><code>![Image](/blog/assets/markdown-mark.png){width=40px}</code></td>
<td style="text-align: center;"><img src="https://amamaral.github.io/blog/assets/markdown-mark.png" class="img-fluid" width="40" alt="Image"></td>
</tr>
</tbody>
</table>
<p>The typing of hypertext becomes reasonably simple using the above syntax, and it can be memorized without too much effort. After you execute the cell, Jupyter notebook will automatically exhibit the formatted output. To use images in your computer as above, remember that it must be sent together with your notebook to be seen by someone else. Images from the web can be shown by using the adequate url. Some will be given later to help in writing mathematical expressions.</p>
<p>Another set of Markdown instructions is to handle sections and blocks of text. Notice that <strong>to separate between distinct blocks must be separated by blank lines.</strong> Your document can be divided in sections with the syntax below. Up to 6 levels can be used, and using this is interesting because it makes easier to navigate through the PDF and outputs.</p>
<pre><code># Section

## Subsection

### Subsubsection</code></pre>
<p>To add a quote, use</p>
<pre><code>&gt; quote text</code></pre>
<p>to achieve</p>
<blockquote class="blockquote">
<p>quote text</p>
</blockquote>
<p>A bullet list can also be written simply by writing the first character of each line as a <code>*</code> or <code>-</code>, as in</p>
<pre><code>* item 1
* item 2
* item 3</code></pre>
<p>to achieve</p>
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
<p>A numbered list can be achieved by starting the line with a number followed by a point. The numbering will start from the first number and the subsequent will be set automatically, such you don’t have to worry with the exact numbers written.</p>
<pre><code>1. item 1
1. item 2
42. item 3</code></pre>
<p>gives</p>
<ol type="1">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ol>
<p>An horizontal rule can be obtained by starting a line with <code>---</code> or more dashes, achieving</p>
<hr>
<p>To add comments that will not appear in the output, use <code>&lt;!--- hidden ---&gt;</code>. The comments may also span several lines, as in</p>
<pre><code>&lt;!---
this entire block will not be shown in the output

so anything can be written here
---&gt;</code></pre>
<p>A code section (or <code>verbatim</code>, unformatted and monospaced text) can be set inside some paragraph using the syntax above, but for longer sections it is possible to use the notation below</p>
<pre><code>```
This is a section of text
which is useful to put some code
```</code></pre>
<p>which results in</p>
<pre><code>This is a section of text
which is useful to put some code</code></pre>
<p>Finally, while mathematical expressions can be placed inside the paragraph by placing the mathematical expression between single dollar signs, as in <code>$x=2$</code> to obtain <img src="https://latex.codecogs.com/png.latex?x=2">. However, to highlight some expression it is possible to write the expression between <code>$$x=2$$</code> to separate it from the paragraph and make it centered, as in <img src="https://latex.codecogs.com/png.latex?x=2"> The next subsection explains how to write some sophisticate mathematical expressions.</p>
<section id="writing-mathematical-expressions" class="level3">
<h3 class="anchored" data-anchor-id="writing-mathematical-expressions">Writing mathematical expressions</h3>
<p> is a very robust language used to produce documents, being actively developed since 1984. Throughout the years lots of add-ons there were developed to handle difficult aspects of document formatting, as advanced typography and taking care of references. is particularly powerful to typeset math expressions and has lots of features, and it’s notation became an important standard to write math using computers. Jupyter notebook does not carry the whole power of , since it is constrained to the features provided by <a href="https://www.mathjax.org/">MathJax</a>. However, several general features are available and this subsection will start with an overview of mathematical symbols. For instance, the table below shows how to write greek letters.</p>
<!---
~~~{.python}
# Greek letter markdown table generator
# Following https://oeis.org/wiki/List_of_LaTeX_mathematical_symbols

letters = [['alpha'], ['beta'], ['gamma', 'Gamma'],
           ['delta', 'Delta'], ['epsilon', 'varepsilon'],
           ['zeta'], ['eta'], ['theta', 'Theta'],
           ['iota'], ['kappa', 'varkappa'],
           ['lambda', 'Lambda'], ['mu'], ['nu'],
           ['xi', 'Xi'], ['circle'], ['pi', 'Pi', 'varpi'],
           ['rho', 'varrho'], ['sigma', 'Sigma', 'varsigma'],
           ['tau'], ['upsilon', 'Upsilon'], ['phi','Phi','varphi'],
           ['chi'], ['psi', 'Psi'], ['omega', 'Omega']]

l1 = letters[0:8]
l2 = letters[8:16]
l3 = letters[16:24]

print("| Symbol | Latex | Symbol | Latex | Symbol | Latex |")
print("|:------:|:-----:|:------:|:-----:|:------:|:-----:|")
for i,j,k in zip(l1, l2, l3):
  out = ''
  for o in [i, j, k]:
    stro = ''
    for a in o:
      stro+=', \\' + a
    stro = stro[2:]

    out += '| $' + stro + '$ | `' + stro + '`'
  out += '|'

  print(out)
~~~
--->
<table class="caption-top table">
<colgroup>
<col style="width: 17%">
<col style="width: 15%">
<col style="width: 17%">
<col style="width: 15%">
<col style="width: 17%">
<col style="width: 15%">
</colgroup>
<thead>
<tr class="header">
<th style="text-align: center;">Symbol</th>
<th style="text-align: center;">Latex</th>
<th style="text-align: center;">Symbol</th>
<th style="text-align: center;">Latex</th>
<th style="text-align: center;">Symbol</th>
<th style="text-align: center;">Latex</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Calpha"></td>
<td style="text-align: center;"><code>\alpha</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Ciota"></td>
<td style="text-align: center;"><code>\iota</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Crho,%20%5Cvarrho"></td>
<td style="text-align: center;"><code>\rho, \varrho</code></td>
</tr>
<tr class="even">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cbeta"></td>
<td style="text-align: center;"><code>\beta</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Ckappa,%20%5Cvarkappa"></td>
<td style="text-align: center;"><code>\kappa, \varkappa</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Csigma,%20%5CSigma,%20%5Cvarsigma"></td>
<td style="text-align: center;"><code>\sigma, \Sigma, \varsigma</code></td>
</tr>
<tr class="odd">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cgamma,%20%5CGamma"></td>
<td style="text-align: center;"><code>\gamma, \Gamma</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Clambda,%20%5CLambda"></td>
<td style="text-align: center;"><code>\lambda, \Lambda</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Ctau"></td>
<td style="text-align: center;"><code>\tau</code></td>
</tr>
<tr class="even">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cdelta,%20%5CDelta"></td>
<td style="text-align: center;"><code>\delta, \Delta</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cmu"></td>
<td style="text-align: center;"><code>\mu</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cupsilon,%20%5CUpsilon"></td>
<td style="text-align: center;"><code>\upsilon, \Upsilon</code></td>
</tr>
<tr class="odd">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cepsilon,%20%5Cvarepsilon"></td>
<td style="text-align: center;"><code>\epsilon, \varepsilon</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cnu"></td>
<td style="text-align: center;"><code>\nu</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cphi,%20%5CPhi,%20%5Cvarphi"></td>
<td style="text-align: center;"><code>\phi, \Phi, \varphi</code></td>
</tr>
<tr class="even">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Czeta"></td>
<td style="text-align: center;"><code>\zeta</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cxi,%20%5CXi"></td>
<td style="text-align: center;"><code>\xi, \Xi</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cchi"></td>
<td style="text-align: center;"><code>\chi</code></td>
</tr>
<tr class="odd">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Ceta"></td>
<td style="text-align: center;"><code>\eta</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5C,"></td>
<td style="text-align: center;"><code></code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cpsi,%20%5CPsi"></td>
<td style="text-align: center;"><code>\psi, \Psi</code></td>
</tr>
<tr class="even">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Ctheta,%20%5CTheta"></td>
<td style="text-align: center;"><code>\theta, \Theta</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cpi,%20%5CPi,%20%5Cvarpi"></td>
<td style="text-align: center;"><code>\pi, \Pi, \varpi</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Comega,%20%5COmega"></td>
<td style="text-align: center;"><code>\omega, \Omega</code></td>
</tr>
</tbody>
</table>
<p>Notice that omicron is the only greek letter that is not explicitly supported since it is indistinguishable from the latin letter o. Regarding notation, superscripts and subscripts are written respectively as <code>^</code> and <code>_</code>, such <code>$2^3$</code> and <code>$a_n$</code> become <img src="https://latex.codecogs.com/png.latex?2%5E3"> and <img src="https://latex.codecogs.com/png.latex?a_n">, respectively. Quite often the latex expressions must have long sub- or super-scripts, such it is necessary to indicate with curly braces <code>{}</code> where the sub-(super-)script starts and ends. The next table also shows some common symbols and expressions in .</p>
<!---
~~~{.python}
# Greek letter markdown table generator
# Following https://oeis.org/wiki/List_of_LaTeX_mathematical_symbols

expressions = ['^\circ C', 'e^{-x}', '\Gamma_i^j', '\\frac{a}{x}', '\\vec{E}', '\hat{a}^\dagger',
               '\\dot{x} \\ddot{x}', '\\int_a^b', '\\sum_{i}^{N}', '\\cdot\\,\\times', '\\gg \\geq',
               '\\ll \\leq', '\\approx', '\\equiv', '\\propto', '\\neq', '\\pm \\mp',
               '\\hbar', '\\ell', '\\Re \\Im', '\\partial \\nabla', '\\square', '\\infty']

print(len(expressions))

l1 = expressions[0:6]
l2 = expressions[6:12]
l3 = expressions[12:18]
l4 = expressions[18:24]

out = ''
out += "| Expr | Latex | Expr | Latex | Expr | Latex | Expr | Latex |\n"
out += "|:----:|:-----:|:----:|:-----:|:----:|:-----:|:----:|:-----:|\n"

for i,j,k, l in zip(l1, l2, l3, l4):
    for o in [i, j, k, l]:
        out += '| $' + o + '$ | `' + o + '`'
    out += '|\n'

#from IPython import display
#display.display(display.Markdown(out))
print(out)
~~~
--->
<table class="caption-top table">
<colgroup>
<col style="width: 11%">
<col style="width: 13%">
<col style="width: 11%">
<col style="width: 13%">
<col style="width: 11%">
<col style="width: 13%">
<col style="width: 11%">
<col style="width: 13%">
</colgroup>
<thead>
<tr class="header">
<th style="text-align: center;">Expr</th>
<th style="text-align: center;">Latex</th>
<th style="text-align: center;">Expr</th>
<th style="text-align: center;">Latex</th>
<th style="text-align: center;">Expr</th>
<th style="text-align: center;">Latex</th>
<th style="text-align: center;">Expr</th>
<th style="text-align: center;">Latex</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5E%5Ccirc%20C"></td>
<td style="text-align: center;"><code>^\circ C</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cdot%7Bx%7D%20%5Cddot%7Bx%7D"></td>
<td style="text-align: center;"><code>\dot{x} \ddot{x}</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Capprox"></td>
<td style="text-align: center;"><code>\approx</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cell"></td>
<td style="text-align: center;"><code>\ell</code></td>
</tr>
<tr class="even">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?e%5E%7B-x%7D"></td>
<td style="text-align: center;"><code>e^{-x}</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cint_a%5Eb"></td>
<td style="text-align: center;"><code>\int_a^b</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cequiv"></td>
<td style="text-align: center;"><code>\equiv</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5CRe%20%5CIm"></td>
<td style="text-align: center;"><code>\Re \Im</code></td>
</tr>
<tr class="odd">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5CGamma_i%5Ej"></td>
<td style="text-align: center;"><code>\Gamma_i^j</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Csum_%7Bi%7D%5E%7BN%7D"></td>
<td style="text-align: center;"><code>\sum_{i}^{N}</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cpropto"></td>
<td style="text-align: center;"><code>\propto</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cpartial%20%5Cnabla"></td>
<td style="text-align: center;"><code>\partial \nabla</code></td>
</tr>
<tr class="even">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cfrac%7Ba%7D%7Bx%7D"></td>
<td style="text-align: center;"><code>\frac{a}{x}</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Ccdot%5C,%5Ctimes"></td>
<td style="text-align: center;"><code>\cdot\,\times</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cneq"></td>
<td style="text-align: center;"><code>\neq</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Csquare"></td>
<td style="text-align: center;"><code>\square</code></td>
</tr>
<tr class="odd">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cvec%7BE%7D"></td>
<td style="text-align: center;"><code>\vec{E}</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cgg%20%5Cgeq"></td>
<td style="text-align: center;"><code>\gg \geq</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cpm%20%5Cmp"></td>
<td style="text-align: center;"><code>\pm \mp</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cinfty"></td>
<td style="text-align: center;"><code>\infty</code></td>
</tr>
</tbody>
</table>
<p>More comprehensive lists of symbols and operators can be found in the internet, as in <a href="https://en.wikipedia.org/wiki/Wikipedia:LaTeX_symbols">Wikipedia</a> for example. The following table contains the instructions for several standard functions and a few more symbols.</p>
<!---
~~~{.python}
expressions = ['\\sin', '\\cos', '\\tan', '\\sinh', '\\cosh', '\\tanh',
               '\\exp', '\\log', '\\ln', '\\sec', '\\csc', '\\cot',
               '\\det', '\\lim', '\\min', '\\max', '\\arg', '\\sqrt{x}',
               '\sqrt[n]{a}','\\prod_i^N', '\\oint', '\\iint', '\\iiint', '\iiiint']

#print(len(expressions))

l1 = expressions[0:6]
l2 = expressions[6:12]
l3 = expressions[12:18]
l4 = expressions[18:24]

out = ''
out += "| Expr | Latex | Expr | Latex | Expr | Latex | Expr | Latex |\n"
out += "|:----:|:-----:|:----:|:-----:|:----:|:-----:|:----:|:-----:|\n"

for i,j,k, l in zip(l1, l2, l3, l4):
    for o in [i, j, k, l]:
        out += '| $' + o + '$ | `' + o + '`'
    out += '|\n'

#from IPython import display
#display.display(display.Markdown(out))
print(out)
~~~
--->
<table class="caption-top table">
<colgroup>
<col style="width: 11%">
<col style="width: 13%">
<col style="width: 11%">
<col style="width: 13%">
<col style="width: 11%">
<col style="width: 13%">
<col style="width: 11%">
<col style="width: 13%">
</colgroup>
<thead>
<tr class="header">
<th style="text-align: center;">Expr</th>
<th style="text-align: center;">Latex</th>
<th style="text-align: center;">Expr</th>
<th style="text-align: center;">Latex</th>
<th style="text-align: center;">Expr</th>
<th style="text-align: center;">Latex</th>
<th style="text-align: center;">Expr</th>
<th style="text-align: center;">Latex</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Csin"></td>
<td style="text-align: center;"><code>\sin</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cexp"></td>
<td style="text-align: center;"><code>\exp</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cdet"></td>
<td style="text-align: center;"><code>\det</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Csqrt%5Bn%5D%7Ba%7D"></td>
<td style="text-align: center;"><code>\sqrt[n]{a}</code></td>
</tr>
<tr class="even">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Ccos"></td>
<td style="text-align: center;"><code>\cos</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Clog"></td>
<td style="text-align: center;"><code>\log</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Clim"></td>
<td style="text-align: center;"><code>\lim</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cprod_i%5EN"></td>
<td style="text-align: center;"><code>\prod_i^N</code></td>
</tr>
<tr class="odd">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Ctan"></td>
<td style="text-align: center;"><code>\tan</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cln"></td>
<td style="text-align: center;"><code>\ln</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cmin"></td>
<td style="text-align: center;"><code>\min</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Coint"></td>
<td style="text-align: center;"><code>\oint</code></td>
</tr>
<tr class="even">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Csinh"></td>
<td style="text-align: center;"><code>\sinh</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Csec"></td>
<td style="text-align: center;"><code>\sec</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cmax"></td>
<td style="text-align: center;"><code>\max</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Ciint"></td>
<td style="text-align: center;"><code>\iint</code></td>
</tr>
<tr class="odd">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Ccosh"></td>
<td style="text-align: center;"><code>\cosh</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Ccsc"></td>
<td style="text-align: center;"><code>\csc</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Carg"></td>
<td style="text-align: center;"><code>\arg</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Ciiint"></td>
<td style="text-align: center;"><code>\iiint</code></td>
</tr>
<tr class="even">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Ctanh"></td>
<td style="text-align: center;"><code>\tanh</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Ccot"></td>
<td style="text-align: center;"><code>\cot</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Csqrt%7Bx%7D"></td>
<td style="text-align: center;"><code>\sqrt{x}</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Ciiiint"></td>
<td style="text-align: center;"><code>\iiiint</code></td>
</tr>
</tbody>
</table>
<p>In Portuguese the sine function should be written as sen, and this is not included by default. So, it is possible to express it in notation using <code>\operatorname{sen} x</code>, which results in <img src="https://latex.codecogs.com/png.latex?%5Coperatorname%7Bsen%7D%20x">. To finish this long list of available symbols, it’s useful to mention that has symbols which correspond to arrows and for brackets to group mathematical expressions. There are also instructions to control the spacing between symbols.</p>
<!---
~~~{.python}
expressions = ['\\leftarrow', '\\Leftarrow', '\\rightarrow', '\\Rightarrow', '\\leftrightarrow', '\\Leftrightarrow',
               '\\uparrow', '\\Uparrow', '\\downarrow', '\\Downarrow', '\\updownarrow', '\\Updownarrow',
               '()', '[]', '\\{\\}', '\\vert', '\\Vert', '\\langle \\rangle',
               'a \\! a', 'a a', 'a \\, a', 'a \\: a', 'a \\; a', 'a \\quad a']

print(len(expressions))

l1 = expressions[0:6]
l2 = expressions[6:12]
l3 = expressions[12:18]
l4 = expressions[18:24]

out = ''
out += "| Expr | Latex | Expr | Latex | Expr | Latex | Expr | Latex |\n"
out += "|:----:|:-----:|:----:|:-----:|:----:|:-----:|:----:|:-----:|\n"

for i in zip(l1, l2, l3, l4):
    for o in i:
        out += '| $' + o + '$ | `' + o + '`'
    out += '|\n'

#from IPython import display
#display.display(display.Markdown(out))
print(out)
~~~
--->
<table class="caption-top table">
<colgroup>
<col style="width: 11%">
<col style="width: 13%">
<col style="width: 11%">
<col style="width: 13%">
<col style="width: 11%">
<col style="width: 13%">
<col style="width: 11%">
<col style="width: 13%">
</colgroup>
<thead>
<tr class="header">
<th style="text-align: center;">Expr</th>
<th style="text-align: center;">Latex</th>
<th style="text-align: center;">Expr</th>
<th style="text-align: center;">Latex</th>
<th style="text-align: center;">Expr</th>
<th style="text-align: center;">Latex</th>
<th style="text-align: center;">Expr</th>
<th style="text-align: center;">Latex</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cleftarrow"></td>
<td style="text-align: center;"><code>\leftarrow</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cuparrow"></td>
<td style="text-align: center;"><code>\uparrow</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?()"></td>
<td style="text-align: center;"><code>()</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?a%20%5C!%20a"></td>
<td style="text-align: center;"><code>a \! a</code></td>
</tr>
<tr class="even">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5CLeftarrow"></td>
<td style="text-align: center;"><code>\Leftarrow</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5CUparrow"></td>
<td style="text-align: center;"><code>\Uparrow</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5B%5D"></td>
<td style="text-align: center;"><code>[]</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?a%20a"></td>
<td style="text-align: center;"><code>a a</code></td>
</tr>
<tr class="odd">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Crightarrow"></td>
<td style="text-align: center;"><code>\rightarrow</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cdownarrow"></td>
<td style="text-align: center;"><code>\downarrow</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5C%7B%5C%7D"></td>
<td style="text-align: center;"><code>\{\}</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?a%20%5C,%20a"></td>
<td style="text-align: center;"><code>a \, a</code></td>
</tr>
<tr class="even">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5CRightarrow"></td>
<td style="text-align: center;"><code>\Rightarrow</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5CDownarrow"></td>
<td style="text-align: center;"><code>\Downarrow</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cvert"></td>
<td style="text-align: center;"><code>\vert</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?a%20%5C:%20a"></td>
<td style="text-align: center;"><code>a \: a</code></td>
</tr>
<tr class="odd">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cleftrightarrow"></td>
<td style="text-align: center;"><code>\leftrightarrow</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cupdownarrow"></td>
<td style="text-align: center;"><code>\updownarrow</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5CVert"></td>
<td style="text-align: center;"><code>\Vert</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?a%20%5C;%20a"></td>
<td style="text-align: center;"><code>a \; a</code></td>
</tr>
<tr class="even">
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5CLeftrightarrow"></td>
<td style="text-align: center;"><code>\Leftrightarrow</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5CUpdownarrow"></td>
<td style="text-align: center;"><code>\Updownarrow</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Clangle%20%5Crangle"></td>
<td style="text-align: center;"><code>\langle \rangle</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?a%20%5Cquad%20a"></td>
<td style="text-align: center;"><code>a \quad a</code></td>
</tr>
</tbody>
</table>
<p>Notice that the curly brackets must be preceded by <code>\</code>, since otherwise they would be confused with the arguments of functions. Normally the brackets have a fixed size, but it is possible to allow them to change their sizes depending on what they enclose. For example, the parenthesis in <code>$(\frac{\int a}{b})$</code> will not match the height of what it encloses (try it). However, adding the instructions <code>\left</code> and <code>\right</code> to indicate what’s between the parenthesis it can adjust its size. This correction implies in writing <code>\left(\frac{\int a}{b}\right)</code> (see how the behavior changes). Finally, notice that the last column in the above table contains commands to change the spacing between symbols, ranging from a negative distance <code>\!</code> to quad spacing. There’s also <code>\qquad</code> which is even larger than <code>\quad</code>.</p>
<!---
~~~{.python}
expressions = [r'A = \left(15.02 \pm 0.02\right) 10^{-2}\text{ m}',
               r'\hbar = \frac{h}{2\pi} = 1.054 \cdot 10^{-34}\text{ J/s}',
               r'y(x) = \int_0^1 t\, dt = \left.\frac{t^2}{2}\right|_{t=0}^1',
               r'\sinh x= \frac{e^x - e^{-x}}{2}',
               r'e^x = \sum_{i=0}^\infty \frac{x^i}{i!} = \lim_{n \rightarrow \infty} \left( 1 + \frac{x}{n}  \right)^n',
               r'f(a) = \frac{1}{2\pi i} \oint \frac{f(z)}{z-a} dz',
               r'\vec\nabla\times\vec{H} = \mu_0\epsilon_0\frac{\partial\vec{E}}{\partial t}',
               r'\ddot{x} + \gamma \dot{x} + \omega^2 x = 0',
               r'w(z) = w_0 \sqrt{1 + \left(\frac{z}{z_R}\right)^2}']

out=''
for i in expressions:
    out += '`' + i + '`  $$' + i + '$$\n'

#from IPython import display
#display.display(display.Markdown(out))
print(out)
~~~
--->
<p>After showing so many possibilities, it is useful to show some examples on how to compose these symbols to write mathematical expressions. Below there are several examples where you can see how to express in a given formula.</p>
<p><code>A = \left(15.02 \pm 0.02\right) 10^{-2}\text{ m}</code> <img src="https://latex.codecogs.com/png.latex?A%20=%20%5Cleft(15.02%20%5Cpm%200.02%5Cright)%2010%5E%7B-2%7D%5Ctext%7B%20m%7D"> <code>\hbar = \frac{h}{2\pi} = 1.054 \cdot 10^{-34}\text{ J/s}</code> <img src="https://latex.codecogs.com/png.latex?%5Chbar%20=%20%5Cfrac%7Bh%7D%7B2%5Cpi%7D%20=%201.054%20%5Ccdot%2010%5E%7B-34%7D%5Ctext%7B%20J/s%7D"> <code>y(x) = \int_0^1 t\, dt = \left.\frac{t^2}{2}\right|_{t=0}^1</code> <img src="https://latex.codecogs.com/png.latex?y(x)%20=%20%5Cint_0%5E1%20t%5C,%20dt%20=%20%5Cleft.%5Cfrac%7Bt%5E2%7D%7B2%7D%5Cright%7C_%7Bt=0%7D%5E1"> <code>\sinh x= \frac{e^x - e^{-x}}{2}</code> <img src="https://latex.codecogs.com/png.latex?%5Csinh%20x=%20%5Cfrac%7Be%5Ex%20-%20e%5E%7B-x%7D%7D%7B2%7D"> <code>e^x = \sum_{i=0}^\infty \frac{x^i}{i!} = \lim_{n \rightarrow \infty} \left( 1 + \frac{x}{n}  \right)^n</code> <img src="https://latex.codecogs.com/png.latex?e%5Ex%20=%20%5Csum_%7Bi=0%7D%5E%5Cinfty%20%5Cfrac%7Bx%5Ei%7D%7Bi!%7D%20=%20%5Clim_%7Bn%20%5Crightarrow%20%5Cinfty%7D%20%5Cleft(%201%20+%20%5Cfrac%7Bx%7D%7Bn%7D%20%20%5Cright)%5En"> <code>f(a) = \frac{1}{2\pi i} \oint \frac{f(z)}{z-a} dz</code> <img src="https://latex.codecogs.com/png.latex?f(a)%20=%20%5Cfrac%7B1%7D%7B2%5Cpi%20i%7D%20%5Coint%20%5Cfrac%7Bf(z)%7D%7Bz-a%7D%20dz"> <code>\vec\nabla\times\vec{H} = \mu_0\epsilon_0\frac{\partial\vec{E}}{\partial t}</code> <img src="https://latex.codecogs.com/png.latex?%5Cvec%5Cnabla%5Ctimes%5Cvec%7BH%7D%20=%20%5Cmu_0%5Cepsilon_0%5Cfrac%7B%5Cpartial%5Cvec%7BE%7D%7D%7B%5Cpartial%20t%7D"> <code>\ddot{x} + \gamma \dot{x} + \omega^2 x = 0</code> <img src="https://latex.codecogs.com/png.latex?%5Cddot%7Bx%7D%20+%20%5Cgamma%20%5Cdot%7Bx%7D%20+%20%5Comega%5E2%20x%20=%200"> <code>w(z) = w_0 \sqrt{1 + \left(\frac{z}{z_R}\right)^2}</code> <img src="https://latex.codecogs.com/png.latex?w(z)%20=%20w_0%20%5Csqrt%7B1%20+%20%5Cleft(%5Cfrac%7Bz%7D%7Bz_R%7D%5Cright)%5E2%7D"></p>
<p>Notice that the equations between pairs of <code>$$</code> above are centered and separated from the text paragraph. For long documents it’s important to number and reference equations. Jupyter can handle this automatically, even though there are some rough edges when editting the notebook. <strong>Create and execute</strong> a code cell (preferably right when the document begins) containing only the instructions below to instruct MathJax to number <code>ams</code> equation environments. Another option is to use <code>all</code> instead of <code>ams</code>, such that equations between pairs of <code>$$</code> will also be numbered.</p>
<pre><code>%%javascript
MathJax.Hub.Config({
    TeX: { equationNumbers: { autoNumber: "ams" } }
});</code></pre>
<!--- Use here to achieve the same effect --->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    TeX: { equationNumbers: { autoNumber: "ams" } }
});
</script>
<p>The <code>ams</code> equation environments support more advanced modes to display equations. In summary, each environment is declared as <code>\begin{env} your equation \end{env}</code>, where <code>env</code> must be replaced by the environment of interest. Below there are some examples of some environments. Use the examples below within markdown cells.</p>
<!---
~~~{.python}
expressions = []
expressions.append(r"""\begin{equation}
y(x) = a x^2 + b x + c. \label{eq:quadratic_formula}
\end{equation}""")
expressions.append(r"""\begin{multline}
y(x) = a x^2 \\
+ b x \\
+ c.
\end{multline}""")
expressions.append(r"""\begin{align}
y &= 2 + 3, \nonumber \\
  &= 5. \label{eq:sum_result}
\end{align}""")
expressions.append(r"""\begin{align}
a &= 1, & b &= 2,\\
c &= 3, & d &= 4.
\end{align}""")

out=''
for i in expressions:
    out += '```\n' + i + '\n```\n\n' + i + '\n\n'

#from IPython import display
#display.display(display.Markdown(out))
print(out)
~~~
--->
<pre><code>\begin{equation}
y(x) = a x^2 + b x + c. \label{eq:quadratic_formula}
\end{equation}</code></pre>
<p><img src="https://latex.codecogs.com/png.latex?%5Cbegin%7Bequation%7D%0Ay(x)%20=%20a%20x%5E2%20+%20b%20x%20+%20c.%20%5Clabel%7Beq:quadratic_formula%7D%0A%5Cend%7Bequation%7D"></p>
<pre><code>\begin{multline}
y(x) = a x^2 \\
+ b x \\
+ c.
\end{multline}</code></pre>
<p><img src="https://latex.codecogs.com/png.latex?%5Cbegin%7Bmultline%7D%0Ay(x)%20=%20a%20x%5E2%20%5C%5C%0A+%20b%20x%20%5C%5C%0A+%20c.%0A%5Cend%7Bmultline%7D"></p>
<pre><code>\begin{align}
y &amp;= 2 + 3, \nonumber \\
  &amp;= 5. \label{eq:sum_result}
\end{align}</code></pre>
<p><img src="https://latex.codecogs.com/png.latex?%5Cbegin%7Balign%7D%0Ay%20&amp;=%202%20+%203,%20%5Cnonumber%20%5C%5C%0A%20%20&amp;=%205.%20%5Clabel%7Beq:sum_result%7D%0A%5Cend%7Balign%7D"></p>
<pre><code>\begin{align}
a &amp;= 1, &amp; b &amp;= 2,\\
c &amp;= 3, &amp; d &amp;= 4.
\end{align}</code></pre>
<p><img src="https://latex.codecogs.com/png.latex?%5Cbegin%7Balign*%7D%0Aa%20&amp;=%201,%20&amp;%20b%20&amp;=%202,%5C%5C%0Ac%20&amp;=%203,%20&amp;%20d%20&amp;=%204.%0A%5Cend%7Balign*%7D"></p>
<p>You may notice that the equation numbering in edit mode is always referred to the equations contained in a single cell. If you put several equations in a single markdown cell they will be numbered sequentially, but the moment you start another cell the counting resets. This is a bug which is not verified when you export the notebook as a pdf or as an HTML file. Equations may contain labels as <code>\label{eq:sum_result}</code> at the end of a line which help to automatically refer to these equations in the text. For instance, the quadratic formula is <img src="https://latex.codecogs.com/png.latex?%5Ceqref%7Beq:quadratic_formula%7D">, which can be referred to using <code>$\eqref{eq:quadratic_formula}$</code>. The result of <img src="https://latex.codecogs.com/png.latex?2+3"> is shown in Eq. <img src="https://latex.codecogs.com/png.latex?%5Ceqref%7Beq:sum_result%7D"> and can be dynamically referred in the text using <code>$\eqref{eq:sum_result}$</code>. This is very powerful, since it’s not necessary to keep track of these numbers when changing the document. Quite often there are some equations that we don’t want to number. The environments above lose their numbering by adding an asterisk after the environment name, as in <code>\begin{env*} your equation \end{env*}</code>. We can also remove the numbering of specific equations using <code>\nonumber</code>.</p>
<p>Each equation environment above is more adequate for specific types of equations. <code>equation</code> is adequate for single mathematical expressions that may fit a single line. Sometimes there are single expressions that are too long, such they can be split along several lines using <code>multline</code> for better visualization. Two bars <code>\\</code> are used to indicate where the line must break. The <code>align</code> environment is useful to exhibit several equations together. The expressions are aligned by <code>&amp;</code> symbols and the lines end at <code>\\</code>.</p>
<p>The syntax to write down matrices and vectors is similar to that used in <code>align</code>. Columns are divided by <code>&amp;</code> and the lines end at <code>\\</code>. The matrix is defined within it’s own environment inside an equation environment. See the example below.</p>
<pre><code>\begin{equation}
  M =
  \begin{bmatrix}
  a &amp; b \\
  c &amp; d
  \end{bmatrix}
\end{equation}</code></pre>
<p><img src="https://latex.codecogs.com/png.latex?%5Cbegin%7Bequation%7D%0A%20%20M%20=%0A%20%20%5Cbegin%7Bbmatrix%7D%0A%20%20a%20&amp;%20b%20%5C%5C%0A%20%20c%20&amp;%20d%0A%20%20%5Cend%7Bbmatrix%7D%0A%5Cend%7Bequation%7D"></p>
<p>There are several variations of the <code>matrix</code> environment, which are associated with the symbols used to enclose the matrix elements. The table below shows some examples.</p>
<!---
~~~{.python}
out = "| Matrix type | Result |\n"
out+= "|:-----------:|:------:|\n"

for i in ['matrix', 'pmatrix', 'bmatrix', 'Bmatrix']:
    mtrx_str = '''\\begin{%s} a & b \\\\ c & d \\end{%s}''' % (i, i)
    out += "| `%s` | $%s$ |\n" % (i, mtrx_str)

#from IPython import display
#display.display(display.Markdown(out))
print(out)
~~~
--->
<table class="caption-top table">
<thead>
<tr class="header">
<th style="text-align: center;">Matrix type</th>
<th style="text-align: center;">Result</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: center;"><code>matrix</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cbegin%7Bmatrix%7D%20a%20&amp;%20b%20%5C%5C%20c%20&amp;%20d%20%5Cend%7Bmatrix%7D"></td>
</tr>
<tr class="even">
<td style="text-align: center;"><code>pmatrix</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cbegin%7Bpmatrix%7D%20a%20&amp;%20b%20%5C%5C%20c%20&amp;%20d%20%5Cend%7Bpmatrix%7D"></td>
</tr>
<tr class="odd">
<td style="text-align: center;"><code>bmatrix</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cbegin%7Bbmatrix%7D%20a%20&amp;%20b%20%5C%5C%20c%20&amp;%20d%20%5Cend%7Bbmatrix%7D"></td>
</tr>
<tr class="even">
<td style="text-align: center;"><code>Bmatrix</code></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cbegin%7BBmatrix%7D%20a%20&amp;%20b%20%5C%5C%20c%20&amp;%20d%20%5Cend%7BBmatrix%7D"></td>
</tr>
</tbody>
</table>
<p>The <code>matrix</code> is useful to express conditional equations, as</p>
<pre><code>\begin{equation}
\Theta(x) =
\left\{
  \begin{matrix}
  0\text{, if } x&lt;0 \\
  1\text{, if } x&gt;0
  \end{matrix}
\right.
\end{equation}</code></pre>
<p><img src="https://latex.codecogs.com/png.latex?%5Cbegin%7Bequation%7D%0A%5CTheta(x)%20=%0A%5Cleft%5C%7B%0A%20%20%5Cbegin%7Bmatrix%7D%0A%20%200%5Ctext%7B,%20if%20%7D%20x%3C0%20%5C%5C%0A%20%201%5Ctext%7B,%20if%20%7D%20x%3E0%0A%20%20%5Cend%7Bmatrix%7D%0A%5Cright.%0A%5Cend%7Bequation%7D"></p>
<p>It can also be used to express vectors, as in</p>
<pre><code>\begin{equation}
    \begin{pmatrix}
    a_1 \\
    a_2 \\
    \vdots \\
    a_n
    \end{pmatrix}
    =
    \begin{pmatrix}
    c_{11} &amp; c_{12} &amp; \dots &amp; c_{1n} \\
    c_{21} &amp; c_{22} &amp; \dots &amp; c_{1n} \\
    \vdots &amp; \ddots &amp;       &amp; \vdots \\
    c_{n1} &amp; c_{n2} &amp; \dots &amp; c_{nn} \\
    \end{pmatrix}
    \begin{pmatrix}
    b_1 \\
    b_2 \\
    \vdots \\
    b_n
    \end{pmatrix}    
\end{equation}</code></pre>
<p><img src="https://latex.codecogs.com/png.latex?%5Cbegin%7Bequation%7D%0A%20%20%20%20%5Cbegin%7Bpmatrix%7D%0A%20%20%20%20a_1%20%5C%5C%0A%20%20%20%20a_2%20%5C%5C%0A%20%20%20%20%5Cvdots%20%5C%5C%0A%20%20%20%20a_n%0A%20%20%20%20%5Cend%7Bpmatrix%7D%0A%20%20%20%20=%0A%20%20%20%20%5Cbegin%7Bpmatrix%7D%0A%20%20%20%20c_%7B11%7D%20&amp;%20c_%7B12%7D%20&amp;%20%5Cdots%20&amp;%20c_%7B1n%7D%20%5C%5C%0A%20%20%20%20c_%7B21%7D%20&amp;%20c_%7B22%7D%20&amp;%20%5Cdots%20&amp;%20c_%7B1n%7D%20%5C%5C%0A%20%20%20%20%5Cvdots%20&amp;%20%5Cddots%20&amp;%20%20%20%20%20%20%20&amp;%20%5Cvdots%20%5C%5C%0A%20%20%20%20c_%7Bn1%7D%20&amp;%20c_%7Bn2%7D%20&amp;%20%5Cdots%20&amp;%20c_%7Bnn%7D%20%5C%5C%0A%20%20%20%20%5Cend%7Bpmatrix%7D%0A%20%20%20%20%5Cbegin%7Bpmatrix%7D%0A%20%20%20%20b_1%20%5C%5C%0A%20%20%20%20b_2%20%5C%5C%0A%20%20%20%20%5Cvdots%20%5C%5C%0A%20%20%20%20b_n%0A%20%20%20%20%5Cend%7Bpmatrix%7D%20%20%20%20%0A%5Cend%7Bequation%7D"></p>
</section>
<section id="citations-and-internal-references" class="level3">
<h3 class="anchored" data-anchor-id="citations-and-internal-references">Citations and internal references</h3>
<p>Jupyter notebook currently does not natively support references to sections and figures, such that it is not practical to write complex documents in it without extensions. Below there are some suggestions on what can be done.</p>
<ul>
<li>For simple documents, the citations and references can be handled manually</li>
<li>The <a href="https://github.com/takluyver/cite2c">cite2c extension</a> allows to use Zotero references to perform literature citations. This is a solution for documents that does not require complex internal references to figures, tables and etc.</li>
<li>The notebook can be used to compose the skeleton of the final document and later be exported to a <code>.tex</code> file. This export procedure will handle figure exports and mathematical expressions. Therefore, the document still must go through a final stage using a distribution such as MiKTeX.</li>
<li><a href="pandoc.org">Pandoc</a> is a document converter that support several formats, it’s native syntax being a markdown flavor. It is possible to use the notebook in a <a href="https://stackoverflow.com/questions/30061902/how-to-handle-citations-in-ipython-notebook">Pandoc based workflow</a>. For example, it’s possible to use python to automate the conversion, or export the notebook to later perform the final adjustments directly using Pandoc.</li>
</ul>
<p>As a final remark, the Jupyter notebook has an internal tool called <code>nbconvert</code> which is used to convert the notebook file to several formats. <code>nbconvert</code> supports templating, such once you can tune the conversion process to make your workflow easier.</p>
<!---

Adicionar workflow para usar o pandoc? Acho que o anaconda instala o pandoc automaticamente... WinPython também!! Vale a pena fazer isso para customizar a saída do template

--->


</section>
</section>
</section>

 ]]></description>
  <category>python</category>
  <category>experimental physics</category>
  <category>data analysis</category>
  <guid>https://amamaral.github.io/blog/posts/python-for-experimental-sciences-2/</guid>
  <pubDate>Sat, 10 Apr 2021 00:00:00 GMT</pubDate>
  <media:content url="https://amamaral.github.io/blog/assets/pes_pos_scatter_plot.png" medium="image" type="image/png" height="96" width="144"/>
</item>
<item>
  <title>Image conversion from cartesian to cylindrical coordinates</title>
  <dc:creator>Anderson M. Amaral</dc:creator>
  <link>https://amamaral.github.io/blog/posts/image-conversion-cartesian-cylindrical/</link>
  <description><![CDATA[ 




<section id="introduction" class="level1">
<h1>Introduction</h1>
<p>Suppose that one has some picture of a cylindrical structure, as for example a Gaussian light beam or Laguerre-Gauss laser modes. How to convert the image from <img src="https://latex.codecogs.com/png.latex?xy"> cartesian coordinates to <img src="https://latex.codecogs.com/png.latex?r%5Ctheta"> cylindrical coordinates? This is particularly important if the pattern does not have azimuthal symmetry and rotates. How to determine the rotation angle?</p>
<p>Consider the light beam below, produced which can be understood as the interference between two LG modes. How to perform the coordinate transformation in a numerically efficient way using Python?</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://amamaral.github.io/blog/assets/xy_rphi_initialproblem.png" class="img-fluid figure-img"></p>
<figcaption>Problem definition</figcaption>
</figure>
</div>
<div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>pylab inline</span>
<span id="cb1-2">xx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> linspace(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>)</span>
<span id="cb1-3">yy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> linspace(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>)</span>
<span id="cb1-4"></span>
<span id="cb1-5">x, y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> meshgrid(xx,yy)</span>
<span id="cb1-6">v <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">1j</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> y</span>
<span id="cb1-7">r <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">abs</span>(v)</span>
<span id="cb1-8">phi <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> angle(v)</span>
<span id="cb1-9"></span>
<span id="cb1-10">offset <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> deg2rad(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb1-11">m <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span></span>
<span id="cb1-12">nbins <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># If this is too large, some distortion in the angle due to pixelation</span></span>
<span id="cb1-13"></span>
<span id="cb1-14">profile <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>  r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>m <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> cos(m<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>(theta<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>phi)) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> exp(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb1-15"></span>
<span id="cb1-16">rr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>,nbins)</span>
<span id="cb1-17">pphi <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> linspace(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>pi,pi,nbins)</span>
<span id="cb1-18">Phi, R <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> meshgrid(pphi, rr)</span>
<span id="cb1-19">profile_r_phi <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> R<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>m <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> cos(m<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>(Phi<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>offset)) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> exp(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>R<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb1-20"></span>
<span id="cb1-21">subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">121</span>)</span>
<span id="cb1-22">title(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'$I(x,y)$'</span>)</span>
<span id="cb1-23"></span>
<span id="cb1-24">dx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (xx[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>xx[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb1-25">dy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (yy[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>yy[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb1-26">extent_xy<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[xx[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>dx, xx[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>dx, yy[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>dy, yy[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>dy]</span>
<span id="cb1-27"></span>
<span id="cb1-28">imshow(absolute(profile)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, origin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'lower'</span>, extent<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>extent_xy)</span>
<span id="cb1-29">subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">122</span>)</span>
<span id="cb1-30"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#im = imshow(angle(profile), cmap=cm.gray)</span></span>
<span id="cb1-31"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#colorbar(im)</span></span>
<span id="cb1-32">title(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'$I(r,\phi)$'</span>)</span>
<span id="cb1-33"></span>
<span id="cb1-34">imshow(absolute(profile_r_phi)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, origin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'lower'</span>)</span>
<span id="cb1-35">xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"$</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\\</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">phi$"</span>)</span>
<span id="cb1-36">ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"r"</span>)</span>
<span id="cb1-37"></span>
<span id="cb1-38">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"assets\xy_rphi_initialproblem.png"</span>)</span></code></pre></div>
</section>
<section id="radial-dependence" class="level1">
<h1>Radial dependence</h1>
<p>Suppose we want to find <img src="https://latex.codecogs.com/png.latex?I(r)">. How do we do this, given that we know <img src="https://latex.codecogs.com/png.latex?I(x,y)">? We can build a map that indicates the coordinate of each pixel in the coordinate system of interest, as performed above for <code>x,y,r,phi</code>. We can use histograms to verify how frequent each value of <code>r,phi</code> appears in the image. Below we have the histogram of <code>r</code> in an array whose size is the same as <code>profile</code>. Notice that the growth is linear with <code>r</code> until the corners of the array are reached at <img src="https://latex.codecogs.com/png.latex?r=5">. Resembles, at least slightly, the Jacobian of the coordinate transformation. Suppose now that the histogram of <img src="https://latex.codecogs.com/png.latex?r"> is weighted by the intensity profile, could this be equivalent to the coordinate transformation?</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://amamaral.github.io/blog/assets/xy_rphi_radial_histogram.png" class="img-fluid figure-img"></p>
<figcaption>Using histograms for coordinate transformation</figcaption>
</figure>
</div>
<div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1">h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> histogram(r, bins<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>nbins, weights<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>absolute(profile)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb2-2">hx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> h[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>][:<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb2-3">hy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> h[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb2-4"></span>
<span id="cb2-5">h2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> histogram(r, bins<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>nbins)</span>
<span id="cb2-6"></span>
<span id="cb2-7">subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">211</span>)</span>
<span id="cb2-8">title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'num of array elems with given r values'</span>)</span>
<span id="cb2-9">plot(hx, h2[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'k.'</span>)</span>
<span id="cb2-10"></span>
<span id="cb2-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Notice that the frequency of r[i] is proportional to r. Jacobian?</span></span>
<span id="cb2-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># It is necessary to normalize by h2!</span></span>
<span id="cb2-13"></span>
<span id="cb2-14">subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">212</span>)</span>
<span id="cb2-15">title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'intensity vs radius?'</span>)</span>
<span id="cb2-16">plot(hx, hy, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'k.'</span>)</span>
<span id="cb2-17"></span>
<span id="cb2-18">tight_layout()</span>
<span id="cb2-19"></span>
<span id="cb2-20">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"assets\xy_rphi_radial_histogram.png"</span>)</span></code></pre></div>
<p>It’s very close indeed, however it is necessary to normalize by the number of pixels whose radius is <code>r</code>. Below this correction is performed and the theory and numerical conversion are compared. Notice the perfect matching, which indicates the present procedure is adequate.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://amamaral.github.io/blog/assets/xy_rphi_radial_histogram_2.png" class="img-fluid figure-img"></p>
<figcaption>Radial expression for the intensity using histograms</figcaption>
</figure>
</div>
<div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'avg intensity vs radius'</span>)</span>
<span id="cb3-2"></span>
<span id="cb3-3">h1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> histogram(r, bins<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>nbins, weights<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>absolute(profile)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb3-4">h2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> histogram(r, bins<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>nbins)</span>
<span id="cb3-5"></span>
<span id="cb3-6">hx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> h1[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>][:<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb3-7">hy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> h1[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>h2[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb3-8"></span>
<span id="cb3-9">factor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> m<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb3-10"></span>
<span id="cb3-11">plot(hx, hy, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'k.'</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'histogram transformation'</span>)</span>
<span id="cb3-12">plot(hx, hx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>m) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> exp(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>hx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>factor, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'theory'</span>)</span>
<span id="cb3-13">legend(loc<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb3-14">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"assets\xy_rphi_radial_histogram_2.png"</span>)</span></code></pre></div>
</section>
<section id="angular-dependence" class="level1">
<h1>Angular dependence</h1>
<p>To obtain the angular dependence is similar, however some extra care must be taken. Consider the histogram of <code>phi</code>, weighted by <code>1</code> or the intensity profiles. Notice that while the radial distortion is due to pixels close to the image borders, in the azimuthal direction there are more pixels along certain directions (diagonals). This is important to notice because the contribution due to some angles can be disproportionate. Also, close to <img src="https://latex.codecogs.com/png.latex?r=0">, some angles may be unavailable due to pixelation.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://amamaral.github.io/blog/assets/xy_rphi_angular_histogram.png" class="img-fluid figure-img"></p>
<figcaption>Obtaining <img src="https://latex.codecogs.com/png.latex?I(%5Ctheta)"></figcaption>
</figure>
</div>
<div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1">h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> histogram(phi, bins<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>nbins, weights<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>absolute(profile)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb4-2">hx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> h[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>][:<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">180</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>pi</span>
<span id="cb4-3">hy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> h[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb4-4"></span>
<span id="cb4-5">h2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> histogram(phi, bins<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>nbins)</span>
<span id="cb4-6"></span>
<span id="cb4-7">subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">211</span>)</span>
<span id="cb4-8">plot(hx, h2[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'k.'</span>)</span>
<span id="cb4-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Notice the distortion at the most frequent phi values</span></span>
<span id="cb4-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># The most frequent phi values are at the diagonals</span></span>
<span id="cb4-11"></span>
<span id="cb4-12">subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">212</span>)</span>
<span id="cb4-13">title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'intensity vs angle?'</span>)</span>
<span id="cb4-14">plot(hx, hy, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'k.'</span>)</span>
<span id="cb4-15"></span>
<span id="cb4-16">tight_layout()</span>
<span id="cb4-17">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"assets\xy_rphi_angular_histogram.png"</span>)</span></code></pre></div>
<p>If the histogram is normalized as before, there will be some distortion due to the diagonals. To avoid this, we filter the image radially and obtain the following result is obtained. Notice how the numerical transformation nicely matches the theoretically expected result.</p>
<p><img src="https://amamaral.github.io/blog/assets/xy_rphi_angular_histogram_2.png" class="img-fluid"></p>
<div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1">title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'intensity vs angle at given radius'</span>)</span>
<span id="cb5-2"></span>
<span id="cb5-3">rad <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sqrt(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>m)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb5-4">width <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># If this is too large, some distortion appear due to the frame edges and pixelation</span></span>
<span id="cb5-5">mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> rad<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>width<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (r <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> rad<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>width<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb5-6"></span>
<span id="cb5-7">h1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> histogram(phi, bins<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>nbins, weights<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>absolute(profile)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> mask)</span>
<span id="cb5-8">h2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> histogram(phi, bins<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>nbins, weights<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>mask)</span>
<span id="cb5-9">hx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> h1[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>][:<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">180</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>pi</span>
<span id="cb5-10">hy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> h1[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>h2[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb5-11"></span>
<span id="cb5-12">plot(hx, hy, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'k.'</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Numerical transformation'</span>)</span>
<span id="cb5-13"></span>
<span id="cb5-14">ampl <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> rad<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>m) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> exp(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>rad<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb5-15">plot(hx, ampl<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>cos(m <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (pi<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>hx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">180</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> offset))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Theory'</span>)</span>
<span id="cb5-16"></span>
<span id="cb5-17">legend(loc<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb5-18">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"assets\xy_rphi_angular_histogram_2.png"</span>)</span></code></pre></div>
</section>
<section id="radial-and-angular-dependence" class="level1">
<h1>Radial and angular dependence</h1>
<p>Since the above considerations allowed to obtain the intensity vs radius or intensity vs angle, would it be possible to obtain intensity as a function of radius and angle? We can use 2d histograms to obtain this transformation, analogously to the previous cases. Some distinctions are important here. <code>histogram2d()</code> does not accept <code>r, phi</code> and <code>profile</code> as 2d arrays, such <code>ravel()</code> is used to convert these matrices to 1D ndarrays. Also, close to <code>r=0</code> there will be several angles which cannot be found, such the normalization will be undefined. In such cases it could be possible to interpolate the data between well defined values. Notice that this is not a limitation of the present procedure, but an unavoidable issue in such transformation. Some pairs of <code>r, phi</code> do not exist, and therefore the method cannot infer these values automatically. Numpy assigns <code>nan</code> to these values and <code>imshow</code> exhibits these pixels in white. It is also important to notice that here it is important to limit the extent of <img src="https://latex.codecogs.com/png.latex?r"> values, otherwise the corners will be included and artifacts introduced in the <img src="https://latex.codecogs.com/png.latex?r%5Ctheta"> representation.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://amamaral.github.io/blog/assets/xy_rphi_transform.png" class="img-fluid figure-img"></p>
<figcaption>Output of the 2D transformation</figcaption>
</figure>
</div>
<div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1">title(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'$I(r,\theta)$'</span>)</span>
<span id="cb6-2">data_range <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>], [<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>pi,pi]]</span>
<span id="cb6-3">h1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> histogram2d(r.ravel(), phi.ravel(), bins<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>nbins, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>data_range, weights<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(absolute(profile)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>).ravel())</span>
<span id="cb6-4">h2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> histogram2d(r.ravel(), phi.ravel(), bins<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>nbins, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>data_range)</span>
<span id="cb6-5"></span>
<span id="cb6-6">im <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> imshow(h1[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>h2[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], origin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'lower'</span>)</span>
<span id="cb6-7">colorbar(im)</span>
<span id="cb6-8"></span>
<span id="cb6-9">xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"$</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\\</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">theta$"</span>)</span>
<span id="cb6-10">ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"r"</span>)</span>
<span id="cb6-11"></span>
<span id="cb6-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># The present approach has errors close to r=0, since there will not be pixels with some values of theta</span></span>
<span id="cb6-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Interpolation is necessary to fill out the gaps where h2[0]==0 close to r=0.</span></span>
<span id="cb6-14"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># The number of gaps reduces with the number of bins</span></span>
<span id="cb6-15"></span>
<span id="cb6-16">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"assets\xy_rphi_transform.png"</span>)</span></code></pre></div>
<p>We can also put the theoretically expected profile and the result of the numerical transformation side by side to see that the transformation is meaningful. Both patterns are very similar.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://amamaral.github.io/blog/assets/xy_rphi_side_by_side.png" class="img-fluid figure-img"></p>
<figcaption>Theoretical and numerically transformed patterns are identical</figcaption>
</figure>
</div>
<div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1">subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">121</span>)</span>
<span id="cb7-2">title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Theoretical'</span>)</span>
<span id="cb7-3">im <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> imshow(absolute(profile_r_phi)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, origin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'lower'</span>, cmap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>im.cmap)</span>
<span id="cb7-4">xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"$</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\\</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">phi$"</span>)</span>
<span id="cb7-5">ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"r"</span>)</span>
<span id="cb7-6"></span>
<span id="cb7-7">subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">122</span>)</span>
<span id="cb7-8">title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Transf. result'</span>)</span>
<span id="cb7-9"></span>
<span id="cb7-10">imshow(h1[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>h2[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], origin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'lower'</span>, cmap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>im.cmap)</span>
<span id="cb7-11">xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"$</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\\</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">phi$"</span>)</span>
<span id="cb7-12">ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"r"</span>)</span>
<span id="cb7-13"></span>
<span id="cb7-14">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"assets\xy_rphi_side_by_side.png"</span>)</span></code></pre></div>
<p>The difference between both patterns above is also very small, as it can be seen from the image below.</p>
<p><img src="https://amamaral.github.io/blog/assets/xy_rphi_difference.png" class="img-fluid"></p>
<div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1">title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Difference (Th-Tr)'</span>)</span>
<span id="cb8-2">delta <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> absolute(absolute(profile_r_phi)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> h1[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>h2[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb8-3">im <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> imshow(delta, origin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'lower'</span>)</span>
<span id="cb8-4">colorbar(im)</span>
<span id="cb8-5">xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"$</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\\</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">phi$"</span>)</span>
<span id="cb8-6">ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"r"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-7">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"assets\xy_rphi_difference.png"</span>)</span></code></pre></div>


</section>

 ]]></description>
  <category>optics</category>
  <category>python</category>
  <guid>https://amamaral.github.io/blog/posts/image-conversion-cartesian-cylindrical/</guid>
  <pubDate>Thu, 25 Jun 2020 00:00:00 GMT</pubDate>
  <media:content url="https://amamaral.github.io/blog/assets/xy_rphi_initialproblem.png" medium="image" type="image/png" height="96" width="144"/>
</item>
<item>
  <title>Instalando o arduino, python e outros pacotes adicionais</title>
  <dc:creator>Anderson M. Amaral</dc:creator>
  <link>https://amamaral.github.io/blog/posts/instalando-arduino-e-python/</link>
  <description><![CDATA[ 




<section id="guia-básico-dos-programas-necessários-para-sensoriamento-e-controle" class="level1">
<h1>Guia básico dos programas necessários para Sensoriamento e controle</h1>
<p>Utilizaremos diversos programas ao longo da disciplina, bem como várias bibliotecas adicionais. Abaixo segue um breve resumo dos passos que você deve adotar para que possa fazer estas atividades em casa ou de pesquisa. As instruções abaixo são para sistemas Windows, mas no caso do Linux a ideia geral é bem parecida.</p>
</section>
<section id="arduino-e-suas-bibliotecas" class="level1">
<h1>Arduino e suas bibliotecas</h1>
<p>Antes de mais nada, é fundamental que a IDE do arduino esteja instalada. Acesse <a href="http://www.arduino.cc" class="uri">http://www.arduino.cc</a> e faça o download e a instalação do programa, seguindo as instruções recomendadas para o seu sistema operacional.</p>
<p><strong>Nota para usuários de sistemas linux</strong>. A instalação da IDE arduino por vezes não permite a comunicação com a placa diretamente. É necessário acessar o terminal e digitar <code>sudo usermod -a -G dialout &lt;username&gt;</code>, onde <code>&lt;username&gt;</code> deverá ser substituído pelo nome da conta de usuário que terá autorização para programar e se comunicar com o arduino. Após a autorização é necessário reiniciar o sistema.</p>
<p>Faça o teste básico do led piscando <code>Arquivo&gt;Exemplos&gt;01. Basics&gt;Blink</code> para verificar se tudo está funcionando corretamente. O próximo passo é instalar as bibliotecas que precisaremos para controlar alguns sensores e periféricos. Na IDE arduino, acesse o menu <code>Sketch&gt;Incluir bibliotecas&gt;Gerenciar bibliotecas</code>. Busque e instale as bibliotecas abaixo:</p>
<ul>
<li>Wire</li>
<li>Adafruit Unified Sensor Library</li>
<li>DHT sensor library</li>
<li>LiquidCrystal I2C</li>
<li>IRremote</li>
<li>RF24</li>
</ul>
<section id="instalação-do-python-e-bibliotecas-adicionais-no-windows" class="level2">
<h2 class="anchored" data-anchor-id="instalação-do-python-e-bibliotecas-adicionais-no-windows">Instalação do Python e bibliotecas adicionais no Windows</h2>
<p>Os passos abaixo são recomendados para quem não possui nenhuma versão anterior do Python instalada na máquina. A instalação das bibliotecas abaixo pode ser feita de forma similar em sistemas Linux ao utilizar o terminal. Além de instalar os aplicativos abaixo, recomendo também que leiam o <a href="https://hplgit.github.io/primer.html/doc/pub/half/book.pdf">excelente livro gratuito sobre programação em Python do Hans Petter Langtangen, A Primer on Scientific Programming with Python</a></p>
<section id="anaconda" class="level3">
<h3 class="anchored" data-anchor-id="anaconda">Anaconda</h3>
<p>O Anaconda é um pacote de Python que contém não apenas as funcionalidades básicas da linguagem, como diversas bibliotecas acessórias já pré-configuradas.</p>
<ul>
<li>Acessar <a href="http://www.anaconda.com" class="uri">http://www.anaconda.com</a> e efetuar o download da versão mais recente (Python 3, 64 bits)</li>
<li>Durante a instalação, adicione o anaconda ao PATH e escolha como Python padrão do sistema</li>
</ul>
</section>
<section id="pyserial-e-kivy" class="level3">
<h3 class="anchored" data-anchor-id="pyserial-e-kivy">PySerial e kivy</h3>
<p>Além das bibliotecas já instaladas no Anaconda, precisaremos também de duas bibliotecas adicionais. A PySerial permite a comunicação com o arduino via serial, de forma similar ao Monitor Serial da IDE arduino. Existem outras bibliotecas mais poderosas e que permitem a comunicação com mais instrumentos, como as bibliotecas PyVisa ou Instrumental. Entretanto a PySerial é suficiente para as nossas aplicações. Para produzir interfaces gráficas no python, e ter um programa com aparência mais “profissional” para controlar nossos instrumentos, utilizaremos a biblioteca kivy.</p>
<ul>
<li>No menu iniciar, procure por <code>Anaconda PowerShell Prompt</code> ou <code>Anaconda Prompt</code>.</li>
<li>No console, execute os comandos abaixo:
<ul>
<li><code>conda install -c anaconda pyserial</code></li>
<li><code>conda install -c conda-forge kivy</code></li>
</ul></li>
</ul>


</section>
</section>
</section>

 ]]></description>
  <category>arduino</category>
  <category>python</category>
  <category>kivy</category>
  <guid>https://amamaral.github.io/blog/posts/instalando-arduino-e-python/</guid>
  <pubDate>Wed, 21 Aug 2019 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Transimpedance amplifiers — application in optical sensing with photodiodes</title>
  <dc:creator>Anderson M. Amaral</dc:creator>
  <link>https://amamaral.github.io/blog/posts/transimpedance-amplifiers/</link>
  <description><![CDATA[ 




<p>In usual optical detectors a given flux of photons (the quantum of the electromagnetic field) are directly converted into a flux of electrons (quantum of electrical current). An associated practical problem is that our measurement instruments are often more appropriate to measure voltage, instead of currents. A transimpedance amplifier is a configuration which converts a current into a (possibly large) voltage with the help of an amplifier.</p>
<section id="a-brief-recapitulation-of-amplifiers-nomenclature" class="level1">
<h1>A brief recapitulation of amplifiers nomenclature</h1>
<p>An amplifier is a device that receives some signal (current or voltage) at its input and outputs another signal (also a current or voltage). There are then 4 possible configurations. Suppose that at the input one has a voltage signal <img src="https://latex.codecogs.com/png.latex?V_%7Bin%7D">, and the output is another voltage <img src="https://latex.codecogs.com/png.latex?V_%7Bout%7D">. This amplifier can be characterized by its voltage gain <img src="https://latex.codecogs.com/png.latex?A_v%20=%20%5Cfrac%7BV_%7Bout%7D%7D%7BV_%7Bin%7D%7D">. For an amplifier which inputs and outputs currents, we also can characterize the current gain as <img src="https://latex.codecogs.com/png.latex?A_i%20=%20%5Cfrac%7BI_%7Bout%7D%7D%7BI_%7Bin%7D%7D">. Notice that <img src="https://latex.codecogs.com/png.latex?A_v"> and <img src="https://latex.codecogs.com/png.latex?A_i"> are unitless quantities. Now, if an amplifier accepts a current as an input and outputs a voltage, we can’t characterize any gain in terms of an unitless quantity. To remain the gain characterization in terms of signal out/signal in, we must have <img src="https://latex.codecogs.com/png.latex?Z_%7Bamp%7D=%5Cfrac%7BV_%7Bout%7D%7D%7BI_%7Bin%7D%7D">, which has units of Ohms. For a constant, DC signal, <img src="https://latex.codecogs.com/png.latex?Z_%7Bamp%7D"> would be a resistance, while in general for time varying signals <img src="https://latex.codecogs.com/png.latex?Z_%7Bamp%7D"> is called an impedance. Equivalently, if an amplifier has an input voltage and outputs a current, it’s called a transconductance amplifier, due to its gain <img src="https://latex.codecogs.com/png.latex?G_%7Bamp%7D=%5Cfrac%7BI_%7Bout%7D%7D%7BV_%7Bin%7D%7D"> (expressed in Siemens, or <img src="https://latex.codecogs.com/png.latex?%5COmega%5E%7B-1%7D">)</p>
</section>
<section id="design-of-a-transimpedance-amplifier" class="level1">
<h1>Design of a transimpedance amplifier</h1>
<section id="some-characteristics-of-photodiodes" class="level2">
<h2 class="anchored" data-anchor-id="some-characteristics-of-photodiodes">Some characteristics of photodiodes</h2>
<p>Here we will comment some physical aspects of sensing light with photodiodes. At the end of this section there are some photodiode typical characteristics and the circuit design starts in the following section.</p>
<section id="currents-in-a-photodiode" class="level3">
<h3 class="anchored" data-anchor-id="currents-in-a-photodiode">Currents in a photodiode</h3>
<p>A photodiode is mainly characterized by the PN junction, which is an interface between positively (P) and negatively (N) doped semiconductors. Because of the spatial distribution of dopants at such interface, there is intrinsic tendency of charges to flow (diffusion process) from the P-doped region to the N-doped region and vice-versa. However, this spatial charge diffusion must cease for a PN junction in equilibrium, where there is no external input power.</p>
<p>The spatial charge diffusion means that close to the PN junction there are some negative charges at the P-doped region, while there are also positive charges at the N-doped region. The electric field established after the charge redistribution must be such that no extra charges can flow through the junction. In other words, the field must establish a barrier to the charge flow, and is oriented from the N-region to the P-region.</p>
<p>Considering the PN junction in equilibrium, there are basically two ways to conduct an electric current across this junction:</p>
<ol type="1">
<li>Increase (decrease) the electric potential at the P(N)-doped region. The extra energy can be used to overcome the barrier after some threshold, and an electric current may occur. <strong>The current flows the P-doped to the N-doped region</strong>.</li>
<li>If a photon hits the semiconductor, it may transfer it’s total energy to a charge carrier (either an electron or a hole). If these charge carriers are produced in the PN junction, they will be accelerated by the existing field due to the diffused spatial charges. <strong>The current flows the N-doped to the P-doped region</strong>. This current is also called <strong>reverse current</strong>.</li>
</ol>
<p>The current associated with a voltage <img src="https://latex.codecogs.com/png.latex?V_D"> across the diode terminals is well approximated by the <a href="https://en.wikipedia.org/wiki/Shockley_diode_equation">Shockley diode equation</a>: <img src="https://latex.codecogs.com/png.latex?I(V_D)%20=%20I_D%20%5Cleft(e%5E%7BV_D/V_T%7D-1%5Cright)"> <img src="https://latex.codecogs.com/png.latex?I_D"> is the dark, or saturation current, and <img src="https://latex.codecogs.com/png.latex?V_T=kT/q"> for an ideal diode (<img src="https://latex.codecogs.com/png.latex?k"> is the Boltzmann constant, <img src="https://latex.codecogs.com/png.latex?T"> the temperature and <img src="https://latex.codecogs.com/png.latex?q"> is the electrical charge). The dark current depends on several parameters as doping, temperature and PN junction area, such that it’s a parameter that varies significantly from diode to diode.</p>
<p>The total current across a diode includes also the reverse current, and can be expressed as</p>
<p><img src="https://latex.codecogs.com/png.latex?I%20=%20I_D%20%5Cleft(e%5E%7BV_D/V_T%7D-1%5Cright)%20-%20I_%7Brev%7D"></p>
<p>We could also include other contributions to the current, as those due to thermal noise, shot noise and 1/f noise. For these contributions, see for example this <a href="https://sensing.honeywell.com/index.php?ci_id=138865&amp;la_id=1">Honeywell’s Application Note on Photodiodes</a>.</p>
<p>Under zero voltage bias (<img src="https://latex.codecogs.com/png.latex?V_D=0">), one has that <img src="https://latex.codecogs.com/png.latex?I=-I_%7Brev%7D"> and only the photogenerated current is relevant. Thus, photodiodes are very useful to measure light. How can we relate <img src="https://latex.codecogs.com/png.latex?I_%7Brev%7D"> to the properties of the electromagnetic field?</p>
</section>
<section id="photogenerated-current" class="level3">
<h3 class="anchored" data-anchor-id="photogenerated-current">Photogenerated current</h3>
<p>Suppose that <img src="https://latex.codecogs.com/png.latex?N"> photons/s are impinging the photodiode active surface. If all photons are used by charge carriers to produce a current, then <img src="https://latex.codecogs.com/png.latex?I_%7Brev%7D=qN">. However, this photon-flux to electron-flux conversion process cannot occur with 100% of efficiency due to several reasons, as surface reflection of photons at the photodiode surface and carrier recombination in the semiconductor. To consider the imperfections, we introduce the quantum efficiency <img src="https://latex.codecogs.com/png.latex?%5Ceta">, and define <img src="https://latex.codecogs.com/png.latex?I_%7Brev%7D%20=%20%5Ceta%20q%20N"></p>
<p>Often we are not directly interested in the number of photons/s, given that it’s difficult to work in the quantum optics regime. It’s more usual to be interested in the relation between the optical power to the generated current. The energy per photon is <img src="https://latex.codecogs.com/png.latex?E=%5Cfrac%7Bhc%7D%7B%5Clambda%7D=%5Cfrac%7B1240%5Ctext%7B%20eV.nm%7D%7D%7B%5Clambda%7D">, and <img src="https://latex.codecogs.com/png.latex?N"> photons/s impinge the photodiode. Thus, the relation between current and power can be expressed through the <strong>Responsivity</strong> <img src="https://latex.codecogs.com/png.latex?%5Ctext%7BResp%7D(%5Clambda)%20=%20%5Ceta%20%5Cfrac%7B%5Clambda%7D%7B1240%5Ctext%7B%20nm%7D%7D%20%5Ctext%7B%20A/W%7D"></p>
<p>Thus for a monochromatic source, one has that <img src="https://latex.codecogs.com/png.latex?I_%7Brev%7D=%20R%20P">. If the light source has a known power spectrum <img src="https://latex.codecogs.com/png.latex?P(%5Clambda)"> and <img src="https://latex.codecogs.com/png.latex?%5Ctext%7BResp%7D(%5Clambda)"> is also known, then <img src="https://latex.codecogs.com/png.latex?I_%7Brev%7D=%20%5Cint%20P(%5Clambda)%20%5Cleft%7C%5Cfrac%7Bd%5Ctext%7BResp%7D(%5Clambda)%7D%7Bd%5Clambda%7D%5Cright%7C%20d%5Clambda">.</p>
<p>The responsivity does not grow indefinitely with <img src="https://latex.codecogs.com/png.latex?%5Clambda">. Indeed, light can efficiently excite single carriers only at wavelengths larger than the material’s bandgap. For silicon at ambient temperature, that means wavelengths around <img src="https://latex.codecogs.com/png.latex?1100%5Ctext%7B%20nm%7D">. Thus, the typical responsivity is a curve like the one below. Notice that photodiodes as the FDS100 or BPW34 can reach responsivities quite close to the ideal case (<img src="https://latex.codecogs.com/png.latex?%5Ceta=1">) in the near infrared, while the overall quantum efficiency reduces at smaller wavelengths.</p>
<div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>pylab inline</span>
<span id="cb1-2"></span>
<span id="cb1-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Represent the ideal photodiode response</span></span>
<span id="cb1-4">wavelengths <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">350</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1150</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># UV to near IR</span></span>
<span id="cb1-5">bandgap <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1100</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Silicon bandgap at room temperature</span></span>
<span id="cb1-6">responsivity <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> wavelengths<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1240</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Ideal case responsivity</span></span>
<span id="cb1-7">responsivity[wavelengths<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>bandgap] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> zeros(wavelengths.shape)[wavelengths<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>bandgap]</span>
<span id="cb1-8"></span>
<span id="cb1-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Consider the data for Thorlabs's FDS100 and BPW34 as a comparison</span></span>
<span id="cb1-10">fds100 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> loadtxt(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'assets\TIA_FDS100_Responsivity_data.csv'</span>, skiprows<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, unpack<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb1-11"></span>
<span id="cb1-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Data retrieved directly from the datasheet using the getdata graph digitizer</span></span>
<span id="cb1-13">bpw34 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> loadtxt(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'assets\TIA_bpw34_spectral_response.csv'</span>, unpack<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb1-14">i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> absolute(bpw34[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">950</span>).argmin() <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Which index corresponds to 950 nm?</span></span>
<span id="cb1-15">bpw34[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> bpw34[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.66</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> bpw34[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,i] <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Adjust the normalized response by the responsivity</span></span>
<span id="cb1-16"></span>
<span id="cb1-17">plot(wavelengths,responsivity, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Ideal case"</span>)</span>
<span id="cb1-18">plot(fds100[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], fds100[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"FDS100"</span>)</span>
<span id="cb1-19">plot(bpw34[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], bpw34[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BPW34"</span>)</span>
<span id="cb1-20"></span>
<span id="cb1-21">grid()</span>
<span id="cb1-22">xlabel(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"Wavelength (nm)"</span>)</span>
<span id="cb1-23">ylabel(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"Responsivity (A/W)"</span>)</span>
<span id="cb1-24">title(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"Responsitivity vs Wavelength"</span>)</span>
<span id="cb1-25">legend()</span>
<span id="cb1-26">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'assets\TIA_ideal_responsivity.png'</span>)</span></code></pre></div>
<p><img src="https://amamaral.github.io/blog/assets/TIA_ideal_responsivity.png" class="img-fluid"></p>
<p>As a final note, we are considering here ordinary photodiodes, where each impinging photon generates a single electron. There is another kind of detector where the carriers lye in a very unstable state, such that a photon may produce an avalanche of carriers, the so-called avalanche photodiode (APD). The physics and electronics behind APD’s is completely different from the case studied here.</p>
</section>
<section id="photodiode-norton-equivalent" class="level3">
<h3 class="anchored" data-anchor-id="photodiode-norton-equivalent">Photodiode Norton equivalent</h3>
<p>Now that some relevant aspects of the physics behind a photodiode were discussed, we may discuss on how to represent it electrically. Given that it’s quite natural to speak about the currents in a photodiode, it’s often preferable to discuss its properties in terms of its <a href="https://en.wikipedia.org/wiki/Norton%27s_theorem">Norton equivalent</a>, instead of Thévenin’s. In summary, we may represent an arbitrary DC circuit by a current source <img src="https://latex.codecogs.com/png.latex?I"> in parallel with an equivalent resistor <img src="https://latex.codecogs.com/png.latex?R_%7BShunt%7D">. We have already talked about the charge distribution near the PN junction, and given that there are charges separated by a distance over a given area, we may easily accept that there should be an effective capacitance <img src="https://latex.codecogs.com/png.latex?C_J"> in parallel to the current flow. This would be a model for the semiconductor itself, while there may be also a resistance associated with the electrical contacts in series with the semiconductor, <img src="https://latex.codecogs.com/png.latex?R_%7BSeries%7D">. If we consider all of these contributions, an effective model for the photodiode is given below.</p>
<p><img src="https://amamaral.github.io/blog/assets/TIA_photodiode.png" class="img-fluid" style="width:60.0%"></p>
<p>The value of <img src="https://latex.codecogs.com/png.latex?R_%7BSeries%7D"> is often negligible. Meanwhile, <img src="https://latex.codecogs.com/png.latex?R_%7BShunt%7D"> can be estimated from the small-signal conductance <img src="https://latex.codecogs.com/png.latex?g=%5Cfrac%7BdI%7D%7BdV_D%7D%20=%20%5Cfrac%7BI_D%7D%7BV_T%7D%20e%5E%7BV_D/V_T%7D">. At zero bias voltage <img src="https://latex.codecogs.com/png.latex?V_D=0">, and <img src="https://latex.codecogs.com/png.latex?g%20=%20%5Cfrac%7BI_D%7D%7BV_T%7D%20=%201/R_%7BShunt%7D">. Given that <img src="https://latex.codecogs.com/png.latex?V_T%5Capprox%2025%5C,%5Ctext%7BmV%7D"> and <img src="https://latex.codecogs.com/png.latex?I_D%5Capprox"> pA-nA range, <img src="https://latex.codecogs.com/png.latex?R_%7BShunt%7D%5Cgtrsim%201%5C,%5Ctext%7BG%7D%5COmega"> and can be safely neglected. These simplifications are also valid under reverse bias (<img src="https://latex.codecogs.com/png.latex?V_D%3C0">). The last effective component is the junction capacitance <img src="https://latex.codecogs.com/png.latex?C_J">. <img src="https://latex.codecogs.com/png.latex?C_J"> depends on several internal characteristics (as junction area, doping profile, temperature, bias voltage…) and is very important in the determination of the AC properties of the transimpedance amplifier. We may thus simplify the photodiode circuit to the model below.</p>
<p><img src="https://amamaral.github.io/blog/assets/TIA_photodiode_simplified.png" class="img-fluid" style="width:40.0%"></p>
</section>
<section id="typical-photodiode-specs" class="level3">
<h3 class="anchored" data-anchor-id="typical-photodiode-specs">Typical photodiode specs</h3>
<ol type="a">
<li>Thorlabs FDS100</li>
</ol>
<ul>
<li>Optical characteristics
<ul>
<li>Responsivity: 0.65 A/W (@ 980 nm)</li>
<li>Active area: 3.6mm x 3.6mm</li>
</ul></li>
<li>Electrical characteristics
<ul>
<li>Dark current: 1 nA (Typ.)</li>
<li>Internal capacitance: 237 pF (@ 0V Reverse bias)</li>
</ul></li>
</ul>
<ol start="2" type="a">
<li>Vishay BPW34</li>
</ol>
<ul>
<li>Optical characteristics
<ul>
<li>Responsivity: 0.66 A/W (@ 950 nm)</li>
<li>Active area: 7.5 mm<img src="https://latex.codecogs.com/png.latex?%5E2"></li>
</ul></li>
<li>Electrical characteristics
<ul>
<li>Dark current: 2 nA (Typ.)</li>
<li>Reverse light current: 50 <img src="https://latex.codecogs.com/png.latex?%5Cmu">A (Typ.)</li>
<li>Internal capacitance: 70 pF (@ 0V Reverse bias)</li>
</ul></li>
</ul>
<div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Conversion of BPW34 datasheet parameters to responsivity @ 950 nm</span></span>
<span id="cb2-2">I_revCurrent <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">50e-6</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># A</span></span>
<span id="cb2-3">irradiance <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-3</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-2</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># W/m^2</span></span>
<span id="cb2-4">area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">7.5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-3</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># m^2</span></span>
<span id="cb2-5">R <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> I_revCurrent <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (irradiance <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> area)</span></code></pre></div>
</section>
</section>
<section id="direct-signal-measurement" class="level2">
<h2 class="anchored" data-anchor-id="direct-signal-measurement">Direct signal measurement</h2>
<p>We may now use the simplified model to consider what we will measure by connecting a photodiode directly to a voltmeter or an oscilloscope. The circuit is essentially a resistor <img src="https://latex.codecogs.com/png.latex?R"> across the diode terminals, and a voltmeter that measures <img src="https://latex.codecogs.com/png.latex?V_D">. Instead of <img src="https://latex.codecogs.com/png.latex?C_J"> only, we may also consider that the measurement instrument also contains some effective capacitance across it’s input terminals, <img src="https://latex.codecogs.com/png.latex?C_%7Bin%7D">, and the total capacitance is <img src="https://latex.codecogs.com/png.latex?C%20=%20C_J%20+%20C_%7Bin%7D">.</p>
<section id="dc-analysis" class="level3">
<h3 class="anchored" data-anchor-id="dc-analysis">DC analysis</h3>
<p>Let us consider that the light source has a constant optical power <img src="https://latex.codecogs.com/png.latex?P">. Given that a current <img src="https://latex.codecogs.com/png.latex?I"> flows across the photodiode, <img src="https://latex.codecogs.com/png.latex?V_D=%20-R%20I%20=%20R%20I_%7Brev%7D%20-%20R%20I_D%20%5Cleft(e%5E%7BV_D/V_T%7D-1%5Cright)."></p>
<p>The previous expression is transcendental in <img src="https://latex.codecogs.com/png.latex?V_D">, such that we’re not able to express <img src="https://latex.codecogs.com/png.latex?V_D"> in terms of <img src="https://latex.codecogs.com/png.latex?I_%7Brev%7D"> using elementary functions. However, we may gain understanding with a graphical solution. Let’s consider what happens for the BPW34 photodiode when connected across a 1 M<img src="https://latex.codecogs.com/png.latex?%5COmega"> resistor (typical value for oscilloscopes). Using the dark current given above, <img src="https://latex.codecogs.com/png.latex?R%20I_D%20=%202%5C,%5Ctext%7BmV%7D">. Also, for improved clarity, let’s consider <img src="https://latex.codecogs.com/png.latex?V_%7Brev%7D=R%20I_%7Brev%7D"> as the voltage contribution to <img src="https://latex.codecogs.com/png.latex?V_D"> due to light only. Ideally, we would be interested in having <img src="https://latex.codecogs.com/png.latex?V_D=V_%7Brev%7D">. However, the increase in <img src="https://latex.codecogs.com/png.latex?V_D"> leads to a nonlinear relation between <img src="https://latex.codecogs.com/png.latex?V_%7BD%7D"> and <img src="https://latex.codecogs.com/png.latex?V_%7Brev%7D">. When does the deviation from the linear behavior becomes significant? The figure below shows the measured voltage <img src="https://latex.codecogs.com/png.latex?V_D"> versus the voltage due to photodetection only, <img src="https://latex.codecogs.com/png.latex?V_%7Brev%7D">.</p>
<div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>pylab inline</span>
<span id="cb3-2">V_D <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Voltage across diode, in mV</span></span>
<span id="cb3-3"></span>
<span id="cb3-4">R <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e6</span>     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 1MOhm resistor</span></span>
<span id="cb3-5">I_D <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2e-9</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Dark current (in A)</span></span>
<span id="cb3-6">V_T <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span>    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Carrier thermal energy at room temperature (in mV)</span></span>
<span id="cb3-7"></span>
<span id="cb3-8">v_rev_0nA <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> V_D</span>
<span id="cb3-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the 1e3 factor below converts the voltage to mV</span></span>
<span id="cb3-10">v_rev_2nA <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> V_D <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (R <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> I_D <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e3</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (exp(V_D<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>V_T)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb3-11"></span>
<span id="cb3-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Approximate a mean linear relation between V_D and v_rev</span></span>
<span id="cb3-13">i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">abs</span>(V_D<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span>).argmin() <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Which V_D index is closer to V_D==60 mV?</span></span>
<span id="cb3-14">V_mean_slope <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (v_rev_2nA[i]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>v_rev_2nA[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>(V_D[i]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>V_D[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb3-15">v_linearized <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> V_mean_slope <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> V_D</span>
<span id="cb3-16"></span>
<span id="cb3-17">plot(v_rev_0nA, V_D, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'$I_D=0$'</span>)</span>
<span id="cb3-18">plot(v_rev_2nA, V_D, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'$I_D=2$ nA'</span>)</span>
<span id="cb3-19">plot(v_linearized, V_D, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'Linearized relation'</span>)</span>
<span id="cb3-20">legend()</span>
<span id="cb3-21">ylabel(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'$V_D$ (mV)'</span>)</span>
<span id="cb3-22">xlabel(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'$V_</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{rev}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">=V_D + R I_D \left(e^{V_D/V_T}-1\right)$ (mV)'</span>)</span>
<span id="cb3-23">grid()</span>
<span id="cb3-24">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'assets\TIA_diode_saturation.png'</span>)</span></code></pre></div>
<p><img src="https://amamaral.github.io/blog/assets/TIA_diode_saturation.png" class="img-fluid"></p>
<p>Notice that the dark current is very important to the photodiode linearity. The deviation grows exponentially with an increase in the <img src="https://latex.codecogs.com/png.latex?V_D/V_T"> ratio, what indicates that the upper voltage limit to a linear detector using this circuit is some small multiple of <img src="https://latex.codecogs.com/png.latex?V_T">. However, if we consider only small <img src="https://latex.codecogs.com/png.latex?V_D"> voltages, its possible to obtain an approximate linear relation. Assuming that one calibrates the photodiode voltage at <img src="https://latex.codecogs.com/png.latex?V_D=60%5C,%5Ctext%7BmV%7D">, the deviation between the linearized relation and the actual relation between <img src="https://latex.codecogs.com/png.latex?V_D"> and <img src="https://latex.codecogs.com/png.latex?V_%7Brev%7D"> is relatively small for <img src="https://latex.codecogs.com/png.latex?0%20%5Cleq%20V_D%20%5Cleq%2060%5C,%5Ctext%7BmV%7D">. This is an important limitation when using photodiodes directly, given that such small voltages are difficult to measure using oscilloscopes (small signals may be easily lost when the photodiode operates in this linearized range). Another remark is that the photodiode response can be brought to the linear regime with the reduction of the load resistor <img src="https://latex.codecogs.com/png.latex?R">, at the cost of reduced sensitivity.</p>
<p>To sum up the discussion, there are a few worthy comments. Supposing that we’re in the linearized representation of the PD, we may state that <img src="https://latex.codecogs.com/png.latex?V_%7Brev%7D=%5Calpha%20V_%7BD%7D">. Also, the typical currents necessary to maintain the diode in the linearized region occur for <img src="https://latex.codecogs.com/png.latex?V_D%5Capprox%2050%5C,%5Ctext%7BmV%7D">, or when <img src="https://latex.codecogs.com/png.latex?I_%7Brev%7D%5Capprox%2050%5C,%5Ctext%7BnA%7D"> (Assuming <img src="https://latex.codecogs.com/png.latex?R=1%5C,%5Ctext%7BM%7D%5COmega">).</p>
</section>
<section id="ac-analysis" class="level3">
<h3 class="anchored" data-anchor-id="ac-analysis">AC analysis</h3>
<p>Now we will consider what happens to the signal when the light beam pulses. This is specially important, considering that photodiodes often used to measure light from ultrafast lasers, where the light pulses have durations ranging from ns (<img src="https://latex.codecogs.com/png.latex?10%5E%7B-9%7D"> s) to fs (<img src="https://latex.codecogs.com/png.latex?10%5E%7B-15%7D"> s). Given that the currents and voltages are dynamic, the effective capacitor <img src="https://latex.codecogs.com/png.latex?C"> becomes relevant. Using Kirchhoff laws for the voltages and currents, we may check that the voltage applied to all elements is <img src="https://latex.codecogs.com/png.latex?V_D">, whereas the current through the diode is divided between the capacitor <img src="https://latex.codecogs.com/png.latex?C"> and the resistor <img src="https://latex.codecogs.com/png.latex?R">.</p>
<p><img src="https://latex.codecogs.com/png.latex?-I%20=%20I_%7Brev%7D%20-%20I_D%20%5Cleft(e%5E%7BV_D/V_T%7D-1%5Cright)%20=%20C%20%5Cfrac%7BdV_D%7D%7Bdt%7D%20+%20%5Cfrac%7BV_D%7D%7BR%7D"></p>
<p><img src="https://latex.codecogs.com/png.latex?RC%20%5Cfrac%7BdV_D%7D%7Bdt%7D%20+%20%5Cleft%5BV_D%20+%20R%20I_D%20%5Cleft(e%5E%7BV_D/V_T%7D-1%5Cright)%5Cright%5D%20=%20RI_%7Brev%7D"></p>
<p>Again, an exact solution to the above equation is considerably difficult. However, if we consider that the photodiode operates in the linearized region for simplicity (<img src="https://latex.codecogs.com/png.latex?V_D/V_T"> less than a factor of 2 or 3), we can approximate <img src="https://latex.codecogs.com/png.latex?%5Cleft%5BV_D%20+%20R%20I_D%20%5Cleft(e%5E%7BV_D/V_T%7D-1%5Cright)%5Cright%5D%20%5Capprox%20%5Calpha%20V_D">. Just to have an idea of the order of magnitude, the DC analysis above indicated that <img src="https://latex.codecogs.com/png.latex?%5Calpha%5Capprox0.75">. Now it becomes much simpler to understand the behavior of <img src="https://latex.codecogs.com/png.latex?V_D">,</p>
<p><img src="https://latex.codecogs.com/png.latex?RC%20%5Cfrac%7BdV_D%7D%7Bdt%7D%20+%20%5Calpha%20V_D%20=%20RI_%7Brev%7D."></p>
<p>The above expression is similar to the case where a capacitor <img src="https://latex.codecogs.com/png.latex?C"> discharges through a resistor <img src="https://latex.codecogs.com/png.latex?R">. There is a source term (<img src="https://latex.codecogs.com/png.latex?RI_%7Brev%7D">) which is due to the impinging light beam. We may then consider the transfer function between the light source and <img src="https://latex.codecogs.com/png.latex?V_D">. Assuming <img src="https://latex.codecogs.com/png.latex?V_D=V_%7BD%5Comega%7De%5E%7Bj%5Comega%20t%7D">, and <img src="https://latex.codecogs.com/png.latex?I_%7Brev%7D%20=%20%20%5Ctext%7BResp%7D(%5Clambda)%20P_%5Comega(%5Clambda)%20e%5E%7Bj%5Comega%20t%7D">, and</p>
<p><img src="https://latex.codecogs.com/png.latex?V_%7BD%5Comega%7D%20=%20%5Cfrac%7BR%7D%7B%5Calpha%20+%20j%20%5Comega%20RC%7D%20%20%5Ctext%7BResp%7D(%5Clambda)%20P_%5Comega(%5Clambda)"></p>
<p>Therefore, if the beam power contains terms oscillating at a high frequency (<img src="https://latex.codecogs.com/png.latex?%5Comega%20%5Cgg%20%5Calpha/RC">), then these terms will not be present in <img src="https://latex.codecogs.com/png.latex?V_%7BD%5Comega%7D">. Thus, for fast signals one must use photodiodes with small capacitances. Fast photodiodes can be easily recognized for their small active region area.</p>
<p>Another relevant condition is the circuit response due to an ultrashort pulse. In this case the pulse is so fast that the associated current occurs almost instantly. The beam power can be expressed in terms of the Dirac delta impulse, <img src="https://latex.codecogs.com/png.latex?P(t)=E_%7Bsingle-pulse%7D%20%5Cdelta(t)">, where <img src="https://latex.codecogs.com/png.latex?E_%7Bsingle-pulse%7D"> is the energy contained in the optical pulse and the Dirac Delta satisfies the following properties: <img src="https://latex.codecogs.com/png.latex?%5Cdelta(t)=0"> for <img src="https://latex.codecogs.com/png.latex?t%5Cneq%200"> and <img src="https://latex.codecogs.com/png.latex?%5Cint_%7B-%5Cepsilon%7D%5E%7B%5Cepsilon%7D%20%5Cdelta(t)%20dt%20=%201"> for infinitesimal <img src="https://latex.codecogs.com/png.latex?%5Cepsilon">. For the short pulse, and considering that <img src="https://latex.codecogs.com/png.latex?V_D=0"> before the pulse, we have that <img src="https://latex.codecogs.com/png.latex?%5Cfrac%7BdV_D%7D%7Bdt%7D%20=%20%5Cfrac%7B1%7D%7BC%7D%20%5Ctext%7BResp%7D(%5Clambda)%20E_%7Bsingle-pulse%7D%20%5Cdelta(t)%20-%20%5Cfrac%7B%5Calpha%7D%7BRC%7D%20V_D."></p>
<p>Integrating both sides only from <img src="https://latex.codecogs.com/png.latex?-%5Cepsilon"> to <img src="https://latex.codecogs.com/png.latex?%5Cepsilon">, where <img src="https://latex.codecogs.com/png.latex?%5Cepsilon"> is infinitesimal, we have that</p>
<p><img src="https://latex.codecogs.com/png.latex?V_D(%5Cepsilon)%20-%20V_D(-%5Cepsilon)%20=%20%5Cfrac%7B1%7D%7BC%7D%20%5Ctext%7BResp%7D(%5Clambda)%20E_%7Bsingle-pulse%7D%20-%20%5Cfrac%7B%5Calpha%7D%7BRC%7D%20%5Cint_%7B-%5Cepsilon%7D%5E%7B%5Cepsilon%7D%20V_D(t)%20dt."></p>
<p><img src="https://latex.codecogs.com/png.latex?V_D(-%5Cepsilon)=0">, because it’s <img src="https://latex.codecogs.com/png.latex?V_D"> before the pulse, while <img src="https://latex.codecogs.com/png.latex?%5Cint_%7B-%5Cepsilon%7D%5E%7B%5Cepsilon%7D%20V_D(t)%20dt%20%5Cleq%20%5Ctext%7BMaximum%7D%5Cleft%5BV_D(-%5Cepsilon%3Ct%3C%5Cepsilon)%5Cright%5D2%5Cepsilon%20%5Crightarrow%200"> in the limit where <img src="https://latex.codecogs.com/png.latex?%5Cepsilon%20%5Crightarrow%200">. Thus, the photodiode current produced by an ultrafast pulse is equivalent to consider an instantaneous charging of the effective capacitor <img src="https://latex.codecogs.com/png.latex?C"> with a charge <img src="https://latex.codecogs.com/png.latex?%5Ctext%7BResp%7D(%5Clambda)%20E_%7Bsingle-pulse%7D">, since</p>
<p><img src="https://latex.codecogs.com/png.latex?V_D(t=0%5E+)%20=%20%5Cfrac%7B1%7D%7BC%7D%20%5Ctext%7BResp%7D(%5Clambda)%20E_%7Bsingle-pulse%7D"></p>
<p>To verify the behavior of <img src="https://latex.codecogs.com/png.latex?V_D"> after the pulse, it simply an issue of considering <img src="https://latex.codecogs.com/png.latex?V_D(t=0%5E+)"> as the initial condition. This circuit discharges as an RC circuit with a time constant <img src="https://latex.codecogs.com/png.latex?RC/%5Calpha">.</p>
<p><img src="https://latex.codecogs.com/png.latex?V_D(t%3E0)%20=%20%5Cfrac%7B%20%5Ctext%7BResp%7D(%5Clambda)%20E_%7Bsingle-pulse%7D%7D%7BC%7D%20e%5E%7B-%5Calpha%20t/RC%7D"></p>
<p><img src="https://latex.codecogs.com/png.latex?V_D"> can rise very fast (and the limitations in the rise time are beyond this simple model), and decays according to the photodiode capacitor <img src="https://latex.codecogs.com/png.latex?C"> and the measurement instrument resistance <img src="https://latex.codecogs.com/png.latex?R">. The input resistance of an oscilloscope is typically around <img src="https://latex.codecogs.com/png.latex?1%5C,%5Ctext%7BM%7D%5COmega">, thus if one needs to reduce the circuit response time to observe fast features in the signal, one may connect a smaller resistance in parallel to the photodiode, to reduce the decay time.</p>
</section>
</section>
<section id="transimpedance-amplifier-design" class="level2">
<h2 class="anchored" data-anchor-id="transimpedance-amplifier-design">Transimpedance amplifier design</h2>
<p>While it’s possible to use diodes within their almost linear range, the associated voltages (~50mV) are quite small. It’s much easier to measure voltages in the 1-5V range, where there are various tools available to measure voltages. For instance, one may use an arduino board to perform several measurements. Thus, an amplified signal may bring in several interesting aspects. Here we will consider some basics of an important configuration for photodiodes: the transimpedance amplifier, where the photodiode current is converted into a voltage. The design of these amplifiers is also nicely covered in the <a href="https://www.maximintegrated.com/en/app-notes/index.mvp/id/5129">Maxim Application Note 5129</a>, and in the <a href="http://www.ti.com/tool/tipd176">Texas Instruments Reference Design 176</a>.</p>
<section id="dc-analysis-1" class="level3">
<h3 class="anchored" data-anchor-id="dc-analysis-1">DC analysis</h3>
<p>We will consider the ideal case where the photodiode is connected with to the inverting input and the ground, and a single resistor <img src="https://latex.codecogs.com/png.latex?R_F"> is connected in the feedback path. We will consider an ideal opamp, where no current flows through the input terminals.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://amamaral.github.io/blog/posts/transimpedance-amplifiers/.png" class="img-fluid figure-img"></p>
<figcaption>Circuit schematic figure</figcaption>
</figure>
</div>
<p>For an opamp under ordinary working circumstances, the output voltage <img src="https://latex.codecogs.com/png.latex?V"> is related to the inverting and non-inverting input voltages <img src="https://latex.codecogs.com/png.latex?v_-">, <img src="https://latex.codecogs.com/png.latex?v_+"> is</p>
<p><img src="https://latex.codecogs.com/png.latex?V%20=%20A%20(v_+%20-%20v_-)"></p>
<p>The open loop gain <img src="https://latex.codecogs.com/png.latex?A"> often has very large values (<img src="https://latex.codecogs.com/png.latex?10%5E%7B10%7D-10%5E%7B12%7D">), such that <img src="https://latex.codecogs.com/png.latex?v_+%20-%20v_-%20=%20V/A%20%5Capprox%200">. The condition <img src="https://latex.codecogs.com/png.latex?v_+%20-%20v_-"> is also called the <em>virtual short constraint</em>. Given that <img src="https://latex.codecogs.com/png.latex?v_+"> is grounded, <img src="https://latex.codecogs.com/png.latex?v_-=v_+=v=0">. A nice feature of this configuration is that the voltage across the diode is <img src="https://latex.codecogs.com/png.latex?0%5C,%5Ctext%7BV%7D">. Then, the dark current contribution becomes negligible and only <img src="https://latex.codecogs.com/png.latex?I_%7Brev%7D"> contributes to the current through the diode. Given that <img src="https://latex.codecogs.com/png.latex?I_%7Brev%7D"> must also flow through <img src="https://latex.codecogs.com/png.latex?R_F">, <img src="https://latex.codecogs.com/png.latex?V=R_F%20I_%7Brev%7D."></p>
<p>Notice that we the photodiode was biased <img src="https://latex.codecogs.com/png.latex?(v_+=v%5Cneq0)">, the dark current would add to <img src="https://latex.codecogs.com/png.latex?I_%7Brev%7D">, such that <img src="https://latex.codecogs.com/png.latex?I_D%20%5Cleft(e%5E%7B-v/V_T%7D-1%5Cright)%5Capprox-I_D">. When considering the reverse bias voltage below, we assume the simplifying assumption that either the bias voltage is zero, such that the dark current is negligible <img src="https://latex.codecogs.com/png.latex?(I_D=0)">, or that the reverse bias is large enough (<img src="https://latex.codecogs.com/png.latex?v%20%5Cgg%20V_T">) that the full dark current is a constant factor (<img src="https://latex.codecogs.com/png.latex?I_D%20%5Cleft(e%5E%7B-v/V_T%7D-1%5Cright)%5Capprox-I_D">). Also, the real opamp draws some bias current <img src="https://latex.codecogs.com/png.latex?I_B"> at its inputs, and there is some offset voltage between <img src="https://latex.codecogs.com/png.latex?v_+"> and <img src="https://latex.codecogs.com/png.latex?v_-">, <img src="https://latex.codecogs.com/png.latex?v_%7Bos%7D=v_+%20-%20v_-%5Cneq%200">. Typical figures for opamps with BJT input transistors are <img src="https://latex.codecogs.com/png.latex?I_B~100%5C,%5Ctext%7BnA%7D">, while FET or CMOS at the opamp input stage lowers to <img src="https://latex.codecogs.com/png.latex?I_B%3C100%5C,%5Ctext%7BpA%7D">. The input offset voltage is often around a few mV or less, and can be trimmed to zero by following the opamp manufacturer suggestions. These are the most important opamp features at DC for the present application, and we will consider these effects below.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://amamaral.github.io/blog/posts/transimpedance-amplifiers/.png" class="img-fluid figure-img"></p>
<figcaption>Circuit schematic - opamp errors figure</figcaption>
</figure>
</div>
<p>Consideration of the currents at the opamp inverting input gives</p>
<p><img src="https://latex.codecogs.com/png.latex?I_%7Brev%7D%20+%20I_%7BD%7D%20=%20%5Cfrac%7BV-(v-v_%7Bos%7D)%7D%7BR_F%7D%20-%20I_B,"></p>
<p><img src="https://latex.codecogs.com/png.latex?V%20=%20v-v_%7Bos%7D%20+%20R_F(I_%7Brev%7D%20+%20I_%7BD%7D%20+%20I_B)"></p>
<p>where it should be remembered that <img src="https://latex.codecogs.com/png.latex?I_D=0"> for the unbiased photodiode (<img src="https://latex.codecogs.com/png.latex?v=0">), while <img src="https://latex.codecogs.com/png.latex?I_D%5Cneq0"> in the biased case (<img src="https://latex.codecogs.com/png.latex?v%5Cneq0">).</p>
<section id="unbiased-photodiode" class="level4">
<h4 class="anchored" data-anchor-id="unbiased-photodiode">Unbiased photodiode</h4>
<p>In this case <img src="https://latex.codecogs.com/png.latex?v=0"> and <img src="https://latex.codecogs.com/png.latex?I_%7BD%7D=0">. So, the offset voltage gives an error in the order of mV, while the base current <img src="https://latex.codecogs.com/png.latex?I_B"> is subject to the same transimpedance gain as the reverse current. Thus, <img src="https://latex.codecogs.com/png.latex?I_B"> limits the maximum achievable gain, and it’s interesting to keep it small by selecting FET input opamps. By knowing the output voltage range of interest, at a given reverse current, one may select the <img src="https://latex.codecogs.com/png.latex?R_F"> value. For instance, the arduino ADC accepts voltages in the range of 0-5 V. For the BPW34, which has a typical <img src="https://latex.codecogs.com/png.latex?I_%7Brev%7D=50%5C,%5Cmu%5Ctext%7BA%7D">, we may select <img src="https://latex.codecogs.com/png.latex?R_F=%5Cfrac%7B5%7D%7B50%20%5Ccdot%2010%5E%7B-6%7D%7D=100%5C,%5Ctext%7Bk%7D%5COmega">. For higher sensitivities (smaller <img src="https://latex.codecogs.com/png.latex?I_%7Brev%7D">), the associated <img src="https://latex.codecogs.com/png.latex?R_F"> must be larger.</p>
</section>
<section id="biased-photodiode" class="level4">
<h4 class="anchored" data-anchor-id="biased-photodiode">Biased photodiode</h4>
<p>In this case <img src="https://latex.codecogs.com/png.latex?v%5Cneq0"> and <img src="https://latex.codecogs.com/png.latex?I_%7BD%7D"> is characteristic of the photodiode. The <img src="https://latex.codecogs.com/png.latex?v_%7Bos%7D"> represents again a small contribution to <img src="https://latex.codecogs.com/png.latex?V">, and our major concerns are <img src="https://latex.codecogs.com/png.latex?I_B"> and <img src="https://latex.codecogs.com/png.latex?I_D">. A FET input opamp will have <img src="https://latex.codecogs.com/png.latex?I_B%3C100%5C,%5Ctext%7BpA%7D">, while <img src="https://latex.codecogs.com/png.latex?I_D%5Capprox2%5C,%5Ctext%7BnA%7D">. Let’s consider that <img src="https://latex.codecogs.com/png.latex?I_B"> is negligible. Then <img src="https://latex.codecogs.com/png.latex?V"> has a minimum value of <img src="https://latex.codecogs.com/png.latex?v+R_FI_D"> and <img src="https://latex.codecogs.com/png.latex?R_FI_%7Brev%7D"> indicates the output variation due to the incident light. Increasing <img src="https://latex.codecogs.com/png.latex?R"> increases the signal gain, but decreases the maximum output voltage range. If <img src="https://latex.codecogs.com/png.latex?I_D"> is much smaller than the typical <img src="https://latex.codecogs.com/png.latex?I_%7Brev%7D">, than we select <img src="https://latex.codecogs.com/png.latex?R_F"> as before. For example, for the BPW34, <img src="https://latex.codecogs.com/png.latex?I_D%5Capprox2%5C,%5Ctext%7BnA%7D">, while <img src="https://latex.codecogs.com/png.latex?I_%7Brev%7D%5Capprox50%5C,%5Cmu%5Ctext%7BA%7D">. Thus, selecting a <img src="https://latex.codecogs.com/png.latex?100%5C,%5Ctext%7Bk%7D"> resistor implies that the dark current offsets the output by <img src="https://latex.codecogs.com/png.latex?200%5C,%5Cmu%5Ctext%7BV%7D">. However, if <img src="https://latex.codecogs.com/png.latex?I_%7Brev%7D"> and <img src="https://latex.codecogs.com/png.latex?I_D"> have the same order of magnitude, they will be amplified together and the output offset due to <img src="https://latex.codecogs.com/png.latex?I_D"> will become of the order of the output voltage. Thus, for very small light powers, <strong>the unbiased configuration is more easily amplified, while the biased photodiode is adequate for larger signals</strong>. The biased version will show itself specially useful when we consider the AC response of these circuits.</p>
<p>As a final remark, it’s possible to make <img src="https://latex.codecogs.com/png.latex?v=0"> while maintaining the diode reverse-biased by connecting the photodiode to a battery instead of ground.</p>
<!--- Would it be an effective bias current removal to add a reverse-biased diode whose voltage drop is compensated by an opamp? In other words, to use a reverse-biased diode to create a current in the nA range to compensate for the PD dark-current. If this is feasible, it would even enable to use ordinary photodiodes as photon-counting devices! (No need for local oscillators: the bias current would be due to an opamp) --->
</section>
</section>
<section id="ac-analysis---oscillations" class="level3">
<h3 class="anchored" data-anchor-id="ac-analysis---oscillations">AC analysis - Oscillations</h3>
<p>The DC analysis neglects that the opamp output needs some time to change it’s output value. Indeed, it can be seen in the datasheets that the gain effectively drops with a frequency increase. This characteristic is represented by the unit Gain-Bandwidth-Product (<img src="https://latex.codecogs.com/png.latex?%5Comega_%7BGBP%7D">) frequency, which indicates the frequency where the voltage gain becomes <img src="https://latex.codecogs.com/png.latex?1">. To estimate the effect of opamp limited bandwidth in our analysis, we consider that the voltage gain becomes <img src="https://latex.codecogs.com/png.latex?A%20%5Crightarrow%20A/%5Cleft(1+j%5Comega/%5Comega_0%5Cright)">, to simulate the effect of a low pass filter between the input voltage difference and the output voltage. <img src="https://latex.codecogs.com/png.latex?%5Comega_0"> is the filter low-pass 3dB frequency, but it’s more interesting to express it in terms of <img src="https://latex.codecogs.com/png.latex?%5Comega_%7BGBP%7D">.</p>
<p>When <img src="https://latex.codecogs.com/png.latex?%5Comega=%5Comega_%7BGBP%7D">, the gain factor becomes 1, <img src="https://latex.codecogs.com/png.latex?%7CA/%5Cleft(1+j%5Comega_%7BGBP%7D/%5Comega_0%5Cright)%7C=1">, or <img src="https://latex.codecogs.com/png.latex?%5Comega_0%20%5Capprox%20%5Comega_%7BGBP%7D/A">. We can than verify how this affects our virtual short opamp simplification, given that now</p>
<p><img src="https://latex.codecogs.com/png.latex?V%20=%20%5Cfrac%7BA%7D%7B1+jA%5Comega/%5Comega_%7BGBP%7D%7D%20(v_+%20-%20v_-)"></p>
<p>In the limit <img src="https://latex.codecogs.com/png.latex?A%20%5Crightarrow%20%5Cinfty">, we can state approximately that</p>
<p><img src="https://latex.codecogs.com/png.latex?v_+%20-%20v_-%20=%20j%5Cfrac%7B%5Comega%7D%7B%5Comega_%7BGBP%7D%7D%20V%20%5Cequiv%20%5Cfrac%7B1%7D%7B%5Comega_%7BGBP%7D%7D%20%5Cfrac%7BdV%7D%7Bdt%7D"></p>
<p>Thus, the opamp inputs will be kept at the same voltage only at signal frequencies much smaller than <img src="https://latex.codecogs.com/png.latex?%5Comega_%7BGBP%7D">. When the signal frequency increases, the difference can become as large as the output voltage. This is an important feature in the design of transimpedance amplifiers because this opamp behavior will lead to oscillations in <img src="https://latex.codecogs.com/png.latex?V">.</p>
<p>Consider again the currents at the opamp inverting input. We have that <img src="https://latex.codecogs.com/png.latex?v_-=-%5Cfrac%7B1%7D%7B%5Comega_%7BGBP%7D%7D%20%5Cfrac%7BdV%7D%7Bdt%7D">, and the currents must satisfy</p>
<p><img src="https://latex.codecogs.com/png.latex?%20I_%7Brev%7D%20+%20I_D%20=%20-%20C%20%5Cfrac%7Bdv_-%7D%7Bdt%7D%20+%20%5Cfrac%7BV-v_-%7D%7BR_F%7D%20"></p>
<p><img src="https://latex.codecogs.com/png.latex?%20R_F(I_%7Brev%7D%20+%20I_D)%20=%20%5Cfrac%7BR_FC%7D%7B%5Comega_%7BGBP%7D%7D%20%5Cfrac%7Bd%5E2V%7D%7Bdt%5E2%7D%20+%20%5Cfrac%7B1%7D%7B%5Comega_%7BGBP%7D%7D%20%5Cfrac%7BdV%7D%7Bdt%7D%20+%20V"></p>
<p>Notice that the above equation for <img src="https://latex.codecogs.com/png.latex?V"> is of second order in time, as in the harmonic oscillator equation. These oscillations, if present, aren’t related with the input light signal, and are undesirable features in the output signal.</p>
<p>To study these natural oscillations, we consider how <img src="https://latex.codecogs.com/png.latex?V"> behaves without any external inputs (<img src="https://latex.codecogs.com/png.latex?I_%7Brev%7D=I_D=0">). Then,</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cfrac%7Bd%5E2V%7D%7Bdt%5E2%7D%20+%20%5Cfrac%7B1%7D%7BR_FC%7D%20%5Cfrac%7BdV%7D%7Bdt%7D%20+%5Cfrac%7B%5Comega_%7BGBP%7D%7D%7BR_FC%7DV%20=%200"></p>
<p><img src="https://latex.codecogs.com/png.latex?V%20=%20V_0%20e%5E%7Bj%5Clambda%20t%7D"> gives the characteristic equation</p>
<p><img src="https://latex.codecogs.com/png.latex?-%5Clambda%5E2%20+j%5Clambda%20%5Cfrac%7B1%7D%7BR_FC%7D%20+%5Cfrac%7B%5Comega_%7BGBP%7D%7D%7BR_FC%7D%20=%200"></p>
<p><img src="https://latex.codecogs.com/png.latex?%5Clambda%20=%20%5Cfrac%7B1%7D%7B2R_FC%7D%5Cleft(j%20%5Cpm%20%5Csqrt%7B4%5Comega_%7BGBP%7DR_FC%20-%201%7D%5Cright)"></p>
<p>Thus, if <img src="https://latex.codecogs.com/png.latex?4%20%5Comega_%7BGBP%7DR_FC%20%3C%201">, then <img src="https://latex.codecogs.com/png.latex?%5Clambda"> will be purely imaginary and <img src="https://latex.codecogs.com/png.latex?V"> always decays exponentially. The oscillations are overdamped. The oscillations are called as critically damped when <img src="https://latex.codecogs.com/png.latex?4%20%5Comega_%7BGBP%7DR_FC=1">, and underdamped when <img src="https://latex.codecogs.com/png.latex?4%20%5Comega_%7BGBP%7DR_FC%3E1">. In the underdamped regime, <img src="https://latex.codecogs.com/png.latex?V_0"> can oscillate several times before settling to its final value. This can be a problem specially when using pulsed lasers, where the optical pulse is much shorter than the circuit response times. If we consider the BPW34 typical figures given in the DC analysis, when using a 1 MHz GBP opamp, we have <img src="https://latex.codecogs.com/png.latex?4%20%5Comega_%7BGBP%7DR_FC=176%5Cgg1">. Notice that we cannot modify <img src="https://latex.codecogs.com/png.latex?C">, which is an intrinsic feature of our detection. To remove oscillations from the circuit above either we must decrease the opamp bandwidth or decrease the transimpedance gain through <img src="https://latex.codecogs.com/png.latex?R_F">.</p>
<div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1">C <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">70e-12</span></span>
<span id="cb4-2">R_F <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e5</span></span>
<span id="cb4-3">GBP <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> pi <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e6</span></span>
<span id="cb4-4"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> GBP <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> R_F <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> C <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 175.92918860102841</span></span></code></pre></div>
<p>What can be done to remove this misbehavior? The critical condition for the onset of oscillations is <img src="https://latex.codecogs.com/png.latex?%5Comega_%7BGBP%7DR_FC=1">. If we want to maintain our transimpedance gain, we have to modify the loop bandwidth somehow. The cause of these oscillations is that <img src="https://latex.codecogs.com/png.latex?v_-%5Cpropto%5Cfrac%7BdV%7D%7Bdt%7D">, specially at higher frequencies. If we modify the feedback loop such that it becomes a follower at higher frequencies, the oscillations are not possible anymore. To decrease the loop impedance at higher frequencies, we may add a capacitor <img src="https://latex.codecogs.com/png.latex?C_F"> in parallel to <img src="https://latex.codecogs.com/png.latex?R_F">. The loop impedance becomes <img src="https://latex.codecogs.com/png.latex?Z_L%20=%20%5Cfrac%7BR_F%7D%7B1+j%5Comega%20R_F%20C_F%7D">. We can apply this impedance to the equation for <img src="https://latex.codecogs.com/png.latex?V"> in frequency representation and look for purely imaginary eigensolutions for <img src="https://latex.codecogs.com/png.latex?%5Comega">, which therefore will not include oscillations.</p>
<p>After some algebra, it can be verified that as long as <img src="https://latex.codecogs.com/png.latex?1%20-%202%20C_F%20R_F%20%5Comega_%7BGBP%7D%20-%204%20C%20R_F%20%5Comega_%7BGBP%7D%20+%20C_F%5E2%20R_F%5E2%20%5Comega_%7BGBP%7D%5E2%3E0">, the solution will not oscillate. Solving for <img src="https://latex.codecogs.com/png.latex?C_F">, it is obtained that given</p>
<p><img src="https://latex.codecogs.com/png.latex?C_F%20%3E%20%5Cfrac%7B1%20+%202%20%5Csqrt%7B%5Comega_%7BGBP%7D%20R_F%20C%7D%7D%7B%5Comega_%7BGBP%7D%20R_F%7D"></p>
<p>the opamp output voltage will not oscillate. The solution above is slightly different than those proposed in <a href="https://www.maximintegrated.com/en/app-notes/index.mvp/id/5129">Maxim Application Note 5129</a> or <a href="http://www.ti.com/tool/tipd176">Texas Instruments Reference Design 176</a>, but the numerical results are quite close. Indeed, the present equation is slightly more conservative. This is interesting, because the value found for <img src="https://latex.codecogs.com/png.latex?C_F"> depend strongly on the opamp bandwidth <img src="https://latex.codecogs.com/png.latex?%5Comega_%7BGBP%7D">, but this is another parameter which can vary significantly (<img src="https://latex.codecogs.com/png.latex?%5Cpm40%5C%25"> according to Maxim’s AN), since it’s not a trimmed parameter. Thus, the present equation can be used without having to underestimate <img src="https://latex.codecogs.com/png.latex?%5Comega_%7BGBP%7D">.</p>
<div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1">C <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">100e-12</span></span>
<span id="cb5-2">GBP <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>pi<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0e6</span></span>
<span id="cb5-3"></span>
<span id="cb5-4">R_F <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> logspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)</span>
<span id="cb5-5">our_eq   <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>sqrt(   <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> GBP <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> R_F <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> C))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>  (GBP <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> R_F)</span>
<span id="cb5-6">maxim_eq <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>sqrt(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> GBP <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> R_F <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> C))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>GBP <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> R_F)</span>
<span id="cb5-7">ti_eq    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>sqrt(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> GBP <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> R_F <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> C))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>GBP <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> R_F)</span>
<span id="cb5-8"></span>
<span id="cb5-9">semilogx(R_F,   our_eq<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e12</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'This'</span>)</span>
<span id="cb5-10">semilogx(R_F, maxim_eq<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e12</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Maxim AN 5129'</span>)</span>
<span id="cb5-11">semilogx(R_F,    ti_eq<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e12</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'TI RD 176'</span>)</span>
<span id="cb5-12">grid()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> legend()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'$R_F$ ($\Omega$)'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'$C_F$ (pF)'</span>)</span>
<span id="cb5-13">title(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'Feedback capacitor selection - $C=100$ pF, $f_</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{GBP}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">=1$ MHz'</span>)</span>
<span id="cb5-14">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'assets\TIA_feedback_capacitor_selection.png'</span>)</span></code></pre></div>
<p><img src="https://amamaral.github.io/blog/assets/TIA_feedback_capacitor_selection.png" class="img-fluid"></p>
<p>Therefore, if we return to our BPW34 design attempt, the feedback loop capacitor must have at least <img src="https://latex.codecogs.com/png.latex?C_F=23%5C,%5Ctext%7BpF%7D"> for a <img src="https://latex.codecogs.com/png.latex?100%5C,%5Ctext%7Bk%7D%5COmega"> feedback resistor, and <img src="https://latex.codecogs.com/png.latex?%5Comega_%7BGBP%7D=2%5Cpi%5Ccdot%201.0%5C,%5Ctext%7BMHz%7D">.</p>
<div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1">C <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">70e-12</span></span>
<span id="cb6-2">R_F <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e5</span></span>
<span id="cb6-3">GBP <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>pi<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0e6</span></span>
<span id="cb6-4"></span>
<span id="cb6-5">C_F <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>sqrt(GBP <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> R_F <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> C))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>(GBP <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> R_F) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 23 pF</span></span>
<span id="cb6-6">C_F</span></code></pre></div>
</section>
</section>
<section id="transimpedance-amplifier-design-summary" class="level2">
<h2 class="anchored" data-anchor-id="transimpedance-amplifier-design-summary">Transimpedance amplifier design summary</h2>
</section>
<section id="some-opamp-specs" class="level2">
<h2 class="anchored" data-anchor-id="some-opamp-specs">Some opamp specs</h2>
<p>Below are shown some specs for some ordinary opamps.</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th style="text-align: right;"></th>
<th style="text-align: center;">LM324</th>
<th style="text-align: center;">TL074</th>
<th style="text-align: center;">LF411</th>
<th style="text-align: center;">TLC2264</th>
<th style="text-align: center;">TLC2274</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: right;">Input type</td>
<td style="text-align: center;">BJT</td>
<td style="text-align: center;">FET</td>
<td style="text-align: center;">FET</td>
<td style="text-align: center;">CMOS</td>
<td style="text-align: center;">CMOS</td>
</tr>
<tr class="even">
<td style="text-align: right;"><img src="https://latex.codecogs.com/png.latex?f_%7BGBP%7D"></td>
<td style="text-align: center;">1 MHz</td>
<td style="text-align: center;">3 MHz</td>
<td style="text-align: center;">4 MHz</td>
<td style="text-align: center;">0.71 MHz</td>
<td style="text-align: center;">2.2 MHz</td>
</tr>
<tr class="odd">
<td style="text-align: right;"><img src="https://latex.codecogs.com/png.latex?I_B"></td>
<td style="text-align: center;">45 nA</td>
<td style="text-align: center;">65 pA</td>
<td style="text-align: center;">50 pA</td>
<td style="text-align: center;">1 pA</td>
<td style="text-align: center;">1 pA</td>
</tr>
<tr class="even">
<td style="text-align: right;"><img src="https://latex.codecogs.com/png.latex?v_%7Bos%7D"></td>
<td style="text-align: center;">2 mV</td>
<td style="text-align: center;">3 mV</td>
<td style="text-align: center;">0.8 mV</td>
<td style="text-align: center;">0.3 mV</td>
<td style="text-align: center;">0.3 mV</td>
</tr>
<tr class="odd">
<td style="text-align: right;">P. Supply</td>
<td style="text-align: center;">Single</td>
<td style="text-align: center;">Dual</td>
<td style="text-align: center;">Dual</td>
<td style="text-align: center;">Single</td>
<td style="text-align: center;">Single</td>
</tr>
</tbody>
</table>
</section>
<section id="tia---version-1" class="level2">
<h2 class="anchored" data-anchor-id="tia---version-1">TIA - Version 1</h2>
</section>
<section id="tia---version-2---noise-considerations" class="level2">
<h2 class="anchored" data-anchor-id="tia---version-2---noise-considerations">TIA - Version 2 - Noise considerations</h2>
<!--- See analog devices AN on dark current compensation.  --->
</section>
</section>
<section id="simulation" class="level1">
<h1>Simulation</h1>
</section>
<section id="experimental-results" class="level1">
<h1>Experimental results</h1>
</section>
<section id="complete-python-code" class="level1">
<h1>Complete python code</h1>
<!--- NOTES: Add important keywords, as photoconductive (reverse bias) or photovoltaic (zero-bias) PD modes.  --->
<!--- Final comment: Notice that typical photodiodes have high quantum efficiencies and a broadband optical response. Operating it as an LED it will have a high current to photon conversion ratio and vice-versa. Now, if two photodiodes are facing each other and there is a significant (balanced) current through them, they can emit light that will be absorbed by the other one at high efficiency. There would be a strong coupling between currents and light in between the PD's! Would it be a cavity with gain (instead of losses) at the mirrors? Considering that the light will be bouncing at the two PD's, with little power losses, would it lase? Second: would it be spectrally tunable with ease? This would be a broadband, tunable laser. Third: Consider that one PD has a 'large' current and emits light, and the other one operates as an usual PD. Can the emitter PD operate as a local oscillator to improve single photon detection efficiency? ---->


</section>

 ]]></description>
  <category>electronics</category>
  <category>arduino</category>
  <category>instrumentation</category>
  <category>optics</category>
  <guid>https://amamaral.github.io/blog/posts/transimpedance-amplifiers/</guid>
  <pubDate>Thu, 31 May 2018 00:00:00 GMT</pubDate>
  <media:content url="https://amamaral.github.io/blog/assets/TIA_photodiode.png" medium="image" type="image/png" height="63" width="144"/>
</item>
<item>
  <title>Python for experimental sciences — chapter I</title>
  <dc:creator>Anderson M. Amaral</dc:creator>
  <link>https://amamaral.github.io/blog/posts/python-for-experimental-sciences-1/</link>
  <description><![CDATA[ 




<section id="python-introduction" class="level1">
<h1>Python introduction</h1>
<p>Currently it’s hardly possible to perform serious scientific experiments without any sort of help from computers. They are needed for both controlling experimental setups and to analyze data. We will see in a series of posts how it’s easy to start doing data analysis with Python even for those without previous programming knowledge. The main idea of this tutorial is to allow a fast start to operate and understand how python can be used in scientific experiments. Some aspects can be difficult at the beginning, but a general recommendation is always valid: <strong>when in doubt, google for it</strong>. There are lots of information available in the web, specially for Python. The following contents aims to discuss the most basic aspects necessary to use python in basic data analysis, while a more extended text as a book would be an essential companion. Personally I like the book <a href="https://hplgit.github.io/primer.html/doc/pub/half/book.pdf"><em>A Primer on Scientific Programming with Python</em></a>, by Hans Petter Langtangen. Another great reference is the <a href="https://docs.python.org/3/tutorial/">Official Python Tutorial</a>, by Guido Van Rossum (the Python’s creator).</p>
<section id="basic-setup" class="level2">
<h2 class="anchored" data-anchor-id="basic-setup">Basic setup</h2>
<section id="installing-python" class="level3">
<h3 class="anchored" data-anchor-id="installing-python">Installing Python</h3>
<p>The first step is to install <strong>Python 3</strong>. There are several alternatives to that, and the <a href="https://www.anaconda.com/download/">Anaconda</a>&nbsp;is one available in all platforms (Windows, Linux and Mac). There are also other Python packages available (Ex.: <a href="http://www.winpython.org">WinPython</a> for windows platforms) or Python can be installed through a Linux package manager. However these alternatives will not be discussed, but are easily found in the web. Given that I use Windows, this series will consider Anaconda installed in this platform. However, the adjustments to use Linux or Mac should be minimal. In particular, the installation may ask if you want to register your Python distribution at some step. While not obligatory, sometimes this is very convenient. It is often disabled by default because then several distinct python’s can be installed in the same machine, but probably that has no use to us in what follows. Therefore, <strong>it’s suggested to register your Python distribution during installation.</strong></p>
</section>
<section id="accessing-the-jupyter-notebook" class="level3">
<h3 class="anchored" data-anchor-id="accessing-the-jupyter-notebook">Accessing the Jupyter Notebook</h3>
<p>The Jupyter notebook can be accessed from the system console <strong>if you’ve registered your python installation</strong>. The python registration is available during installation and is optional, it can be disabled. If the procedures below don’t work, you should be able to find Jupyter on your operational system’s start menu.</p>
<p>In Windows, its useful to create some folder to contain the files that you’ll be working with. Open that folder with the Windows Explorer (Ex.: <code>My Documents\Jupyter Notebooks</code>) and access the menu <code>File &gt; Open Windows PowerShell &gt; Open Windows PowerShell</code>.</p>
<p>To open the Jupyter notebook, type in the PowerShell</p>
<div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode powershell code-with-copy"><code class="sourceCode powershell"><span id="cb1-1">jupyter notebook</span></code></pre></div>
<p>Then, you must wait for the web browser to open the initial page of the Jupyter notebook. At the upper right corner there is a button to create a new notebook. Select a <code>New &gt; Python 3 notebook</code>. Now everything is set and we may start our first python program.</p>
</section>
</section>
<section id="a-quick-start-to-python-programming" class="level2">
<h2 class="anchored" data-anchor-id="a-quick-start-to-python-programming">A quick start to Python programming</h2>
<p>By default, the new notebook is opened with an input field (a <em>Cell</em>) adequate for code input (for other input types see the dropdown menu currently stating <code>Code</code>). Type <code>print("Obey the gravity. It's the law!")</code> in the cell and press <code>Shift + Enter</code> in your keyboard. The output must be</p>
<pre><code>Obey the gravity. It's the law!</code></pre>
<p>This is a small program which indicates that you want that the program returns a text (more correctly <em>string</em>) informing a given comment. Python understands anything between single <code>'text'</code> and double <code>"text"</code> quotes as a text. In Jupyter notebook the output of a given cell is just below the associated input code.</p>
<p>Now you think… well… the above code is nice. But, I want to perform experiments, and what I need is a computer to do heavy and difficult calculations. Python allows you to also do that easily. Consider a sum of two terms:</p>
<div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span></code></pre></div>
<p>Press <code>Shift + Enter</code> to execute the above code and check that the answer is correct. You can also try to improve the output. <strong>It’s possible to send several arguments to any function by separating expressions with a comma</strong>. to make your statement stronger:</p>
<div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"The sum of 2+2 is"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div>
<p>Python is very good at math. Indeed, we can perform several mathematical operations. Sum <code>+</code>, Difference <code>-</code>, Multiplication <code>*</code> and division <code>/</code> operators are available. Powers can be calculated with <code>**</code> (Ex.: <img src="https://latex.codecogs.com/png.latex?2%5E3"> is written as <code>2**3</code>), and operations can be grouped with parenthesis (<code>1/(1+1) == 0.5</code>, while <code>(1/1) + 1 == 2</code>). Python calculates powers, multiplications and divisions before sums and differences (See <a href="https://docs.python.org/3/reference/expressions.html">operator precedence</a>). Thus, when in doubt <strong>it’s a good practice to separate multiplication and division terms with parenthesis</strong>. We can also use variables to store information (numbers, texts and even more complex structures lying ahead). Suppose that we want to consider the parabolic trajectory of a mass due to the action of gravity. We may define the variables <code>y0</code>, <code>v0</code> and <code>a</code> to store the initial information of the mass launch (initial height, initial velocity and acceleration) as follows:</p>
<div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python input code-with-copy"><code class="sourceCode python"><span id="cb5-1">y0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>  <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># m</span></span>
<span id="cb5-2">v0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">20.0</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># m/s</span></span>
<span id="cb5-3">a  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">9.8</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># m/s**2</span></span></code></pre></div>
<p>Whenever we refer later to <code>y0</code>, <code>v0</code> or <code>a</code> we can retrieve these values from the computer memory. In this way we can, for example, write down mathematical formulas involving <code>y0</code>, <code>v0</code> and <code>a</code> and let the computer remember which number is associated with each quantity. This is interesting because it allows us to do and redo a given set of calculations just by changing these initial values. We don’t have to rewrite each step of the calculation, since we will later describe in Python which calculations we want the computer to perform.</p>
<p><strong>Notice that each instruction occupies one line</strong>. In the previous cell we had 3 instructions which only stored numbers in the memory. The units, as m/s, are not stored. Therefore, we must be careful with the units of each variable, or be sure that the adequate conversions are considered at the beginning or at a later stage. <strong>To keep track of the units it’s useful to add comments</strong> at the end of the line. Python will ignore everything after a <code>#</code> symbol, and you may add any text. Comments are useful to understand what the program is doing at each step. <strong>Also notice that the decimal separator in python is the period <code>.</code>, and not the comma <code>,</code></strong>. Commas are always<sup>1</sup> used to separate expressions, as function arguments.</p>
<p>Once all variables are available in the memory, you may calculate the mass height at a given time using the known formula <img src="https://latex.codecogs.com/png.latex?y(t)%20=%20y_0+%20v_0%20t+%5Cfrac%7Bat%5E2%7D%7B2%7D">. For example, at <img src="https://latex.codecogs.com/png.latex?t=3%5C,%5Ctext%7Bs%7D">, if we now request the python program to calculate</p>
<div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python input code-with-copy"><code class="sourceCode python"><span id="cb6-1">y0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> v0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Calculate the mass height at t=3 s</span></span></code></pre></div>
<pre><code>15.899999999999999</code></pre>
<p>To obtain the particle height at other times, we may replace the time <img src="https://latex.codecogs.com/png.latex?t=3%5C,%5Ctext%7Bs%7D"> by another time of interest. Also, we may the motion parameters <code>y0, v0, a</code> by updating the variable values. For example, if the particle now has an initial velocity of 15 m/s, we may adjust the initial velocity with the following code:</p>
<div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1">v0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># m/s</span></span></code></pre></div>
<p>An important remark is that the <strong>variable names must be typed exactly in the same way everywhere</strong>. <code>v0</code> and <code>V0</code> are different variables. The syntax (or how do you <strong>exactly</strong> write things) is extremely important in a computer language. The computer is “dumb” and will only follow exact instructions. Any language imprecision will give errors.</p>
<p>Python variables can store other types of information, besides numbers. For example, they may be used to store text (<code>strings</code>):</p>
<div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1">message <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"The current initial velocity is"</span></span>
<span id="cb9-2"></span>
<span id="cb9-3"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(message, v0)</span></code></pre></div>
</section>
<section id="functions" class="level2">
<h2 class="anchored" data-anchor-id="functions">Functions</h2>
<p>It would be extremely annoying if we had to enter the time everywhere it appears in the trajectory formula whenever we want to determine the mass position. One approach to let the program calculate for us by defining the function <img src="https://latex.codecogs.com/png.latex?y(t)"> as a python function. There are two basic ways to define a function in python. Through the so called lambda functions, one has</p>
<div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1">y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> t: y0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> v0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> t <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> t<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span></code></pre></div>
<p>the general structure of a lambda function is <code>'function name' = lambda 'arguments': 'python expression'</code>. To calculate the function value we can simply type <code>y(3)</code>, <code>y(1.5)</code>, … Test the output values in a new cell for several values of <code>t</code>. Notice that the function contains <code>y0</code>, <code>v0</code> and <code>a</code> which are variables stored in memory. Try to change the values of these variables and see how they affect <code>y(t)</code>. While here we are considering a function of a single argument (<img src="https://latex.codecogs.com/png.latex?y=y(t)">), it’s possible to have multiple arguments too. For example, suppose that we want to consider the height at a time <img src="https://latex.codecogs.com/png.latex?t"> for a particle that starts at <img src="https://latex.codecogs.com/png.latex?y(0)=0"> and allow the initial velocity to change. We may define a more specific function to this problem</p>
<div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1">y2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> t, v0y: v0y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> t <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">9.8</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> t<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span></code></pre></div>
<p>Thus, if we want to consider this second scenario, we may use python to call <code>y2(1, 10)</code> to know the particle height at <code>t=1</code> s and with an initial velocity of <code>10</code> m/s. <strong>Notice the ordering</strong>: the first number indicates the value of <code>t</code>, while the second number indicates the value of <code>v0y</code>. Another possibility is to use a variable to set the argument values, as in <code>y2(2, v0)</code>. We may also use <code>y2(3.5, 13.2)</code> to consider the particle height at <code>3.5</code> s given an initial velocity of <code>13.2</code> m/s. Notice also that the <strong>comma is an argument separator</strong> (separates the arguments <code>t</code> and <code>v0y</code>), while the <strong>period is a decimal separator</strong> in python. Thus, if one tries to type a number with the comma as a decimal separator it will lead to an unexpected behavior (may even trigger error messages). For example, <code>y2(3,5, 13,2)</code> will send four arguments (<code>3</code>, <code>5</code>, <code>13</code> and <code>2</code>) to <code>y2</code>, while <code>y2</code> accepts only two arguments (<code>t</code> and <code>v0y</code>). Calling <code>y2(3,5, 13,2)</code> will lead to an error message.</p>
<p>Sometimes the function definition through lambda functions as above is not very adequate, because Python functions are more general than mathematical functions and can also be used to request the computer to perform a more complex set of tasks. For instance, suppose that we want to know simultaneously both the particle height and velocity with a single function. We may define a function as</p>
<div class="sourceCode" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> parabolic_motion(t, v0y):</span>
<span id="cb12-2">  yt <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> v0y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> t <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">9.8</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> t<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb12-3">  vt <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> v0y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">9.8</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> t</span>
<span id="cb12-4">  <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'at t='</span>, t, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">', y(t)='</span>, yt,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">', v(t)='</span>, vt)</span>
<span id="cb12-5">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> yt, vt</span>
<span id="cb12-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Function ends where indentation ends</span></span>
<span id="cb12-7"></span>
<span id="cb12-8">final_height, final_velocity <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> parabolic_motion(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>)</span></code></pre></div>
<p>Test the above code. After the line <code>def ...</code> there are several <strong>instructions, which must be indented</strong> (that is, each line starts with two spaces or more, or a TAB key press). The same indentation that you use in the first line must be used in the following ones within the function. When the indentation stops it means that the instructions that should be performed by the function have ended. Given a time <code>t</code> and initial velocity <code>v0y</code>, it will compute the height and store it in <code>yt</code>, then it will compute the particle velocity and store it in <code>vt</code>. Then, it will print to the user a string informing the current time, height and velocity. <code>print</code> accepts several arguments, where some of them are strings (text between quotes) and the others are variables. Always remember that <strong>commas are used to separate expressions or arguments</strong>. Finally the <code>return</code> instruction will send the values of <code>yt</code> and <code>vt</code> as the function output. Thus, the above steps will be carried sequentially and the function will return two numbers that can be attributed to other variables. For instance, <code>final_height, final_velocity = parabolic_motion(5, 15)</code> will set <code>final_height=-47.5</code> and <code>final_velocity=-34</code>. The general structure is</p>
<div class="sourceCode" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'function name'</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'arguments'</span>):</span>
<span id="cb13-2">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'indented instructions'</span></span>
<span id="cb13-3">  ...</span>
<span id="cb13-4">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> output</span>
<span id="cb13-5">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Function 'function name' ends here.</span></span>
<span id="cb13-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># The program instructions follow unindented below</span></span></code></pre></div>
</section>
<section id="advanced-math-and-arrays" class="level2">
<h2 class="anchored" data-anchor-id="advanced-math-and-arrays">Advanced math and arrays</h2>
<p>The previous concepts can be used to define some simple mathematical functions, as polynomials. However, we often need a broader set of functions in our calculations. For instance, we may need trigonometric, hyperbolic, exponential or logarithmic functions. Also, we may need to use constants as <img src="https://latex.codecogs.com/png.latex?%5Cpi"> or <img src="https://latex.codecogs.com/png.latex?e">. There are basically two ways to introduce such functions in a python program. The first one is through the native <code>math</code> <a href="https://docs.python.org/3/library/math.html">library</a>. In programming, a library represents a set of functions (or objects) that solve some set of problems. To use a given library, we may use the <code>import 'library'</code> instruction. To call a given library function or constant, it’s possible to use a syntax like <code>'library'.'function'</code>, or <code>'library'.'constant'</code>.</p>
<div class="sourceCode" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> math</span>
<span id="cb14-2"></span>
<span id="cb14-3"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(math.sin(math.pi<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span></code></pre></div>
<pre><code>1.0</code></pre>
<p>To consult the available constants, functions and other python objects, one may consult the <a href="https://docs.python.org/3/library/math.html">math library documentation</a>, or use some autocompletion features in the editor. For instance, if you type a period after math, <code>math.</code>, and press the <code>TAB</code> key, then the interface will display a menu containing the available properties. For instance, <code>math.si</code>+<code>tab</code> shows <code>math.sin</code> and <code>math.sinh</code> as options. Since these are functions, we may add the parenthesis to begin the function call. To see how these functions operate, its possible to use Jupyter notebook’s tooltip feature. Consider <code>math.sin(</code> and type <code>Shift+Tab</code>. A documentation regarding the syntax and usage of that function will be readily available.</p>
<p>While the above possibility is very general and can be used to import other libraries, the Jupyter notebook can perform a <a href="http://ipython.readthedocs.io/en/stable/interactive/magics.html">magic</a> that automatically simplifies enormously the syntax of complex mathematical expressions. One of the most convenient is the <code>%pylab</code> magic, which I recommend calling only once at the beginning cell of a notebook. Type in some cell</p>
<div class="sourceCode" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>pylab inline</span></code></pre></div>
<p>the <code>inline</code> option is related with the tool that we will use later to plot curves. After the <code>%pylab inline</code> magic is called, we may calculate the sine more clearly:</p>
<div class="sourceCode" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(sin(pi<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span></code></pre></div>
<pre><code>1.0</code></pre>
<p>Python is also able to handle complex numbers natively. The imaginary number is <code>1j</code>, and one can easily obtain results as the Euler’s identity: <img src="https://latex.codecogs.com/png.latex?e%5E%7B%5Cjmath%20%5Cpi%7D%20+%201%20=%200"> is verified within the calculation precision,</p>
<div class="sourceCode" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb19-1">exp(<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">1j</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> pi) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span></code></pre></div>
<pre><code>1.2246467991473532e-16j</code></pre>
<p>A remark on numeric notation in python. In a number, <code>e</code> indicates the exponentiation over a base 10. Thus <code>1e1==10</code>, <code>1e2==100</code>, <code>-1.5e-2==-0.015</code>. The smallest number that can be accurately calculated is called epsilon and can be obtained from <code>sys.float_info.epsilon</code>. My machine’s <code>epsilon</code> is <code>2.220446049250313e-16</code>. Since this is the smallest increment/decrement that can be calculated, some calculations suffer from accuracy with such small numbers and the expressions should be normalized. Numerical calculations may also involve infinity (for example, <code>log(0)==-float('inf')</code>) while another important symbol is not a number, <code>NaN</code>, which is returned for undefined operations as <img src="https://latex.codecogs.com/png.latex?%5Cinfty%20-%20%5Cinfty">, or <code>float('inf') - float('inf') == float('nan')</code>.</p>
<p>When using complex numbers, there are several auxiliary functions available. For example, if we have <code>c = sqrt(3)/2 + 1j * 1/2</code>, we may compute the real and imaginary parts of <code>c</code> simply from <code>real(c)</code> and <code>imag(c)</code>. The absolute value of <code>c</code> is <code>abs(c)</code>, while the angle (in radians) between <code>c</code> and the real axis in the complex plane is <code>angle(c)</code>. This angle is limited to the domain <img src="https://latex.codecogs.com/png.latex?%5B-%5Cpi,%5Cpi%5D">.</p>
<!--- Create a table containing those functions which are used mostly --->
<p>The <code>%pylab</code> magic does not use the standard python math library. Instead, it uses the <a href="https://docs.scipy.org/doc/numpy/reference/routines.math.html">Numpy library</a>, which has much more capabilities. Numpy contains a large set of tools to handle numerical data, from matrix operations to fast Fourier transforms. It’ worthwhile to comment that python is a great language to code with, because it’s fast to create and test pieces of code. However, <em>this increased facility comes at a cost in processing time when python code is used directly</em>. Numpy implements several important numerical procedures using other languages<sup>2</sup> that process data much faster than native python. <strong>When crunching numbers, use Numpy/Scipy methods as much as possible</strong>. <a href="http://www.scipy.org">Scipy</a> is another library which contains several applications of Numpy to a multitude of science-related problems.</p>
<p>Quite often one has to deal with functions defined within a certain range of variable values, a finite domain. The Numpy library has two main auxiliary functions that allow us to define this domain for mathematical functions, <code>arange</code> and <code>linspace</code>. <code>arange([start], stop, [step])</code> indicates an array of integer numbers starting from <code>start</code> (which is an optional argument, <code>0</code> by default) to <code>stop</code>, in equally separated <code>step</code> steps (optional, <code>step=1</code> if not given). Notice that <code>arange</code> does not include the <code>stop</code> as a value in the array. This is sometimes useful, but must always be remembered. In the code below, <code>x</code> starts at <code>2</code> and increases in steps of <code>2</code>, until the array value is lesser than the <code>stop=9</code> value. This will produce an array containing the even numbers from <code>2</code> to <code>8</code>. <code>y</code> contains the positive integers (including <code>0</code>) lesser than stop (remember that the default <code>step</code> is <code>1</code>). It’s also possible to produce an array of fractional values with a given spacing, as in <code>z</code>.</p>
<div class="sourceCode" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb21-1">x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> arange(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb21-2">y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> arange(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span>
<span id="cb21-3">z <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> arange(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, step<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>)</span>
<span id="cb21-4">x, y, z</span></code></pre></div>
<pre><code>(array([2, 4, 6, 8]),
 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
 array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9]))</code></pre>
<p>While <code>arange</code> does not include the final point and one must define the spacing between values, <code>linspace(start, stop, num)</code> takes another approach. It will create an array of values between <code>start</code> and <code>stop</code>. The endpoint is included by default. <code>num</code> indicates how many points the array must have between <code>start</code> and <code>stop</code>, and is quite useful to increase or decrease the resolution in which a given function is represented in a given domain. The definition os a given step as in <code>arange</code> can be less intuitive when we want to represent functions in different domains. <code>linspace</code> is more adequate for fractional spacing than <code>arange</code>.</p>
<div class="sourceCode" id="cb23" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb23-1">x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span>
<span id="cb23-2">y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span>
<span id="cb23-3">z <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)</span>
<span id="cb23-4">x, y, z</span></code></pre></div>
<pre><code>(array([ 0.        ,  0.11111111,  0.22222222,  0.33333333,  0.44444444,
         0.55555556,  0.66666667,  0.77777778,  0.88888889,  1.        ]),
 array([  0.,   5.,  10.]),
 array([  0. ,   2.5,   5. ,   7.5,  10. ]))</code></pre>
<p>Notice that now <code>x</code> contains an array of <code>10</code> values and includes the endpoints. Considering that the number of intervals is <code>num-1</code>, the spacing between subsequent points is <code>(stop-start)/(num-1)</code>. Notice <code>num</code> represents the number of point in the array, and to obtain intervals with a given sort of regular spacing, as <code>w=(stop-start)/divisor</code>, one must use <code>num = divisor + 1</code>.</p>
<p>The output of <code>arange</code> and <code>linspace</code> are <code>array</code> objects, which is the basic way that Numpy uses to handle sets of numbers. If we want to define arrays over a given set of values, we may also use the following syntax</p>
<div class="sourceCode" id="cb25" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb25-1">a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> array([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">13</span>])</span>
<span id="cb25-2">b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> array([<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">52</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>])</span>
<span id="cb25-3">c <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> array([ <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">2j</span>, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">1j</span>])</span>
<span id="cb25-4">a, b, c</span></code></pre></div>
<pre><code>(array([ 1,  2,  3,  5,  7, 11, 13]),
 array([  0.1,   0.3,   0. , -52. ,  42. ]),
 array([ 1.+0.j,  1.+2.j, -3.+0.j, -1.-1.j]))</code></pre>
<p>The set of numbers separated by commas within square brackets <code>[1, 2, ...,]</code> is a Python list, which is a python object that can be used to store ordered information. Beware that the order in which the data is added is retained. Also, notice that if one adds complex numbers the array automatically considers that all numbers in the array are complex. Each element in the list is associated with an index used to locate such element. To access the elements of the list <code>x = ['a', 'b', 42, [-5, 1j] ]</code> we can use <code>x[i]</code>, where <code>i</code> ranges from <code>0</code> to <code>3</code>. In particular, <code>x[0]=='a'</code>, <code>x[1]=='b'</code>, <code>x[2]==42</code> and <code>x[3]==[-5, 1j]</code>.</p>
<p>A great aspect of arrays is that one may easily perform calculations over them. For instance, we may create an array with even numbers from 0 to 10 using an <code>arange</code>. <code>arange(6)</code> creates the array <code>[0, 1, 2, 3, 4, 5]</code>, while the multiplication by <code>2</code> multiply each value individually.</p>
<div class="sourceCode" id="cb27" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb27-1"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>arange(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>)</span></code></pre></div>
<p>All of the basic operations (<code>+, -, *, /, **</code>) and the Numpy functions can be calculated over each value in the array. Thus, consider that we want to calculate the values of a linear function, <img src="https://latex.codecogs.com/png.latex?y(x)=%202%20+%2015%20x%20-%205%20x%5E2">. The Numpy array is such that if we have an array <code>x</code> and we call <code>y = 2 + 15 * x - 5 * x**2</code>, then <code>y</code> will be another array that contains the result of the calculation of the right-hand side expression <strong>for each value of</strong> <code>x</code>. Numpy will get each value of <code>x</code> in the array, evaluate the mathematical expression, and return the output value to <code>y</code> at the corresponding <code>x</code> value position. An important aspect is that Numpy evaluates the native mathematical functions and expressions quite efficiently, and since the python expression can look like the mathematical function that we want to calculate, it’s easy to check for errors.</p>
<div class="sourceCode" id="cb28" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb28-1">x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>)</span>
<span id="cb28-2">y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb28-3">x, y</span></code></pre></div>
<pre><code>(array([ 0. ,  0.5,  1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ,  4.5,  5. ]),
 array([  2.  ,   8.25,  12.  ,  13.25,  12.  ,   8.25,   2.  ,  -6.75,
        -18.  , -31.75, -48.  ]))</code></pre>
<p>The above code represents the set of (x, y) values that satisfy the relationship expected for the function <img src="https://latex.codecogs.com/png.latex?y(x)">. However, it would be much nicer if we could see this in a graphical representation, as we’ll see just below. To finish this section, we may notice that we may use functions to calculate these results.</p>
<div class="sourceCode" id="cb30" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb30-1">x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>)</span>
<span id="cb30-2">y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> t: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> t <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> t<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb30-3">x, y(x)</span></code></pre></div>
<pre><code>(array([ 0. ,  0.5,  1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ,  4.5,  5. ]),
 array([  2.  ,   8.25,  12.  ,  13.25,  12.  ,   8.25,   2.  ,  -6.75,
        -18.  , -31.75, -48.  ]))</code></pre>
<p>Notice that <code>y</code> is a <code>lambda</code> function that has a generic argument <code>t</code>, instead of <code>x</code> directly. An advantage of the function definition above is that now it is possible to evaluate the function <code>y(t)</code> over distinct Numpy arrays, and we don’t have to rewrite everything. For example, suppose that somewhere else we want to evaluate <code>y</code> over a larger domain <code>z</code> and at a higher resolution. We may use simply</p>
<div class="sourceCode" id="cb32" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb32-1">z<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>linspace(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)</span>
<span id="cb32-2">z, y(z)</span></code></pre></div>
</section>
<section id="basic-curve-plotting" class="level2">
<h2 class="anchored" data-anchor-id="basic-curve-plotting">Basic curve plotting</h2>
<p>Obtaining a list of calculated values is very important, since the computer can calculate very fast and efficiently. However, it’s often easier to understand data if we can visualize it in a graphic. The <a href="https://matplotlib.org/gallery.html">matplotlib package</a> contains several tools to produce high-quality data plots (both in 2D and 3D). Another interesting aspect is that matplotlib contains several <a href="https://matplotlib.org/gallery.html">examples</a> which are useful under several data plotting contexts. For us, we will see some of the most basic capabilities.</p>
<p>In the previous section, we calculated <img src="https://latex.codecogs.com/png.latex?y(x)=%202%20+%2015%20x%20-%205%20x%5E2"> for <img src="https://latex.codecogs.com/png.latex?x%5Cin%20%5Cleft%5B0,%205%5Cright%5D">. This function can be graphically represented with the simple command <code>plot(x, y)</code></p>
<div class="sourceCode" id="cb33" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb33-1">x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>)</span>
<span id="cb33-2">y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb33-3">plot(x, y)</span>
<span id="cb33-4">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'assets\pes_parabola_plot1.png'</span>)</span></code></pre></div>
<p><img src="https://amamaral.github.io/blog/assets/pes_parabola_plot1.png" class="img-fluid"></p>
<p>The function <code>savefig(r'assets\pes_parabola_plot1.png')</code> saves the current matplotlib graphic in the external file <code>pes_parabola_plot1.png</code> located in the folder <code>assets</code>. The folder must exist before the file is written! Several output graphics file formats are supported, and this is useful to include the analyzed data in other documents (for example in Word, LaTeX,…). Notice that the above plot has some sharp corners, which are due to the small number of points used to represent <img src="https://latex.codecogs.com/png.latex?y(x)">. We can improve the graphic resolution by changing the number of points in the <code>x</code> array:</p>
<div class="sourceCode" id="cb34" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb34-1">x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">101</span>)</span>
<span id="cb34-2">y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb34-3">plot(x, y)</span>
<span id="cb34-4">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'assets\pes_parabola_plot2.png'</span>)</span></code></pre></div>
<p><img src="https://amamaral.github.io/blog/assets/pes_parabola_plot2.png" class="img-fluid"></p>
<p>A typical scientific plot has several features, as a title, axis labels and maybe a legend, to indicate what is represented in each curve. In the example below we can see how to show several curves and add some of these features</p>
<div class="sourceCode" id="cb35" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb35-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Parabola representation with a low resolution</span></span>
<span id="cb35-2">x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)</span>
<span id="cb35-3">y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb35-4">plot(x, y, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'--'</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"low res."</span>)</span>
<span id="cb35-5">plot(x, y, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'.'</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"low res. points"</span>)</span>
<span id="cb35-6"></span>
<span id="cb35-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Parabola representation with a high resolution</span></span>
<span id="cb35-8">x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">101</span>)</span>
<span id="cb35-9">y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb35-10">plot(x, y, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'-'</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"high res."</span>)</span>
<span id="cb35-11"></span>
<span id="cb35-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Plot properties</span></span>
<span id="cb35-13">title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'$y(x)= 2 + 15 x - 5 x^2$'</span>)</span>
<span id="cb35-14">xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x (m)'</span>)</span>
<span id="cb35-15">ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y (m)'</span>)</span>
<span id="cb35-16">legend() <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Use legends</span></span>
<span id="cb35-17">grid() <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Use grid</span></span>
<span id="cb35-18"></span>
<span id="cb35-19">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'assets\pes_parabola_plot3.png'</span>)</span></code></pre></div>
<p><img src="https://amamaral.github.io/blog/assets/pes_parabola_plot3.png" class="img-fluid"></p>
<p>The <code>plot</code> function accepts several arguments, and its complete description is given in the <a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html">documentation</a>. The string after the <code>x</code> and <code>y</code> data is used to set the curve format properties (color, line type, markers…). In the above example we set the line type as dashed (<code>--</code>), dotted (<code>.</code>) or a solid line (<code>-</code>, the default). It is also possible to associate a symbol to each pair of <code>x,y</code> data coordinates, some common ones being <code>o, *, +, x</code> that respectively generate the symbols <img src="https://latex.codecogs.com/png.latex?%5Cbullet,%20*,%20+,%20%5Ctimes">. The color changes automatically, but can also be selected in the format string. To identify each curve in the plot, we label each curve. These labels only appear when <code>legend()</code> is called. The location of <code>legend</code> can be set by using the argument <code>loc=</code> (See <a href="https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend">documentation</a>). <code>title</code>, <code>xlabel</code> and <code>ylabel</code> are used to set the plot title and horizontal and vertical axis labels. A nice feature is that matplotlib accepts LaTeX typeset formulas in its labels (check the <a href="https://en.wikibooks.org/wiki/LaTeX/Mathematics">LaTeX wikibook</a>).</p>
<div class="sourceCode" id="cb36" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb36-1">x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">101</span>)</span>
<span id="cb36-2">y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pi <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb36-3">plot(x, y)</span>
<span id="cb36-4"></span>
<span id="cb36-5">title(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'$y(x)=\pi+\int_0^x \left(15 - \frac</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{20}{2}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;"> t\right) dt$'</span>)</span>
<span id="cb36-6">xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x (m)'</span>)</span>
<span id="cb36-7">ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y (m)'</span>)</span>
<span id="cb36-8"></span>
<span id="cb36-9">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'assets\pes_parabola_plot4.png'</span>)</span></code></pre></div>
<p><img src="https://amamaral.github.io/blog/assets/pes_parabola_plot4.png" class="img-fluid"></p>
<p>In the above plot the title contains terms as the integral operator <img src="https://latex.codecogs.com/png.latex?%5Cint%5Crightarrow"><code>\int</code> and the greek letter <img src="https://latex.codecogs.com/png.latex?%5Cpi%5Crightarrow"><code>\pi</code>. LaTeX formulas must be within a string and enclosed by dollar signs <code>$</code>. Quite often these strings can be misinterpreted by python, given that <code>\</code> is used in strings to describe some special characters. Thus, <strong>when typing latex formulas one must define <code>raw</code> strings by adding the character r immediately before quotes in the formula-containing string</strong>. Quite often we want to write sub or superscripts in our expressions, and the Latex notation is very simple. <img src="https://latex.codecogs.com/png.latex?x_1"> can be written as <code>$x_1$</code>, or a more general subscript must be enclosed between curly brackets, <img src="https://latex.codecogs.com/png.latex?%5Cpsi_%7B1,2,3%7D%5Crightarrow"><code>$\psi_{1,2,3}$</code>. The superscripts are similar, typical examples being <img src="https://latex.codecogs.com/png.latex?e%5E%7B-x%5E2%7D%5Crightarrow"><code>$e^{-x^2}$</code> or <img src="https://latex.codecogs.com/png.latex?2%5E%7B2%5E2%7D%5Crightarrow"><code>$2^{2^2}$</code>.</p>
<p>To finish this section, we consider a few difficult function calculations. Notice that the same <code>x</code> array is used to represent all functions.</p>
<div class="sourceCode" id="cb37" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb37-1">x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">201</span>)</span>
<span id="cb37-2"></span>
<span id="cb37-3">y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> sin(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>x) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> exp(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>x)</span>
<span id="cb37-4">plot(x, y, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'$3 \sin(6x) e^{-x}$'</span>)</span>
<span id="cb37-5"></span>
<span id="cb37-6">y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.9</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> sqrt(sin(x)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> cos(x)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb37-7">plot(x, y, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">':'</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'$- 0.9 \sqrt{\sin^2(x) + cos^2(x)}$'</span>)</span>
<span id="cb37-8"></span>
<span id="cb37-9">y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">abs</span>(x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)</span>
<span id="cb37-10">plot(x, y, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'--'</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'$|x-5|$'</span>)</span>
<span id="cb37-11"></span>
<span id="cb37-12">y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> log(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb37-13">plot(x, y, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'-.'</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'$\log\left(2x + 1\right)$'</span>)</span>
<span id="cb37-14"></span>
<span id="cb37-15">title(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'Several mathematical functions'</span>)</span>
<span id="cb37-16">legend()</span>
<span id="cb37-17">xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>)</span>
<span id="cb37-18">ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y'</span>)</span>
<span id="cb37-19"></span>
<span id="cb37-20">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'assets\pes_plots_example.png'</span>)</span></code></pre></div>
<p><img src="https://amamaral.github.io/blog/assets/pes_plots_example.png" class="img-fluid"></p>
</section>
<section id="summary" class="level2">
<h2 class="anchored" data-anchor-id="summary">Summary</h2>
<p>In the present tutorial we have seen how to install Python and the Jupyter notebook, how to use Python to calculate simple expressions, a brief introduction to python variables and functions, Numpy mathematical tools and how to use matplotlib to plot Numpy arrays and numerical functions. In the following part we will see how to analyze experimental data in Jupyter notebook.</p>
<!---

NOTA: Acho que vale a pena colocar a parte de iteráveis (list, tuple e dict) bem como algumas instruções gerais sobre loops aqui. Assim esse capítulo dá uma visão geral sobre a programação em python e sua sintaxe. Essa parte de storing data in lists anda array acho que pode ser suprimida tendo em vista o novo material sobre o uso do pandas no próximo capítulo.

NOTA2: Outra limitação importante desse texto resumido é que ele não ensina como lidar com erros e problemas de sintaxe... No caso do livro seria muito importante adicionar esses conceitos.

## Storing data in lists and arrays

As seen in the [part I](python_for_experimental_sciences_part_1.html), we may store ordered data in a list or a numpy array. Here we will discuss a bit more on how to manipulate this data. Let's create an artificial dataset due to a function $y=x^2$. The array `y` contains the exact function, while `ydata` simulates experimental data, by adding a noise contribution. Measurements always have some noise, which we will add artificially with the `randn` function. Noise typically follows a [Gaussian distribution](https://en.wikipedia.org/wiki/Normal_distribution), and `randn` produces such distribution with mean `0` and width `1`. To adjust the noise amplitude we multiply `randn` by `0.5`. If `randn` is called without arguments, it returns a single random number. We want to add an artificial noise to each `x` value, we have to inform `randn` how many normally distributed random numbers it must generate. This can be achieved with the help of `len(x)`, which indicates how many entries there are in the `x` array. **It is a good practice to not use static numbers (as the `num=10` argument given in `linspace`) directly**, but some dynamic approach as using `len(x)` or `x.shape[0]` (which also indicates how many elements there are along the array's first dimension). **The program will result in an error with a static approach whenever the length of the dataset changes** (ex.: we have instead that `x = linspace(0, 6, 20)`). Change the number of values in `x` and see that the code below still works. Later change `len(x)` in the code below to `13` or a different number to see the error message. To represent experimental data in a plot we often represent each measurement with a point, and the `ydata` plot format string `'k.'` indicates that this dataset should be represented by black (`k`) points (`.`).

~~~{.python}
%pylab inline
x = linspace(0, 6, 10)
y = x**2
ydata = x**2 + 0.5 * randn(len(x))

plot(x, y)
plot(x, ydata, 'k.')
savefig(r'assets\pes_artificial_dataset.png')
~~~

![](/blog/assets/pes_artificial_dataset.png)

## Iterables and loops

Now that the good practice on calculating functions with python arrays has been established, we can talk about some bad python practices^[Actually the calculation approaches given below are the standard way to compute in other languages, as C/C++/Fortran. However, the increased flexibility of python with respect to those other languages leads to a slower execution of these "standard" routines. Numpy implements calculations like those below under the hood.]  to calculate function values. While for pure function evaluation these techniques are bad in python, they increase the flexibility and can be useful to perform more general operations during the calculation.

### Lists and tuples
### Numpy arrays
### Sets (?), Dicts and ordered dicts

--->
<!--- PART 2 - Experimental data analysis in 1D

## Data modelling
## Fitting experimental parameters

## An example: a diode current-voltage curve (REMOVED! Use this as an example/exercise???)

## Using Jupyter notebook for scientific writing

## Data storage in a csv or an xml file
## Reading experimental data
### Some caveats (`.` or `,` in datafiles, ...)
### Iterables and loops (Lists, Dicts, Tuples, Arrays)

## Rename tutorial series as Python for experimental science (???)

--->
<!--- Future topics

## Brief insights to numerical solutions of physical problems: Derivatives, integrals and differential equations
## Symbolic manipulation using Sympy
## Communications with instruments using pyvisa (communication with arduino/oscilloscopes??)
## Creation of Python executable programs - Using the Spyder IDE
## Graphical user interfaces to control scientific experiments

## Finite state machines and OOP
## Noise and data filtering

From here on, if more content is thought, it must always be remembered that there will be already a large set of concepts exploited in the previous tutorials. This is important to remember, since increasing the rigor and the details can be interesting to craft a book. Another aspect to keep in mind is that these ideas can be complemented to grow the set of applications. For instance, consider a set of chapters where python programs are considered to solve mechanics, thermodynamics...

Added later: An interesting addition is to talk about evolutionary algorithms (specially genetic algorithm), machine learning and neural networks as applications for physics. The concept is to discuss some generic intro and then show how to implement these concepts in some relevant problems. Below are given some problems with direct physical relevance. Meanwhile,

# Brief introduction to evolutionary algorithms and machine learning
## Intro - Imperative algorithms vs Evolutionary algorithms and machine learning

Is it interesting to speak a little about statistics? Maybe an appendix or a chapter before... There is a nice book at http://theoryandpractice.org/stats-ds-book/intro.html (jupyter book gallery) which covers some interesting topics related to statistics, physics and applications of scikit-learn libs (I think)

An interesting guide can be found at https://github.com/louisfb01/start-machine-learning-in-2020

## Genetic Algorithms
### Data fitting using GA (it's interesting to show how it improves w.r.t. pure least squares)
### Multilayer thin-film optimization (how to obtain the best combination of fabrication layers). Another possibility is to develop analog filter circuits.
#### Increased difficulty: add fabrication tolerances!
## Neural networks
### Simple NN
#### Classify experimental data type (power lqw, exp, log, linear, polynomial, sine, damped sine...)
#### Classify how many Lorentzian peaks are there in a spectral curve
### CNNs
#### Look for some image manipulation and feature extraction examples

--->


</section>
</section>


<div id="quarto-appendix" class="default"><section id="footnotes" class="footnotes footnotes-end-of-document"><h2 class="anchored quarto-appendix-heading">Footnotes</h2>

<ol>
<li id="fn1"><p><em>Always</em> is always a tricky word. Commas are understood as text within strings. Ex.: <code>"This is good, isn't it?"</code>. However, since we’re mainly considering numerical manipulations in such a short manuscript, we’re reinforcing the usage of commas in python syntax.↩︎</p></li>
<li id="fn2"><p>mainly <a href="https://en.wikipedia.org/wiki/C%2B%2B">C/C++</a> and <a href="https://en.wikipedia.org/wiki/Fortran">Fortran</a>↩︎</p></li>
</ol>
</section></div> ]]></description>
  <category>python</category>
  <category>experimental physics</category>
  <category>data analysis</category>
  <guid>https://amamaral.github.io/blog/posts/python-for-experimental-sciences-1/</guid>
  <pubDate>Mon, 14 May 2018 00:00:00 GMT</pubDate>
  <media:content url="https://amamaral.github.io/blog/assets/pes_parabola_plot1.png" medium="image" type="image/png" height="96" width="144"/>
</item>
<item>
  <title>RC filter cutoff frequency optimization</title>
  <dc:creator>Anderson M. Amaral</dc:creator>
  <link>https://amamaral.github.io/blog/posts/rc-filter-cutoff-optimization/</link>
  <description><![CDATA[ 




<p>Given that one has some electronic signal added with noise, how do we select the filter cut-off frequency such that we can eliminate most of the noise while retaining most of the signal? In other words, we intend to enhance the signal to noise ratio. This can be very useful in arduino and electronics projects in general. <strong>Long story short</strong>, it is shown that the filter cutoff (3 dB point) should be chosen at the signal frequency under quite general circumstances, both for high-pass and low-pass filters.</p>
<p>We will consider the following scenario:</p>
<ul>
<li>There is a signal whose frequency is <img src="https://latex.codecogs.com/png.latex?f_s=1000"> Hz</li>
<li>The noise is mostly at smaller frequencies. Ex.: <img src="https://latex.codecogs.com/png.latex?f_n=100"> Hz would be an upper bound to the noise due to the power lines.</li>
<li>The filter cut-off frequency is <img src="https://latex.codecogs.com/png.latex?f_c"> and we want to determine “the best”</li>
</ul>
<p>For simplicity we will consider a first-order RC filter (1 Resistor, 1 Capacitor). Given that the signal has a higher frequency than the noise, it seems more interesting to use a <a href="https://en.wikipedia.org/wiki/High-pass_filter" title="See more in wikipedia">high-pass filter</a>, which transmits better signals at higher frequencies. A schematic of such filter is shown below:</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://amamaral.github.io/blog/assets/rc-high-pass.svg" class="img-fluid figure-img"></p>
<figcaption>A first-order high-pass RC filter</figcaption>
</figure>
</div>
<p>The signal comes in as <img src="https://latex.codecogs.com/png.latex?V_i">, and <img src="https://latex.codecogs.com/png.latex?V_o"> is the filter output.</p>
<section id="high-pass-filter-analysis" class="level2">
<h2 class="anchored" data-anchor-id="high-pass-filter-analysis">High-pass filter analysis</h2>
<p>How much of a signal at a frequency <img src="https://latex.codecogs.com/png.latex?f"> passes through a high-pass filter whose cut-off frequency is <img src="https://latex.codecogs.com/png.latex?f_c">? The fraction of the signal that is allowed to pass through the filter is informed by the transfer function <img src="https://latex.codecogs.com/png.latex?T">. For a first-order high-pass filter, <img src="https://latex.codecogs.com/png.latex?T(f,f_c)=%5Cfrac%7Bf%7D%7Bf-jf_c%7D,"> where <img src="https://latex.codecogs.com/png.latex?j"> is the imaginary unit, <img src="https://latex.codecogs.com/png.latex?j%5E2=-1">.</p>
<p>We want the most of the a signal whose frequency is <img src="https://latex.codecogs.com/png.latex?f_s">, while blocking most of the noise at <img src="https://latex.codecogs.com/png.latex?f_n">. In other words, we’re interested in the amplitude of both signal and noise after the filter. The amplitude of a filtered signal at a frequency <img src="https://latex.codecogs.com/png.latex?f"> is given by <img src="https://latex.codecogs.com/png.latex?%7CT(f,f_c)%7C=%5Cfrac%7Bf%7D%7B%5Csqrt%7Bf%5E2+f_c%5E2%7D%7D."></p>
<p>Now we know the fraction of the signal and noise which are allowed to pass through the filter. Let us consider which value of <img src="https://latex.codecogs.com/png.latex?f_c"> must be chosen. If <img src="https://latex.codecogs.com/png.latex?f_c"> is too small, then both signal and noise have a “high frequency” and are allowed to pass. On the other hand, if <img src="https://latex.codecogs.com/png.latex?f_c"> becomes too large, then both signal and noise have a “low frequency” and thus the filter removes the information of interest. There must be some optimal value for <img src="https://latex.codecogs.com/png.latex?f_c"> under some appropriate constraints.</p>
<p>In the plot below there are considered the relative amounts of signal at 1 kHz (blue) and noise at 100 Hz (orange) after the filter, as a function of the filter cutoff frequency <img src="https://latex.codecogs.com/png.latex?f_c">. The high-pass filter is useful only between <img src="https://latex.codecogs.com/png.latex?10%5E1%20%5Cleq%20f_c%20%5Cleq%2010%5E5">. For frequencies outside this range, the filter does not discriminate signal and noise from each other.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://amamaral.github.io/blog/assets/sn_ratio_hpf.svg" class="img-fluid figure-img"></p>
<figcaption>Transfer curves for signal (blue) and noise (orange). Signal to noise transfer ratio (green)</figcaption>
</figure>
</div>
<p>We want that the output does not affect the signal by much, while it attenuates the noise. To achieve this we may consider a figure-of-merit <img src="https://latex.codecogs.com/png.latex?S/N"> which is proportional to the signal transfer and inversely proportional to the noise transfer. More signal and less noise should increase this figure. A simple calculation shows that <img src="https://latex.codecogs.com/png.latex?S/N%20=%20%5Cfrac%7B%7CT(f_s,f_c)%7C%7D%7B%7CT(f_n,f_c)%7C%7D%20=%20%5Cfrac%7Bf_s%7D%7Bf_n%7D%20%5Cfrac%7B%5Csqrt%7Bf_n%5E2+f_c%5E2%7D%7D%7B%5Csqrt%7Bf_s%5E2+f_c%5E2%7D%7D"></p>
<p><img src="https://latex.codecogs.com/png.latex?S/N"> is shown in the plot above as the green curve. Notice that if <img src="https://latex.codecogs.com/png.latex?f_c%5Capprox%20f_s"> then the signal attenuation is relatively small, but the <img src="https://latex.codecogs.com/png.latex?S/N"> ratio is appreciable. Indeed this makes sense, given that to get rid of low frequency noise it’s necessary to have a filter with the highest available cutoff. Meanwhile, the highest cutoff which does not affect the signal by much is precisely when <img src="https://latex.codecogs.com/png.latex?f_c=f_s">.</p>
</section>
<section id="figure-of-merit-edit" class="level2">
<h2 class="anchored" data-anchor-id="figure-of-merit-edit">Figure-of-merit (Edit)</h2>
<p>Another approach to characterize the effectiveness of the filter is through the definition of a figure of merit, that increases when the signal increases at the output, while it also increases for an enhanced <img src="https://latex.codecogs.com/png.latex?S/N"> ratio. This quantity would be <img src="https://latex.codecogs.com/png.latex?FOM=(S/N)%20%7CT(S)%7C%20=%20%5Cfrac%7B%7CT(f_s,f_c)%7C%5E2%7D%7B%7CT(f_n,f_c)%7C%7D">. Below we show how the FOM depends on frequency for the above filter. The proposed FOM makes it clearer that the filter must be at the signal frequency.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://amamaral.github.io/blog/assets/sn_ratio_fom.svg" class="img-fluid figure-img"></p>
<figcaption>Figure-of-merit(FOM) of a high-pass filter</figcaption>
</figure>
</div>
</section>
<section id="summary" class="level2">
<h2 class="anchored" data-anchor-id="summary">Summary</h2>
<p>The above analysis is simplified but valid under various circumstances. When selecting the cutoff frequency of a given filter one must first consider to put this frequency as close as possible from the signal frequency, but not larger. However, if the total noise signal becomes negligible at smaller <img src="https://latex.codecogs.com/png.latex?f_c"> values, then such values are preferred given that less signal will be lost. Also, a higher order filter can do a much better job at filtering than this simple RC filter. Finally, it is quite straightforward to achieve a similar conclusion for a low-pass RC filter to select a signal which has a frequency smaller than that of the relevant noise source.</p>
<p>Python code to produce the above plot:</p>
<div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>pylab inline</span>
<span id="cb1-2"></span>
<span id="cb1-3">f <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> logspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)</span>
<span id="cb1-4">fn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Noise freq.</span></span>
<span id="cb1-5">fs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Signal freq.</span></span>
<span id="cb1-6">signal_transfer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>sqrt((fs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>f<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb1-7">noise_transfer  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>sqrt((fn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>f<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb1-8">sn_ratio <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sqrt((fn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>f<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>(fs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>f<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb1-9">psig <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> semilogx(f, signal_transfer, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"$|T_</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{Signal}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">(f_c)|$"</span>)</span>
<span id="cb1-10">pnoi <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> semilogx(f, noise_transfer , label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"$|T_</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{Noise}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">(f_c)|$"</span>)</span>
<span id="cb1-11">psnr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> semilogx(f, sn_ratio       , label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"(S/N ratio)$\cdot\frac</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{f_n}{f_s}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">$"</span>)</span>
<span id="cb1-12">vlines(fs, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">vars</span>(psig[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'_color'</span>], linestyle<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed"</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"$f_s=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%d</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">$ Hz"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>fs)</span>
<span id="cb1-13">vlines(fn, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">vars</span>(pnoi[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'_color'</span>], linestyle<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed"</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"$f_n=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%d</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">$ Hz"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>fn)</span>
<span id="cb1-14">legend()</span>
<span id="cb1-15">xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'$f_c$ (Hz)'</span>)</span>
<span id="cb1-16">grid()</span>
<span id="cb1-17">tight_layout()</span>
<span id="cb1-18">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'assets\sn_ratio_hpf.svg'</span>)</span></code></pre></div>
<div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>pylab inline</span>
<span id="cb2-2"></span>
<span id="cb2-3">f <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> logspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)</span>
<span id="cb2-4">fn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Noise freq.</span></span>
<span id="cb2-5">fs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Signal freq.</span></span>
<span id="cb2-6">signal_transfer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>sqrt((fs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>f<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb2-7">noise_transfer  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>sqrt((fn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>f<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb2-8">sn_ratio <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sqrt((fn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>f<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>(fs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>f<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb2-9">psig <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> semilogx(f, signal_transfer, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"$|T_</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{Signal}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">(f_c)|$"</span>)</span>
<span id="cb2-10">pnoi <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> semilogx(f, noise_transfer , label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"$|T_</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{Noise}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">(f_c)|$"</span>)</span>
<span id="cb2-11">FOM <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> semilogx(f, sn_ratio <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> signal_transfer    , label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"FOM"</span>)</span>
<span id="cb2-12">vlines(fs, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">vars</span>(psig[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'_color'</span>], linestyle<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed"</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"$f_s=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%d</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">$ Hz"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>fs)</span>
<span id="cb2-13">vlines(fn, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">vars</span>(pnoi[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'_color'</span>], linestyle<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed"</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"$f_n=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%d</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">$ Hz"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>fn)</span>
<span id="cb2-14">legend()</span>
<span id="cb2-15">xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'$f_c$ (Hz)'</span>)</span>
<span id="cb2-16">grid()</span>
<span id="cb2-17">tight_layout()</span>
<span id="cb2-18">savefig(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'assets\sn_ratio_fom.svg'</span>)</span></code></pre></div>


</section>

 ]]></description>
  <category>electronics</category>
  <category>arduino</category>
  <category>filters</category>
  <category>instrumentation</category>
  <guid>https://amamaral.github.io/blog/posts/rc-filter-cutoff-optimization/</guid>
  <pubDate>Thu, 26 Apr 2018 00:00:00 GMT</pubDate>
  <media:content url="https://amamaral.github.io/blog/assets/rc-high-pass.svg" medium="image" type="image/svg+xml"/>
</item>
</channel>
</rss>
