To Create Dictionary By Passing One OutPut Of One Value to Dictionary - python-3.x

Basic_Sal = (2750,2500,2900)// This is My Input
for sal in Basic_Sal:
if sal <= 2750:
HRA = (sal*15)/100
DA = (sal*10)/100
MA = (sal *5)/100
Gross_Sal = HRA + DA + MA //Here I am calculating Gross_Sal
print(Gross_Sal)
else:
HRA = (sal * 20) / 100
DA = (sal * 10) / 100
MA = (sal * 5) / 100
Gross_Sal = HRA + DA + MA
print(Gross_Sal)
// I should get O/P as Dictionary =(Basic_Sal : Gross_Sal)
//Now I need to create Dictionary by passing Tuples and Gross_Sal, So that If I Call the Tuples I should get the Gross_salary directly.
// Can Anyone Help me this Without Using Function

If you want to get Gross Salary based on salary, you should be saving your results in dictionary like this:
salaryDictionary = dict()
Basic_Sal = (2750,2500,2900)// This is My Input
for sal in Basic_Sal:
if sal <= 2750:
HRA = (sal*15)/100
DA = (sal*10)/100
MA = (sal *5)/100
Gross_Sal = HRA + DA + MA //Here I am calculating Gross_Sal
print(Gross_Sal)
else:
HRA = (sal * 20) / 100
DA = (sal * 10) / 100
MA = (sal * 5) / 100
Gross_Sal = HRA + DA + MA
print(Gross_Sal)
salaryDictionary[sal] = Gross_Sal
Then you can call salaryDictionary[sal] and get the value. (first checking if sal in salaryDictionary)

Related

trying to make frequency spectra with OCTAVE

