If statement check mistake - python-3.x

I had a code with if statements and the code found the cosine value of the user-defined angle in radial. I typed the code to Taylor Series up to 12!. The code is;
import numpy as np
import matplotlib.pyplot as plt
import math
teta = np.arange(-8*np.pi, 8*np.pi+0.1,0.1)
P_ = [None]*len(teta)
ang_ = np.zeros(len(teta))
def func(teta):
for i in range(len(teta)):
if teta[i]<=0:
if abs(teta[i])%np.pi>=np.pi:
ang_[i] = (abs(teta[i])%(2*np.pi)-2*np.pi)*(-1)
else:
ang_[i] = (abs(teta[i])%(2*np.pi))*(-1)
else:
if teta[i]%2*np.pi >= np.pi:
ang_[i] = teta[i] % (2*np.pi) - 2*np.pi
else:
ang_[i] = teta[i] % (2*np.pi)
P_[i] = 1 - (1/2)*((ang_[i])**2) + (1/math.factorial(4))*((ang_[i])**4) - (1/math.factorial(6))*((ang_[i])**6) + (1/math.factorial(8))*((ang_[i])**8) - (1/math.factorial(10))*((ang_[i])**10) + (1/math.factorial(12))*((ang_[i])**12)
return P_
plt.plot(teta, func(teta), "b:+")
plt.plot(teta, np.cos(teta), "k--")
plt.grid()
plt.show
And the code cannot calculate when the teta angle is greater than 6 or -6. when I checked the code by debugging the step, that teta angle is -6.18319, jump over if statement
if abs(teta[i])%2*np.pi >= np.pi and teta[i]<-np.pi:
and jumps into
elif abs(teta[i])%np.pi >= 0 and teta[i]<0:
and code transverse the teta value to another angle array named ang_, and it determines by
ang_[i] = (abs(teta[i])%(2*np.pi))*(-1)
Thus the result of the function is over 2.
I will be glad if you would help me. Thanks a lot.

