an essential tool for mathematics

I believe the blackboard is an essential tool for mathematics. Usually, to solve (or find) a problem, you have to make many incorrect guesses or other mistakes first. Writing on a blackboard is easily edited, which is useful in the process of shaping one’s own thoughts in the process of solving a problem. On paper, even pencil is more difficult to erase, so there is some underlying pressure not to waste space with ideas perceived to be bad — but these “bad” ideas might actually turn out to be very important, or at least inspire progress. Because writing on a blackboard is temporary, it is very easy to put an idea up and see what happens next.

from Do Not Erase: Mathematicians and Their Chalkboards by Wynne, Jessica.

How to Interpolate Data with Scipy

Interpolation may sound like a fancy mathematical exercise, but in many ways, it is much like what machine learning does.

• Start with a limited set of data points relating multiple variables
• Interpolate (basically, create a model)
• Construct a new function that can be used to predict any future or new point from the interpolation

So, the idea is — ingest, interpolate, predict.

Concretely, suppose we have a limited number of data points for a pair of variables (x,y) that have an unknown (and nonlinear) relationship between them i.e. y = f(x). From this limited data, we want to construct a prediction function that can generate y values for any given x values (within the same range that was used for the interpolation).

There are a lot of mathematical theories and work on this subject. You can certainly write your own algorithm to implement those interpolation methods. But why not take advantage of the open-source (and optimized) options?

Scipy interpolate

We start with a quadratic function where we have only 11 data points. The code to interpolate is basically a one-liner:

f1 = interp1d(x, y, kind='linear')


Note that this interp1d class of Scipy has a __call__ method that returns back a function. This is the function f1 we get back as our prediction model.

Here the code we have used:

from scipy.interpolate import interp1d
import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate

NUM_DATA = 11
NUM_INTERPOLATE = 41

x = np.linspace(0, 10, num=NUM_DATA, endpoint=True)
y = x**2+7*x-28

f1 = interp1d(x, y, kind='linear')
xnew = np.linspace(0, 10, num=NUM_INTERPOLATE, endpoint=True)

fig, ax  = plt.subplots(1,2,figsize=(6,3),dpi=120)
ax[0].scatter(x, y)
ax[0].set_title("Original data")
ax[1].scatter(x, y)
ax[1].plot(xnew, f1(xnew), color='orange',linestyle='--')
ax[1].set_title("Interpolation")
plt.show()


Let us go one degree higher to a cubic generating function. The interpolation result looks as smooth as ever.

x = np.linspace(0, 10, num=NUM_DATA, endpoint=True)
y = 0.15*x**3+0.23*x**2-7*x+18

f1 = interp1d(x, y, kind='linear')
xnew = np.linspace(0, 10, num=NUM_INTERPOLATE, endpoint=True)

fig, ax  = plt.subplots(1,2,figsize=(6,3),dpi=120)
ax[0].scatter(x, y)
ax[0].set_title("Original data")
ax[1].scatter(x, y)
ax[1].plot(xnew, f1(xnew), color='red',linestyle='--')
ax[1].set_title("Interpolation")
plt.show()



Note that the original data may come from a cubic function, but this is still a ‘linear’ interpolation which is set by the kind parameter as shown above. This means that the intermediate points between the original data points lie on a linear segment.

But Scipy offers quadratic or cubic splines too. Let’s see them in action.

Things can be a little tricky to handle with linear interpolation when the original data is not polynomial in nature or the data has inherent noise (natural for any scientific measurement).

Here is a demo example for a particularly tricky nonlinear example:

x = np.linspace(0, 10, num=NUM_DATA, endpoint=True)
y = 0.15*x**3+0.23*x**2-7*x+18

f1 = interp1d(x, y, kind='linear')
f3 = interp1d(x,y, kind='cubic')
xnew = np.linspace(0, 10, num=NUM_INTERPOLATE, endpoint=True)

fig, ax  = plt.subplots(1,3,figsize=(6,3),dpi=120)
ax[0].scatter(x, y)
ax[0].set_title("Original data")
ax[1].scatter(x, y)
ax[1].plot(xnew, f1(xnew), color='red',linestyle='--')
ax[1].set_title("Linear")
ax[2].scatter(x, y)
ax[2].plot(xnew, f3(xnew), color='orange',linestyle='--')
ax[2].set_title("Cubic and Linear splines")

plt.show()


Which Social is more popular in the last 3 months in Italy?

import pandas as pd

from pytrends.request import TrendReq

pytrend = TrendReq(hl='en-US', tz=360)

# list of keywords to get data
#Which Social is more popular in the last 3 months in Italy?
kw_list = keywords,
cat=0,
timeframe = 'today 3-m',
geo='IT',
gprop='')

data = pytrend.interest_over_time()

data= data.drop(labels=['isPartial'],axis='columns')

image = data.plot(title = 'Social media more popular in last 3 months on Google Trends ')
fig = image.get_figure()
fig.savefig('figure.png')
data.to_csv('Py_VS_R.csv', encoding='utf_8_sig')


