≡ Menu

Using AnimatPlot for Animating Graphs & Plots

Data Visualization helps in understanding different patterns, associations, visual insights from the data, etc. It is important because it uncovers the mystery behind the data tables in form of charts, graphs, and plots. There are tons of python libraries that help in visualizing the data like Matplotlib, Seaborn, etc.

AnimatPlot is an open-source python library that is built on top of Matplotlib and is used for creating highly interactive animated plots. Now, we will explore some of the functionalities that AnimatPlot provides.

Installing required libraries

We will start by installing AnimatPlot using pip. The command given below will do that.

pip install animatplot

Animatplot is built on the concept of blocks. We’ll start by animating a Line block.

First we need some imports.

Interactivity is not available in the static docs. Run the code locally to get interactivity.

So, we will use JupyterLab for our simulations.

We will import the required libraries for creating animated plots.

We will animate the function:

\(y=\cos (2 \pi(x+t)) \text { over the range } x=[0,1] \text {, and } t=[0,1]\)

Let’s generate the data:

In order to tell animatplot how to animate the data, we must pass it into a block. By default, the Line block will consider each of the rows in a 2D array to be a line at a different point in time.

We then pass a list of all our blocks into an Animation, and show the animation.

We’ll use the same data to make a new animation with interactive controls.

block = amp.blocks.Line(X, Y)
anim = amp.Animation([block])

anim.controls() # creates a timeline_slider and a play/pause toggle
anim.save_gif('images/line2') # save animation for docs
plt.show()

Displaying the Time

The above animation didn’t display the time properly because we didn’t tell animatplot what the values of time are. Instead it displayed the frame number. We can simply pass our values of time into our call to Animation.

block = amp.blocks.Line(X, Y)
anim = amp.Animation([block], t) # pass in the time values

anim.controls()
anim.save_gif('line3') # save animation for docs
plt.show()

Similarly, now we will add more data and create multiple plots in a single chart.

and once again:

{ 0 comments }

Insieme di Mandelbrot…

L’insieme di Mandelbrot o frattale di Mandelbrot è l’insieme dei numeri complessi \(c \in \displaystyle{C}\) per i quali la successione definita da:

{\displaystyle {\begin{cases}z_{0}=0\\z_{n+1}=z_{n}^{2}+c\end{cases}}}

è limitata.

Nonostante la semplicità della definizione, l’insieme ha una forma complessa il cui contorno è un frattale.

Qui, la funzione per la costruzione della matrice da diagrammare:

def plotter(n, vallim, itlim, xi,xs,yi,ys):
    image = np.full((n,n),0)
    Xp = np.linspace(xi,xs,n)
    Yp = np.linspace(yi,ys,n)
    for x in range(n):
        for y in range(n):
            image[y][x] = divergetest(complex(Xp[x],Yp[y]),vallim, itlim)
    return image

Di seguito, invece, la routine per verificare la convergenza della successione:

def divergetest(c, vallim, itlim):
    z = c
    i = 0
    while i < itlim and np.sqrt((z.real)**2 + (z.imag)**2)< vallim:
        z = z**2 + c
        i = i + 1
    return i

Il programma principale:

n = 5000
xi,xs,yi,ys = -3,1,-2,2
vallim = 5
itlim = 30
mandelbrot = plotter(n,vallim,itlim,xi,xs,yi,ys)

plt.figure(1,figsize=[8,8])
plt.title('Mandelbrot Set')
plt.imshow(mandelbrot,extent=[-3,1,-2,2])
plt.xlabel('Real')
plt.ylabel('Complex')
plt.show()

Di seguito, l’output del programma:

{ 0 comments }

Project Euler: Problem 9

That is the problem:

We can solve the problem by writing a Python code.

Let’s start with a function that checks if the three numbers \(a,b,c\), with \(a<b<c\), are a Pythagorean triplet.

def is_triplet(a,b,c):
	if (a**2 + b**2) == c**2:
		return(True)
	else:
		return(False)

Now, let’s move on to defining the main function:

def main(sum_value):
	for c in range(sum_value):
		for b in range(c):
			for a in range (b):
				if (a+b+c) == sum_value:
					if is_triplet(a,b,c):
						print(a,b,c)
						print(a*b*c)

and then, the main program:

sum_total = 1000
main(sum_total)

This is the answer:

{ 0 comments }

#spigolatricedisapri

Guardommi, e mi rispose: “O mia sorella,
Vado a morir per la mia patria bella”.
Io poi buttai i miei occhi un po’ da fora,
né potei dirgli: “Che culo, oh mia Signora!”

[*]

{ 0 comments }

Chi controlla chi

in russo la parola “spione” viene dal verbo “bussare”. E che dunque quando in russo dici spione, subito, vedi il bambino che bussa alla porta del maestro per accusare il compagno che ha copiato il compito, l’insegnante che bussa alla porta del direttore per denunciare un collega, il direttore che bussa alla porta di un ufficio anonimo per avvertire che qualcuno dietro una parete di notte scrive a macchina per ore e ore qualcosa che è certamente letteratura antisovietica.

Chiara Valerio da La Repubblica in edicola

{ 0 comments }

The square root of 2…

The square root of 2 (approximately 1.4142) is a positive real number that, when multiplied by itself, equals the number 2. 

There are a number of algorithms for approximating √2 as a ratio of integers or as a decimal. The most common algorithm for this, which is used as a basis in many computers and calculators, is the Babylonian method for computing square roots, which is one of many methods of computing square roots. It goes as follows:

First, pick a guess, a0 > 0; the value of the guess affects only how many iterations are required to reach an approximation of a certain accuracy. Then, using that guess, iterate through the following recursive computation:

\(a_{n+1}=\frac{a_{n}+\frac{2}{a_{n}}}{2}=\frac{a_{n}}{2}+\frac{1}{a_{n}}\)

In general, suppose we want to evaluate the square root of a number n. Let’s assume the \(n=a^2+b\), where \(a^2\) is the biggest square number that is less or equal to \(n\).

Then, we can write it as:

\(n-a^2=b\)

or:

\(\left( {\sqrt n + a} \right)\left( {\sqrt n – a} \right) = b \Leftrightarrow \sqrt n – a = \frac{b}{{\sqrt n + a}}\)

and then:

\(\sqrt n = a + \frac{b}{{\sqrt n + a}}\)

Recursively replacing the \(\sqrt{n}\):

\(\sqrt n = a + \frac{b}{{2a + \frac{b}{{\sqrt n + a}}}}\)

or:

For \(n=2\) we have \(a=1\) and \(b=2-1=1\). So:

In general, we will write the sequence:

\({a_{n + 1}} = 1 + \frac{1}{{{a_n} + 1}}\)

In Python:

import numpy as np
import decimal

def twoSqrt(EPS):
    decimal.getcontext().prec = 10000
    
    x = decimal.Decimal(1)
    t = x
    # while error is still big
    while abs(x*x - decimal.Decimal(2)) > EPS:
        x = decimal.Decimal(1) + decimal.Decimal(1)/(decimal.Decimal(1)+t)
        # converge the answer
        t = x
    return x

EPS = decimal.Decimal(1e-200)

r1 = twoSqrt(EPS) 
r2 = decimal.Decimal(2).sqrt()

print('%.19f' % r1)

def twoSqrt(EPS):
    decimal.getcontext().prec = 10000
    
    myList = []
    myCount = []
    
    x = decimal.Decimal(1)
    t = x
    i = 0
    myList.append(x)
    myCount.append(i)
    # while error is still big
    while abs(x*x - decimal.Decimal(2)) > EPS:
        x = decimal.Decimal(1) + decimal.Decimal(1)/(decimal.Decimal(1)+t)
        # converge the answer
        myList.append(x)
        i = i+1
        t = x
        myCount.append(i)
    plt.xlabel("iterations")
    plt.ylabel("$\sqrt{2}$ values")    
    plt.plot(myCount,myList, marker = "x")
    plt.savefig("sqrt2.jpg")
    plt.show()
    return x

With this code change, the following diagram can be obtained:

{ 0 comments }