Pls help, whenever i try to call the function grabacion, this error occurs:
error: horizontal dimensions mismatch (32768x32768 vs 1x1)
i really dont know anything about Octave, my teacher sent me this code and its not working, and he wont help at all. i need to get the energy density and frecuency spectra of an audio
function grabacion(fmax,Amax)
%
[x, rate] = audioread('prueba.wav');
%
%fs=44100; % frecuencia de muestreo [muestras/segundo]
%ts=1/rate; % tiempo de muestreo [segundos/muestras]
nsample = size(x, 1); % [muestras]
nsample = pow2(nextpow2(nsample));
x=[x;zeros(nsample - length(x)),1]; %genera un tamaño potencia de 2
%
%eje de frecuencias
dur = nsample / rate; %duraci\'on [seg]
fs = 1 / rate; %tasa de muestreo [seg]
t = 0:fs:dur; %eje de tiempo [seg]
tam = length(t);
f = (rate/2) * (1:tam/2) / (tam/2); %eje frecuencia [Hz]
N_min = round(nsample * 20 / rate) + 1;
N_max = round(nsample * fmax / rate) + 1;
f = f(N_min:N_max);
%
x = x .* hanning(length(x));
fftx = abs(fft(x));
fftx = fftx(N_min:N_max);
l = N_max - N_min + 1;
fft_x = 20 * log10(fftx); %unidad en dB
%
% Espectro de densidad de energía
figure;
subplot(2,1,1)
plot(f, fft_x', 'linewidth', 2);
set(gca, 'linewidth', 2, 'fontsize', 14);
axis([20 fmax 0 Amax]);
title(['Densidad Espectral de Energía'] );
xlabel(['Frecuencia [Hz]']);
ylabel(['Amplitud [dB]']);
grid;
%size(t)
nx=size(x,1);
subplot(2,1,2)
plot(t(1:nx),x', 'linewidth', 2);
set(gca, 'linewidth', 2, 'fontsize', 14);
%axis([20 fmax 0 Amax]);
title(['función en el tiempo [seg]',] );
xlabel(['Tiempo [seg]']);
ylabel(['Amplitud [V]']);
grid;
endfunction

Any suggestions to make python code faster?

My present code takes too much time to execute say N=100000 values. Last time I tried it took around 4 hrs. Which is too much computing time. If someone can suggest anything to make the code a little faster?
def gen_chain(N):
coordinates = np.loadtxt('saw.txt', skiprows=0)
return coordinates
def lj(rij2):
sig_by_r6 = np.power(sigma / rij2, 3)
sig_by_r12 = np.power(sig_by_r6, 2)
lje = 4.0 * epsilon * (sig_by_r12 - sig_by_r6)
return lje
def fene(rij2):
return (-0.5 * K * R**2 * np.log(1 - ((np.sqrt(rij2) - r0)**2 / R**2)))
def total_energy(coord):
# Non-bonded
e_nb = 0
for i in range(N):
for j in range(i - 1):
ri = coord[i]
rj = coord[j]
rij = ri - rj
rij2 = np.dot(rij, rij)
if (np.sqrt(rij2) < rcutoff):
e_nb += lj(rij2)
# Bonded
e_bond = 0
for i in range(1, N):
ri = coord[i]
rj = coord[i - 1]
rij = ri - rj
rij2 = np.dot(rij, rij)
e_bond += fene(rij2)
return e_nb + e_bond
def move(coord):
trial = np.ndarray.copy(coord)
for i in range(N):
delta = (2.0 * np.random.rand(3) - 1) * max_delta
trial[i] += delta
return trial
def accept(delta_e):
beta = 1.0 / T
if delta_e <= 0.0:
return True
random_number = np.random.rand(1)
p_acc = np.exp(-beta * delta_e)
if random_number < p_acc:
return True
return False
if __name__ == "__main__":
# FENE parameters
K = 40
R = 0.3
r0 = 0.7
# LJ parameters
sigma = 0.624
epsilon = 1.0
# MC parameters
N = 100 # number of particles
rcutoff = 2.5 * sigma
max_delta = 0.01
n_steps = 100000
T = 0.5
coord = gen_chain(N)
energy_current = total_energy(coord)
traj = open('traj.xyz', 'w')
for step in range(n_steps):
if step % 1000 == 0:
traj.write(str(N) + '\n\n')
for i in range(N):
traj.write("C %10.5f %10.5f %10.5f\n" % (coord[i][0], coord[i][1], coord[i][2]))
print(step, energy_current)
coord_trial = move(coord)
energy_trial = total_energy(coord_trial)
delta_e = energy_trial - energy_current
if accept(delta_e):
coord = coord_trial
energy_current = energy_trial
traj.close()
I know it cannot be compared to C/C++.Therefore, please don't suggest to use any other language. I also welcome suggestions regarding some unnecessary objects.

Monte Carlo simulation of a system of polymer chain

I want to perform Monte Carlo simulation to the particles which are interacting via Lennard-Jones potential + FENE potential. I'm getting negative values in the FENE potential which have the log value in it. The error is "RuntimeWarning: invalid value encountered in log return (-0.5 * K * R**2 * np.log(1-((np.sqrt(rij2) - r0) / R)**2))" The FENE potential is given by:
import numpy as np
def gen_chain(N, R0):
x = np.linspace(1, (N-1)*0.8*R0, num=N)
y = np.zeros(N)
z = np.zeros(N)
return np.column_stack((x, y, z))
def lj(rij2):
sig_by_r6 = np.power(sigma/rij2, 3)
sig_by_r12 = np.power(sig_by_r6, 2)
lje = 4.0 * epsilon * (sig_by_r12 - sig_by_r6)
return lje
def fene(rij2):
return (-0.5 * K * R**2 * np.log(1-((np.sqrt(rij2) - r0) / R)**2))
def total_energy(coord):
# Non-bonded
e_nb = 0
for i in range(N):
for j in range(i-1):
ri = coord[i]
rj = coord[j]
rij = ri - rj
rij2 = np.dot(rij, rij)
if (np.sqrt(rij2) < rcutoff):
e_nb += lj(rij2)
# Bonded
e_bond = 0
for i in range(1, N):
ri = coord[i]
rj = coord[i-1]
rij = ri - rj
rij2 = np.dot(rij, rij)
e_bond += fene(rij2)
return e_nb + e_bond
def move(coord):
trial = np.ndarray.copy(coord)
for i in range(N):
delta = (2.0 * np.random.rand(3) - 1) * max_delta
trial[i] += delta
return trial
def accept(delta_e):
beta = 1.0/T
if delta_e <= 0.0:
return True
random_number = np.random.rand(1)
p_acc = np.exp(-beta*delta_e)
if random_number < p_acc:
return True
return False
if __name__ == "__main__":
# FENE parameters
K = 40
R = 0.3
r0 = 0.7
# LJ parameters
sigma = r0/0.33
epsilon = 1.0
# MC parameters
N = 50 # number of particles
rcutoff = 2.5*sigma
max_delta = 0.01
n_steps = 10000000
T = 0.5
coord = gen_chain(N, R)
energy_current = total_energy(coord)
traj = open('traj.xyz', 'w')
for step in range(n_steps):
if step % 1000 == 0:
traj.write(str(N) + '\n\n')
for i in range(N):
traj.write("C %10.5f %10.5f %10.5f\n" % (coord[i][0], coord[i][1], coord[i][2]))
print(step, energy_current)
coord_trial = move(coord)
energy_trial = total_energy(coord_trial)
delta_e = energy_trial - energy_current
if accept(delta_e):
coord = coord_trial
energy_current = energy_trial
traj.close()
The problem is that calculating rij2 = np.dot(rij, rij) in total energy with the constant values you use is always a very small number. Looking at the expression inside the log used to calculate FENE, np.log(1-((np.sqrt(rij2) - r0) / R)**2), I first noticed that you're taking the square root of rij2 which is not consistent with the formula you provided.
Secondly, notice that ((rij2 - r0) / R)**2 is the same as ((r0 - rij2) / R)**2, since the sign gets lost when squaring. Because rij2 is very small (already in the first iteration -- I checked by printing the values), this will be more or less equal to ((r0 - 0.05)/R)**2 which will be a number bigger than 1. Once you subtract this value from 1 in the log expression, 1-((np.sqrt(rij2) - r0) / R)**2 will be equal to np.nan (standing for "Not A Number"). This will propagate through all the function calls (for example, calling energy_trial = total_energy(coord_trial) will effectively set energy_trial to np.nan), until an error will be raised by some function.
Maybe you could do something with np.isnan() call, documented here. Moreover, you should check how you iterate through the coord (there's some inconsistencies throughout the code) -- I suggest you check the code review community as well.

How can I speed up this code, it has a very big input file

Could you please help me speed up this code?
It takes a very long time to run because of how big the input file is, thank you to anyone who helps out.
racers = [int(file[0].split()[0]) / float(x) for x in file[0].split()[1::]]
print("hi")
def av(race):
race = race.split()
j = 0
while j != len([float(race[0]) / float(x) for x in race[1::]]):
racers[j] = [float(race[0]) / float(x) for x in race[1::]][j] + racers[j]
j += 1
for i in range(1, len(file)):
av(file[i])
a = min(racers)
del(racers[racers.index(min(racers))])
b = min(racers)
c = b-a
h = int(c)
c-=h
m = int(c * 60)
c-=m/60
s = round(c * 60 * 60)
print(str(h) + "h" + str(m) + "m" + str(s) + "s")

Matlab: How to run code using multi threading/parallel computing?

I have Matlab code that simulates something called the 2-D Lid Driven Cavity Flow. In this code I have the following structure:
for i = 1:timeStep
%Lets call this Part 1
for a1 = 1:N
for b1 = 1:N
%calculates things
end
end
%Lets call this Part 2
for a2 = 1:N
for b2 = 1:N
%calculates things
end
end
%Lets call this Part 3
for a3 = 1:N
for b3 = 1:N
%calculates things
end
end
end
Since Part 1, Part 2, and Part 3 are independent pf each other I would like to compute them in parallel, or multi thread them, every time there is a timeStep (every iteration of primary for loop). Is there any way I can achieve this?
Thanks!
I include my code to to reference:
Nx = 50;
Ny = 50;
numTimesteps = 10000;
reynoldsNum = 1000;
dt = 0.0025;
numIter = 100000;
Beta = 1.5;
maxErr = 0.001;
ds = 1/(Nx + 1);
x1 = 0:ds:1;
x2 = 0:ds:1;
time = 0;
boundarySpeed = 1;
PHI = zeros(Nx+2, Ny+2);
OMEGA = zeros(Nx+2, Ny+2);
U = zeros(Nx+2, Ny+2);
V = zeros(Nx+2, Ny+2);
x2d = zeros(Nx+2, Ny+2);
y2d = zeros(Nx+2, Ny+2);
PRESSURE = zeros(Nx+2, Ny+2);
B = zeros(Nx+2, Ny+2);
pressureOLD = zeros(Nx+2, Ny+2);
W = zeros(Nx+2, Ny+2);
for i = 1:Nx+2
for j = 1:Ny+2
x2d(i,j) = x1(i);
y2d(i,j) = x2(j);
end
end
for timeStep = 1:numTimesteps
if(mod(timeStep,10000) == 0)
disp(timeStep);
end
OLDPHI = PHI;
OLDOMEGA = OMEGA;
OLDPRESSURE = PRESSURE;
parfor parJob = 1:4
switch parJob
%{
----------------------------------
STREAM FUNCTION CALCULATION
----------------------------------
%}
case 1
for iter = 1:numIter
ERRMATRIX = OLDPHI;
for i = 2:Nx+1
for j = 2:Ny+1
PHI(i,j) = (1/4) * Beta * (OLDPHI(i+1,j) + OLDPHI(i-1,j) + OLDPHI(i,j+1) + OLDPHI(i,j-1) + ...
ds * ds * OLDOMEGA(i,j)) + (1 - Beta) * OLDPHI(i,j);
end
end
Err = 0;
for i = 1:Nx+2
for j = 1:Ny+2
Err = Err + abs(ERRMATRIX(i,j) - PHI(i,j));
end
end
if (Err <= maxErr)
break;
end
OLDPHI = PHI;
end
%{
----------------------------------
BOUNDARY CONDITIONS FOR VORTICITY
----------------------------------
%}
case 2
for i = 2:Nx+1
for j = 2:Ny+1
OMEGA(i,1) = -2 * OLDPHI(i,2) / (ds * ds); % bottom wall
OMEGA(i,Ny+2) = -2 * OLDPHI(i,Ny+1) / (ds * ds) - 2 * boundarySpeed / ds; % top wall
OMEGA(1,j) = -2 * OLDPHI(2,j) / (ds * ds); % right wall
OMEGA(Nx+2,j) = -2 * OLDPHI(Nx+1,j) / (ds * ds); % left wall
end
end
%{
----------------------------------
VORTICITY CALCULATIONS
----------------------------------
%}
for i = 2:Nx+1
for j = 2:Ny+1
W(i,j) = -(1 / 4) * ((OLDPHI(i,j+1) - OLDPHI(i,j-1)) * (OLDOMEGA(i+1,j) - OLDOMEGA(i-1,j)) ...
- (OLDPHI(i+1,j) - OLDPHI(i-1,j)) * (OLDOMEGA(i,j+1) - OLDOMEGA(i,j-1))) / (ds * ds) ...
+(1 / reynoldsNum) * (OLDOMEGA(i+1,j) + OLDOMEGA(i-1,j) + OLDOMEGA(i,j+1) + ...
OLDOMEGA(i,j-1) - 4 * OLDOMEGA(i,j)) / (ds * ds);
end
end
OMEGA(2:Nx+1,2:Ny+1) = OLDOMEGA(2:Nx+1,2:Ny+1) + dt * W(2:Nx+1,2:Ny+1);
time = time + dt;
for i = 1:Nx
for j = 1:Ny
x2d(i,j) = x1(i);
y2d(i,j) = x2(j);
end
end
%{
----------------------------------
U AND V CALCULATIONS
----------------------------------
%}
case 3
for i = 2:Nx+1
for j = 2:Ny+1
U(i,j) = (OLDPHI(i,j+1) - OLDPHI(i,j)) / (2 * ds);
V(i,j) = -(OLDPHI(i+1,j) - OLDPHI(i,j)) / (2 * ds);
U(:,Ny+2) = 1;
V(Nx+2,:) = 0.0;
end
end
%{
----------------------------------
PRESSURE CALCULATIONS
----------------------------------
%}
otherwise
for i = 2:Nx+1
for j = 2:Ny+1
PRESSURE(i,j) = (1/4) * (pressureOLD(i+1,j) + pressureOLD(i-1,j) + pressureOLD(i,j+1) ...
+ pressureOLD(i,j-1)) - (1/2) * (((((OLDPHI(i-1,j) - 2 * OLDPHI(i,j) + ...
OLDPHI(i+1,j)) / (ds^2)) * ((OLDPHI(i,j-1) - 2 * OLDPHI(i,j) + OLDPHI(i,j+1)) / (ds^2))) ...
- (OLDPHI(i+1,j+1) - OLDPHI(i+1,j-1) - OLDPHI(i-1,j+1) + OLDPHI(i-1,j-1)) / (4 * (ds^2))) * ds^2);
end
pressureOLD = PRESSURE;
end
end
end
You can use parfor to run jobs in parallel.
result = cell(3, 1);
parfor k = 1:3
result{k} = ['result-' num2str(k)];
switch k
case 1
disp('do part one')
case 2
disp('do part two')
otherwise
disp('do part three')
end
end

Resources