Teach it…

If you want to master something, teach it. The more you teach, the better you learn. Teaching is a powerful tool to learning.

– Richard Feynman

work in progress

Una semplice calcolatrice del BMI (Indice di Massa Corporea) in PyQt… Qui il codice sorgente.

Do not erase…

Chalkboards are a major part of my life. I couldn’t live without them

Plot 3D Functions With Matplotlib and NumPy

Math is beautiful, and the software we have at our fingertips represents an invaluable way to explore that beauty. Never before have we been able to visualize and experiment with mathematical objects in such an accessible way.

In this short tutorial I would like to break down the steps required to plot a function of two variables using Python.

Along the way, we’ll learn about a few NumPy procedures that’ll have you manipulating matrices like a wizard. I’ve broken the process down into three conceptual steps that’ll also help refresh the underlying math.

Finally, I put everything together into a function you can use out of the box, so feel free to skip to that if it’s all you need.

Define the Function Domain

A mathematical function is a map that takes elements from one set and associates them with one element of another set. This first set of inputs is called the domain of the function. In our case, the domain will consist of tuples of real numbers.

Although there are infinitely many real numbers inside any interval, we obviously can’t store an infinite set for our domain. For our plot to look nice, it’s sufficient to sample enough points within our domain so the end product will look smooth and not unnaturally jagged.

With this in mind, we can define our domain and store it in a set of arrays in three steps.

1. Decide on the boundaries for each of the two variables in our domain:
x_interval = (-2, 2)
y_interval = (-2, 2)


2. Sample points within each of these intervals:

x_points = np.linspace(x_interval[0], x_interval[1], 100)
y_points = np.linspace(y_interval[0], y_interval[1], 100)


3. Take the Cartesian product of these two sampled sets to produce two arrays that (when stacked) form a set of ordered pairs we can compute a function on:

X, Y = np.meshgrid(x_points, y_points)


The next step is to associate an output value with every point in our input domain. For the purpose, we define our math function as a Python function of two scalar inputs:

def func3d(x, y):
return -np.sin(10 * (x**2 + y**2)) / 10


Then we produce a vectorized version of the function that can be called on vectors or matrices of inputs:

func3d_vectorized = np.vectorize(func3d)


Plot the Function

From this point, things proceed in nearly the same way as they would in making a 2D plot with Matplotlib. Only a few argument and method names need to change in order to produce beautiful 3D visualizations.

1. Set up a plotting figure and axes with projection='3d':
plt.figure(figsize=(20, 10))
ax = plt.axes(projection=’3d’)


2. Select a plotting method of the axes object and call it on our function data:

ax.plot_surface(X, Y, Z, rstride=1, cstride=1,
cmap=’terrain’, edgecolor=None)


3. Set other attributes of the plot, such as the title and axis labels:

ax.set(xlabel=”x”, ylabel=”y”, zlabel=”f(x, y)”,
title=”Cool Function”)


To make the process more reproducible, I’ve packaged all these steps together into a Python function for producing quick surface plots.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d

def plot_surface(domain, fn, grid_samples=100, title=None, **plot_kwargs):
x = np.linspace(domain[0][0], domain[0][1], grid_samples)
y = np.linspace(domain[1][0], domain[1][1], grid_samples)

X, Y = np.meshgrid(x, y)

fn_vectorized = np.vectorize(fn)
Z = fn_vectorized(X, Y)

fig = plt.figure(figsize=(20,10))
ax = plt.axes(projection="3d")
ax.plot_surface(X, Y, Z, **plot_kwargs)
ax.set(xlabel="x", ylabel="y", zlabel="f(x, y)", title=title)
plt.show()

return fig, ax

# now let's try it out!
def func(x, y):
return -np.sin(10 * (x**2 + y**2)) / 10

domain = [(-0.5, 0.5), (-0.5, 0.5)]
fig, ax = plot_surface(domain, func, rstride=1, cstride=1, cmap='terrain', edgecolor=None)


How to Create a Translator with Python

In the following lines, we will learn how to create a simple dictionary in a few lines of Python code. First, we need the translate package.

translate is a simple but powerful translation tool written in Python with support for multiple translation providers. It offers integration with Microsoft Translation API, MyMemory API, LibreTranslate, and DeepL’s free and professional APIs.

We can use translate as a module with this command:

\$ pip install translate


Now we create some codes that allow us to enter what we have to translate. We will write the following method pB_traducoClick():

    def pB_traducoClick(self):

try:
to_Translate = (self.lE_input.text())
self.lE_output.setText(result)

except:
print('Valore nel campo non accettato')


This is the connection diagram:

The value of to_lang is one of the languages that are available in ISO_639–1 (like “en”, “ja”, “ko”, “pt”, “zh”, “zh-TW”, etc.)

You can choose in this document the language you want.

The result:

From here you can find the source codes.