I found the mistake and the correct code is;
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 1 13:54:51 2022
#author: burak
"""
import numpy as np
import matplotlib.pyplot as plt
import math
user_degree = int(input('cosine value of angle in degree')) / 180 * np.pi
teta = np.arange(-user_degree, user_degree+0.1,0.1)
P_ = [None]*len(teta)
ang_ = np.zeros(len(teta))
def func(teta):
for i in range(len(teta)):
if teta[i]<=0:
teta = abs(teta)
if teta[i]%(2*np.pi) >= np.pi:
ang_[i] = (teta[i]%(2*np.pi)) - 2 * np.pi
else:
ang_[i] = (teta[i]%(2*np.pi))
else:
if teta[i]%(2*np.pi) >= np.pi:
ang_[i] = teta[i] % (2*np.pi) - 2 * np.pi
else:
ang_[i] = teta[i] % (2*np.pi)
P_[i] = 1 - (1/2)*((ang_[i])**2) + (1/math.factorial(4))*((ang_[i])**4) - (1/math.factorial(6))*((ang_[i])**6) + (1/math.factorial(8))*((ang_[i])**8) - (1/math.factorial(10))*((ang_[i])**10) + (1/math.factorial(12))*((ang_[i])**12)
return P_
plt.plot(teta, func(teta), "b:+")
plt.plot(teta, np.cos(teta), "k--")
plt.grid()
plt.show
The purpose of this code is to obtain correct cosine values of given angle. I asked the qs that the code cannot step to the correct if condition. for example when the angle is greater than np.pi the resul was above 1. I changed the code as when the angle is lesser than zero and greater than np.pi, code calculates absolute value of angle. Then the step moves to the correct condition. The next calculation is when the absolute value of teta greater then np.pi, the code substructs np.pi. At last the Taylor Series calculation matched with the np.cos() calculation.

Related

Determine the rating for text quality in an Image

I want to determine the quality score of the text by giving them some score or rating (something like ' image-text is 90% bad. Texts are not readable ).
What I am doing now is I am using the Blind/referenceless image spatial quality evaluator (BRISQUE) model to assess the quality.
It gives scores from 0 to 100. 0 score for good quality and 100 for bad quality.
The problem I am having with this code is that it is giving bad scores to even good quality "images-texts".
Also, the score exceeds 100 sometimes but according to the reference I am taking, the score should be between 0 to 100 only.
Can someone please suggest to me how can I get promising and reliable results for assessing the quality of the text-based images?
import collections
from itertools import chain
# import urllib.request as request
import pickle
import numpy as np
import scipy.signal as signal
import scipy.special as special
import scipy.optimize as optimize
# import matplotlib.pyplot as plt
import skimage.io
import skimage.transform
import cv2
from libsvm import svmutil
from os import listdir
# Calculating Local Mean
def normalize_kernel(kernel):
return kernel / np.sum(kernel)
def gaussian_kernel2d(n, sigma):
Y, X = np.indices((n, n)) - int(n/2)
gaussian_kernel = 1 / (2 * np.pi * sigma ** 2) * np.exp(-(X ** 2 + Y ** 2) / (2 * sigma ** 2))
return normalize_kernel(gaussian_kernel)
def local_mean(image, kernel):
return signal.convolve2d(image, kernel, 'same')
# Calculating the local deviation
def local_deviation(image, local_mean, kernel):
"Vectorized approximation of local deviation"
sigma = image ** 2
sigma = signal.convolve2d(sigma, kernel, 'same')
return np.sqrt(np.abs(local_mean ** 2 - sigma))
# Calculate the MSCN coefficients
def calculate_mscn_coefficients(image, kernel_size=6, sigma=7 / 6):
C = 1 / 255
kernel = gaussian_kernel2d(kernel_size, sigma=sigma)
local_mean = signal.convolve2d(image, kernel, 'same')
local_var = local_deviation(image, local_mean, kernel)
return (image - local_mean) / (local_var + C)
# It is found that the MSCN coefficients are distributed as a Generalized Gaussian Distribution (GGD) for a broader spectrum of distorted image.
# Calculate GGD
def generalized_gaussian_dist(x, alpha, sigma):
beta = sigma * np.sqrt(special.gamma(1 / alpha) / special.gamma(3 / alpha))
coefficient = alpha / (2 * beta() * special.gamma(1 / alpha))
return coefficient * np.exp(-(np.abs(x) / beta) ** alpha)
# Pairwise products of neighboring MSCN coefficients
def calculate_pair_product_coefficients(mscn_coefficients):
return collections.OrderedDict({
'mscn': mscn_coefficients,
'horizontal': mscn_coefficients[:, :-1] * mscn_coefficients[:, 1:],
'vertical': mscn_coefficients[:-1, :] * mscn_coefficients[1:, :],
'main_diagonal': mscn_coefficients[:-1, :-1] * mscn_coefficients[1:, 1:],
'secondary_diagonal': mscn_coefficients[1:, :-1] * mscn_coefficients[:-1, 1:]
})
# Asymmetric Generalized Gaussian Distribution (AGGD) model
def asymmetric_generalized_gaussian(x, nu, sigma_l, sigma_r):
def beta(sigma):
return sigma * np.sqrt(special.gamma(1 / nu) / special.gamma(3 / nu))
coefficient = nu / ((beta(sigma_l) + beta(sigma_r)) * special.gamma(1 / nu))
f = lambda x, sigma: coefficient * np.exp(-(x / beta(sigma)) ** nu)
return np.where(x < 0, f(-x, sigma_l), f(x, sigma_r))
# Fitting Asymmetric Generalized Gaussian Distribution
def asymmetric_generalized_gaussian_fit(x):
def estimate_phi(alpha):
numerator = special.gamma(2 / alpha) ** 2
denominator = special.gamma(1 / alpha) * special.gamma(3 / alpha)
return numerator / denominator
def estimate_r_hat(x):
size = np.prod(x.shape)
return (np.sum(np.abs(x)) / size) ** 2 / (np.sum(x ** 2) / size)
def estimate_R_hat(r_hat, gamma):
numerator = (gamma ** 3 + 1) * (gamma + 1)
denominator = (gamma ** 2 + 1) ** 2
return r_hat * numerator / denominator
def mean_squares_sum(x, filter=lambda z: z == z):
filtered_values = x[filter(x)]
squares_sum = np.sum(filtered_values ** 2)
return squares_sum / ((filtered_values.shape))
def estimate_gamma(x):
left_squares = mean_squares_sum(x, lambda z: z < 0)
right_squares = mean_squares_sum(x, lambda z: z >= 0)
return np.sqrt(left_squares) / np.sqrt(right_squares)
def estimate_alpha(x):
r_hat = estimate_r_hat(x)
gamma = estimate_gamma(x)
R_hat = estimate_R_hat(r_hat, gamma)
solution = optimize.root(lambda z: estimate_phi(z) - R_hat, [0.2]).x
return solution[0]
def estimate_sigma(x, alpha, filter=lambda z: z < 0):
return np.sqrt(mean_squares_sum(x, filter))
def estimate_mean(alpha, sigma_l, sigma_r):
return (sigma_r - sigma_l) * constant * (special.gamma(2 / alpha) / special.gamma(1 / alpha))
alpha = estimate_alpha(x)
sigma_l = estimate_sigma(x, alpha, lambda z: z < 0)
sigma_r = estimate_sigma(x, alpha, lambda z: z >= 0)
constant = np.sqrt(special.gamma(1 / alpha) / special.gamma(3 / alpha))
mean = estimate_mean(alpha, sigma_l, sigma_r)
return alpha, mean, sigma_l, sigma_r
# Calculate BRISQUE features
def calculate_brisque_features(image, kernel_size=7, sigma=7 / 6):
def calculate_features(coefficients_name, coefficients, accum=np.array([])):
alpha, mean, sigma_l, sigma_r = asymmetric_generalized_gaussian_fit(coefficients)
if coefficients_name == 'mscn':
var = (sigma_l ** 2 + sigma_r ** 2) / 2
return [alpha, var]
return [alpha, mean, sigma_l ** 2, sigma_r ** 2]
mscn_coefficients = calculate_mscn_coefficients(image, kernel_size, sigma)
coefficients = calculate_pair_product_coefficients(mscn_coefficients)
features = [calculate_features(name, coeff) for name, coeff in coefficients.items()]
flatten_features = list(chain.from_iterable(features))
return np.array(flatten_features, dtype=object)
# Loading image from local machine
def load_image(file):
return cv2.imread(file)
# return skimage.io.imread("img.png", plugin='pil')
path = "C:\\Users\\Krishna\\PycharmProjects\\ImageScore\\images2\\"
image_list = listdir(path)
for file in image_list:
image = load_image(path+file)
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# image = load_image()
# gray_image = skimage.color.rgb2gray(image)
# _ = skimage.io.imshow(image)
#%%time
# Calculate Coefficients
mscn_coefficients = calculate_mscn_coefficients(gray_image, 7, 7/6)
coefficients = calculate_pair_product_coefficients(mscn_coefficients)
# Fit Coefficients to Generalized Gaussian Distributions
brisque_features = calculate_brisque_features(gray_image, kernel_size=7, sigma=7/6)
# Resize Image and Calculate BRISQUE Features
downscaled_image = cv2.resize(gray_image, None, fx=1/2, fy=1/2, interpolation = cv2.INTER_CUBIC)
downscale_brisque_features = calculate_brisque_features(downscaled_image, kernel_size=7, sigma=7/6)
brisque_features = np.concatenate((brisque_features, downscale_brisque_features))
# a pretrained SVR model to calculate the quality assessment. However, in order to have good results, we need to scale the features to [-1, 1]
def scale_features(features):
with open('normalize.pickle', 'rb') as handle:
scale_params = pickle.load(handle)
min_ = np.array(scale_params['min_'])
max_ = np.array(scale_params['max_'])
return -1 + (2.0 / (max_ - min_) * (features - min_))
def calculate_image_quality_score(brisque_features):
model = svmutil.svm_load_model('brisque_svm.txt')
scaled_brisque_features = scale_features(brisque_features)
x, idx = svmutil.gen_svm_nodearray(
scaled_brisque_features,
isKernel=(model.param.kernel_type == svmutil.PRECOMPUTED))
nr_classifier = 1
prob_estimates = (svmutil.c_double * nr_classifier)()
return svmutil.libsvm.svm_predict_probability(model, x, prob_estimates)
print(calculate_image_quality_score(brisque_features))
Here is one output for the quality score I am getting for one of the "text-based image"
156.04440687506016

Python projectile motion graph gives me a straight line

Here is the code that should calulate the motion but it is producing a line instead of a parabola, any help is appreciate.
import math as m
import matplotlib.pyplot as plt
import numpy as np
class Projectile_motion:
def __init__(self, V_x, V_y, g, delta_time):
self.gravity = g
self.V_x = V_x
self.V_y = V_y
self.delta_time = delta_time
def velocity(self, angle):
self.angle = angle
self.V_x= m.ceil(self.V_x *m.cos(self.angle))
self.V_y = m.ceil((self.V_y * m.sin(self.angle))) - (self.gravity * self.delta_time)
def distance(self, x, y):
self.x = x
self.y = y
self.x = self.x + (self.V_x * self.delta_time)
self.y = self.y + (self.V_y * m.sin(self.angle)) + (0.5 * self.gravity * ((self.delta_time)**2))
return self.x, self.y
ww = np.linspace(0, 50, num=5)
for i in ww:
attempt1 = Projectile_motion(30, 30, 9.8, i)
attempt1.velocity(1.042)
ss=attempt1.distance(0, 0)
plt.plot(ss)
plt.show()
Output:
You are off to a good start here, but you need to clean up some of the physics in your model.
If you have a V_x and V_y, it isn’t clear what you are doing with an angle, because that is already defined by the relationship of V_x and V_y.
I would suggest you get rid of the angle for a starter. Then, you just need to do a couple things with V_y:
Update V_y repeatedly when you are running. Gravity should be increasing V_y, right? Right now your V_y does not update. It should increase by 9.8m/s^2, so that is your update every time step
Use this updated V_y to calculate the distance. So After you update V_y, just use that to change y position. You should not be doing any more math there, just y += V_y*dt
If you get that working, you can transition back to using an angle (which I assume is your initial direction) and calculate V_x and V_y by standard application of cosine and sine on the angle. Also, remember, the math module wants angular inputs in radians.

How do I curve text in a polar plot?

Hello Matplotlib Experts,
How do I curve text in a matplotlib polar plot? In my attempt below, my code rotates each char individually, but doing so would remove the natural spacing of each font. Can somebody describe a solution for passing ax.text in matplotlib?
import numpy as np
import matplotlib as mpl
import matplotlib.pylab as plt
def curveText(text, height, minTheta, maxTheta, ax):
interval = np.arange(minTheta, maxTheta, .022)
if( maxTheta <= np.pi):
progression = interval[::-1]
rotation = interval[::-1] - np.arctan(np.tan(np.pi/2))
else:
progression = interval
rotation = interval - np.arctan(np.tan(np.pi/2)) - np.pi
## Render each letter individually
for i, rot, t in zip(progression, rotation, text):
ax.text(i, height, t, fontsize=11,rotation=np.degrees(rot), ha='center', va='center')
def buildCircularHeatMap( data=None, label=None, cmaps=None, categorymap=None, vmin=0, vmax=None ):
(xDim, yDim) = data.shape
if cmaps == None:
cmaps = [mpl.cm.get_cmap()] * yDim
BOTTOM = xDim / 100 * 120
#FONTSIZE = 1 if xDim/100*8 < 1 else xDim/100*8
theta = np.linspace(0.0, 2 * np.pi - 5 * np.pi/180, xDim, endpoint=False)
width = (2*np.pi - 5 * np.pi/180)/xDim
ax = plt.subplot(111, polar=True)
ax.grid(False)
ax.set_yticklabels([])
ax.set_xticklabels([])
categorysum = np.zeros(len(categorymap))
for x in label:
categorysum[int(float( x )) - 1] += 1
categorysum = categorysum/np.sum(categorysum)*2*np.pi
## Build Face Color Values
for i in range(yDim):
cmap_scalar = mpl.cm.ScalarMappable(cmap=cmaps[i])
cmap_scalar.set_clim(vmin=vmin, vmax=vmax)
facecolor = cmap_scalar.to_rgba(data[:,i])
_ = ax.text(2 * np.pi - 5 * np.pi/180, BOTTOM+i*10, str(i), fontsize=11, rotation=np.degrees(270))
bars = ax.bar(theta, np.ones(xDim)*10, width=width, bottom=BOTTOM+i*10)
for j, b in enumerate(bars):
b.set_facecolor( facecolor[j] )
## Build CCS Label
for th, l, bar in zip(theta, label, bars):
rot = np.arctan(np.tan(th))
ax.text(th,BOTTOM+yDim*10+bar.get_height()+5, l, rotation_mode='anchor',
rotation=np.degrees(rot), fontsize=11, ha='center', va='center')
## Build Category Label
categoryColor = np.asarray([int(float(c)) for c in label])
bars = ax.bar(theta, np.ones(xDim)*20, width=width, bottom=BOTTOM+yDim*10 + 30)
for j, b in enumerate(bars):
b.set_facecolor(np.asarray([0.0,0.0,0.0]))
if categoryColor[j] % 2 == 0:
b.set_alpha(0.07)
else:
b.set_alpha(0.0)
for i in range(len(categorymap)):
c = i + 1
t = theta[categoryColor==c]
mi = np.min(t)
ma = np.max(t)
rad = (ma-mi)/2+mi
curveText(categorymap[c], BOTTOM+yDim*10+40, mi, ma, ax)
if __name__ == "__main__":
categorymap={
1: "Infectious & parasitic dieases",
2: "Neoplasms",
3: "Endocrine; nutritional; and metabolic diseases and immunity disorders",
4: "Diseases of the blood and blood-forming organs",
5: "Mental Illness",
6: "Nervous system disorders",
7: "Circulatory disorders",
8: "Respiratory disorders",
9: "Digestive disorders",
10: "Genitourinary disorders",
11: "Complications of pregnancy; childbirth; and the puerperium",
12: "Skin and subcutaneous tissue disorder",
13: "Musculoskeletal system and connective tissue disorder",
14: "Congenital anomalies",
15: "Certain conditions originating in the perinatal period",
16: "Injury and poisoning",
17: "Ill-defined status",
18: "Unclassified"
}
data = np.random.standard_normal((180, 3))
colormaps = [mpl.cm.get_cmap("Reds"), mpl.cm.get_cmap("Oranges"), mpl.cm.get_cmap("Greens"), mpl.cm.get_cmap("Blues")]
labels = sorted([ '{:.2f}'.format(np.abs(i)) for i in np.random.random_sample(180) * 18 + 1 ])
fig = plt.figure(figsize=(11,11))
buildCircularHeatMap(data=data, label=labels, cmaps=colormaps, categorymap=categorymap)
plt.show()
In the link below, Thomas's answer seems only applicable for cartesian coordinates and my current attempt should be similar to Daan.
Curved text rendering in matplotlib
As #Makdous suggested above, Curved text rendering in matplotlib is a nice implementation of the problem. I read through the code, and you're right, it is in cartesian coordinates, but I think you could just modify it a bit and get it working using these formulas:
You can also use this one line function I wrote:
from typing import Tuple
from math import sqrt, degrees, atan2
def cartesian_to_polar(x: float, y: float)-> Tuple[float, float]:
return sqrt(x**2 + y ** 2), degrees(atan2(y,x))
Or, if you have polar coordinates and want to make it work with the script linked in the other response, you can use this:
from math import cos, sin, radians
def polar_to_cartesian(r: float, theta: float)-> Tuple[float, float]:
return r * cos(radians(theta)), r * sin(radians(theta))
Depending on how you implemented it, you could feed it in the coordinates you have, then convert it appropriately to arrive at cartesian coordinates and run the linked script, then convert the points back to polar coordinates and plot it.

Simulate stock price based on a given equation in Python

How can I generate a price time series using the following equation:
p(t) = p0(1+A * sin(ωt +0.5η(t)))
where t ranges from 0 to 1 in 1000 time steps, p0 = 100, A = 0.1, and ω = 100. η(t) is a sequence of i.i.d Gaussian random variables with zero mean and unit variance.
I have use the code as follows to generate price, but it seems not as required. So I need helps from the community. Thanks in advance.
from scipy.stats import norm
import numpy as np
import matplotlib.pyplot as plt
mu = 0
sigma = 1
np.random.seed(2020)
dist = norm(loc = mu,scale=sigma)
sample = dist.rvs(size = 1000)
stock_price = np.exp(sample.cumsum())
print(stock_price)
plt.plot(stock_price)
plt.xlabel("Day")
plt.ylabel("Price")
plt.title("Simulated Stock price")
plt.show()
Assuming I haven't missed anything, this should do the trick
import numpy as np
import matplotlib.pyplot as plt
n_t = np.random.normal(0, 1, 1000)
t = np.arange(0, 1, 1/1000)
p_0, A, w = 100, 0.1, 100
ts = p_0 * (1 + A * np.sin(w * t + 0.5 * n_t))
plt.plot(t, ts)
plt.xlabel("Day")
plt.ylabel("Price")
plt.show()
which gives the plot
My trial, not sure if it's correct, welcome to give me some comments.
import numpy as np
import math
np.random.seed(2020)
mu = 0
sigma = 1
dt = 0.01
p0 = 100
A = 0.1
w = 100
N = 1000
for t in np.linspace(0, 1, 1000):
X = np.random.normal(mu * dt, sigma* np.sqrt(dt), N)
X = np.cumsum(X)
pt = p0 * (1+ A*np.sin(w*t + 0.5*X))
# print(pt)
plt.plot(pt)
plt.xlabel("Day")
plt.ylabel("Price")
plt.title("Simulated Stock price")
plt.show()
Out:

Monte Carlo Optimization

I am trying to do Monte Carlo minimization to solve for parameters of a given equation. My equation has 4 parameters, making my iteration about 4**n
when I try iteration n = 100, I saw it is not a good idea to search all the parameter space.
Here is my code:
import sys
import numpy as np
#import matplotlib.pyplot as plt
#import pandas as pd
import random
#method returns sum square for given parameter m and c
def currentFunc(x,alpha1,alpha2,alpha3,alpha4):
term = -(x/alpha4)
term_Norm = term
expoterm = np.exp(term_Norm)
expoterm = np.exp(term_Norm)
#print('check term: x: %0.10f %0.10f exp: %0.10f' % (x,term_Norm,expoterm) )
return(-alpha1*( (alpha2/(alpha3+ expoterm )) - 1))
def sumsquarecurr(x,y,a1,a2,a3,a4):
xsize = len(x)
ysize = len(y)
sumsqdiff = 0
if(xsize != ysize):
print("check your X and Y length exiting ...")
sys.exit(0)
for i in range(ysize):
diff = y[i] - currentFunc(x[i],a1,a2,a3,a4)
sumsqdiff+=diff*diff
return sumsqdiff
# number of random number (this affects the accuracy of the Monte Carlo method
n = 10
a_rnad = []
b_rnad = []
c_rnad = []
d_rnad = []
for i in range(n):
#random.seed(555)
xtemp = random.uniform(0.0, 2.0)
print('check %.4f ' % (xtemp))
a_rnad.append(xtemp)
b_rnad.append(xtemp)
c_rnad.append(xtemp)
d_rnad.append(xtemp)
Yfit=[-7,-5,-3,-1,1,3,5,7]
Xfit=[8.077448e-07,6.221196e-07,4.231292e-07,1.710039e-07,-4.313762e-05,-8.248818e-05,-1.017410e-04,-1.087409e-04]
# placeholder for the parameters and the minimun sum squared
#[alpha1,alpha2,alpha3,alpha4,min]
minparam = [0,0,0,0,99999999999.0]
for j in range(len(a_rnad)):
for i in range(len(b_rnad)):
for k in range(len(c_rnad)):
for m in range(len(d_rnad)):
minsumsqdiff_temp =sumsquarecurr(Xfit,Yfit,a_rnad[j],b_rnad[i],c_rnad[k],d_rnad[m])
print('alpha1: %.4f alpha2: %.4f alpha3: %.4f alpha4: %.4f min: %0.4f' % (a_rnad[j],b_rnad[i],c_rnad[k],d_rnad[m],minsumsqdiff_temp))
if(minsumsqdiff_temp<minparam[4]):
minparam[0] = a_rnad[j]
minparam[1] = b_rnad[i]
minparam[2] = c_rnad[k]
minparam[3] = d_rnad[m]
minparam[4] = minsumsqdiff_temp
print('minimazation: alpha1: %.4f alpha2: %.4f alpha3: %.4f alpha4: %.4f min: %0.4f' % (minparam[0],minparam[1],minparam[2],minparam[3],minparam[4]))
Question:
is there a way to make this algorithm run faster (either by cutting the search/phase space down)?
I feel I am reinventing the wheel. please does anyone know a python module that can do what I am trying to do?
Thanks in advance for your help

Resources