I have to do a speed comparison of a simple program for detrended fluctuation analysis for Python, Matlab and C++. Unfortunately the speed of my Python and Matlab code was about two orders of magnitude slower then I expected. So either is what I read about those languages wrong, or I wrote the code in a very inefficient way.
That's why I'm asking if there are any obvious ways to speed up the code pasted below. You can download the Data here if you would like to run the code yourself.
Python hrv_dfa module
import numpy as np
import matplotlib.pyplot as plt
import math
import sys
import time
def hrv_dfa(file, version, verbose):
r_data = np.fromfile(file, dtype=float, count=-1, sep=" ")
# compute intervals
RR = RR_intervals_from_data(r_data)
RRavg = RR.mean(axis = 0)
y = (RR - RRavg).cumsum(axis = 0)
if (verbose):
fig = plt.ion().figure()
fig.ion()
fig.plot(y, 'o')
fig.show()
N = len(y)
#window size
lk = range(5, int(np.floor(N/10)+1))
E = np.zeros((len(lk), 1), dtype=float)
tic = time.time()
for k in range(0, len(lk)):
window = lk[k]
Sq_sum = 0
y_detrended = np.zeros((len(y), 1), dtype=float)
if (version == 1):
for i in range(0, N-window, window):
y_in_window = y[i:i+window]
x_in_window = range(i,i+window)
(a, b) = np.polyfit(x_in_window, y_in_window, 1)
y_regression = np.add(np.multiply(a, x_in_window), b)[np.newaxis]
y_detrended[i:i+window] = y_in_window - y_regression.T # bylo [i:i+window-1]
elif (version == 2):
for i in range(0, N-window):
#wybor danych z danego okna
x_in_window = range(i, i+window)
y_in_window = y[i:i+window]
#regresja liniowa dla danej probki
(a, b) = np.polyfit(x_in_window, y_in_window, 1)
#usuwanie trendu
if (not (window % 2 == 0)):
y_regression = a*(i+window/2+0.5)+b
y_detrended[i] = y[i+window/2+0.5] - y_regression
else:
y_regression1 = a*(i+window/2-0.5)+b
y_regression2 = a*(i+window/2+0.5)+b
y_detrended[i] = (y[i+window/2-0.5] - y_regression1 + y[i+window/2+0.5] - y_regression2)/2
else:
print( 'unsupported window version')
sys.exit([1])
if (verbose):
fig.plot(y_detrended, 'bl-')
fig.show()
Sq_sum = np.dot(y_detrended.T, y_detrended)
E[k] = np.sqrt(Sq_sum/N)
toc = time.time()
len(E)
if verbose:
fig = plt.figure()
x = np.log10(lk)
y = np.log10(E)
if (verbose):
plt.plot(x, y, 'o')
(a, b) = np.polyfit(x, y, 1)
if (verbose):
y_all_fitted = a*x+b
plt.plot(x, y_all_fitted)
#print lk[0:12]
(a1, b1) = np.polyfit(x[0:12], y[0:12], 1)
if (verbose):
y_short_term_fitted = a1*x[0:12]+b1
plt.plot(x[0:12], y_short_term_fitted)
(a2, b2) = np.polyfit(x[12:], y[12:], 1)
if (verbose):
y_long_term_fitted = a2*x[12:]+b2
plt.plot(x[12:], y_long_term_fitted)
if (verbose):
plt.show()
exec_time = toc - tic
print( "a = %f" % a)
print( "a1 = %f" % a1)
print( "a2 = %f" % a2)
print( "exec_time = %f" % exec_time)
#plt.show(block=True)
return a, a1, a2, exec_time
def RR_intervals_from_data(data):
RR = np.zeros((len(data), 1), dtype=float)
for t in range(len(data)-1):
RR[t] = (data[t+1]-data[t])
return RR
if __name__ == "__main__":
hrv_dfa(arg[1], arg[2], arg[3])
Python test code (runs every sample 10 times and saves results and execution time to csv)
import hrv_dfa34 as hrv_dfa
import sys
import csv
def test_hrv_dfa():
file_numbers = ["100", "101"] #, "102", "103", "104", "105", "106", "107", \
#"108", "109", "111", "112", "113", "114", "115", "116", \
#"117", "118", "119", "121", "122", "123", "124", "201", \
#"202", "203", "205", "207", "208", "209", "210", "212", \
#"213", "214", "215", "217", "219", "220", "221", "222", \
#"223", "228", "230", "231", "232", "233", "234"]
prefix = "..\Data\RPeakData"
file_names = []
for i in range(0, len(file_numbers)):
file_names.append(prefix + file_numbers[i] + ".txt")
for file_number_idx in range(0, len(file_numbers)):
for test_number in range(0, 10):
a, a1, a2, exec_time = hrv_dfa.hrv_dfa(file_names[file_number_idx], 1, False)
with open('fwrite_sw.csv', 'a', newline='') as fwrite_sw:
writer = csv.writer(fwrite_sw, delimiter=';', \
quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow([file_numbers[file_number_idx], a[0], a1[0], a2[0], exec_time])
#fwrite_sw.write( + " " + a + " " + a1 + " " + a2 + " " + exec_time + "\n")
for file_number_idx in range(0, len(file_numbers)):
for test_number in range(0, 10):
a, a1, a2, exec_time = hrv_dfa.hrv_dfa(file_names[file_number_idx], 2, False)
with open('fwrite_mw.csv', 'a', newline='') as fwrite_mw:
writer2 = csv.writer(fwrite_mw, delimiter=';', \
quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer2.writerow([file_numbers[file_number_idx], a[0], a1[0], a2[0], exec_time])
#fwrite_mw.write(file_numbers[file_number_idx] + " " + a + " " + a1 + " " + a2 + " " + exec_time + "\n")
print('\nDone!')
if __name__ == '__main__':
test_hrv_dfa()
Matlab hrv_dfa module
function [ alpha, alpha1, alpha2, exec_time ] = hrv_dfa(file, version, verbose)
% skrypt ładujący dane i uruchamiający poszczególne metody hrv_dfa
% metoda 1 - stałe okno (obcinana nadmiarowa część próbek)
% metoda 2 - ślizgające się okno
fileID = fopen(file, 'r');
formatSpec = '%f';
r_data = fscanf(fileID, formatSpec);%cumsum(r_intervals) % << sztuczne dane
fclose(fileID);
%save r_data.out r_data -ASCII
RR = RR_intervals_from_data(r_data);
RRavg = mean(RR);
y = cumsum(RR-RRavg);
N = length(y);
lk = 5:floor(N/10);
E = zeros(1,length(lk));
tic;
for k = 1:length(lk)
window = lk(k);
Sq_sum = 0;
y_detrended = zeros(size(y));
if version == 1
for i = 1:window:(N-window+1)
y_in_window = y(i:i+window-1);
x_in_window = (i:i+window-1)';
linear_regression_coeffs = polyfit(x_in_window, y_in_window,1);
a = linear_regression_coeffs(1);
b = linear_regression_coeffs(2);
y_regression = a*x_in_window+b;
y_detrended(i:i+window-1) = y_in_window - y_regression;
end
elseif version == 2
for i = 1:N-window
x_in_window = (i:i+window-1)';
y_in_window = y(x_in_window);
linear_regression_coeffs = polyfit(x_in_window, y_in_window,1);
a = linear_regression_coeffs(1);
b = linear_regression_coeffs(2);
if (~(mod(window, 2)==0))
y_regression = a*(i+window/2 - 0.5)+b;
y_detrended(i) = y(i + window/2 - 0.5) - y_regression;% +window/2
else
y_regression1 = a*(i+window/2-1)+b;
y_regression2 = a*(i+window/2)+b;
y_detrended(i) = (y(i+window/2-1) - y_regression1 + y(i+window/2) - y_regression2)/2;
end
end
else
exit('unsupported window version');
end
if verbose == true
figure(99);
plot(y)
hold on;
plot(y_detrended)
end
Sq_sum = y_detrended'*y_detrended;
E(k) = sqrt(Sq_sum/N);
end
exec_time = toc;
x = log10(lk);
y = log10(E);
if verbose == true
figure(999);
hold off
plot(x, y, '.')
end
allRegression = polyfit(x,y,1);
alpha = allRegression(1);
beta = allRegression(2);
y_all_fitted = alpha*x+beta;
shortTermRegression = polyfit(x(1:12), y(1:12), 1);
alpha1 = shortTermRegression(1);
beta1 = shortTermRegression(2);
y_short_term_fitted = alpha1*x(1:12)+beta1;
longTermRegression = polyfit(x(12:end), y(12:end), 1);
alpha2 = longTermRegression(1);
beta2 = longTermRegression(2);
y_long_term_fitted = alpha2*x(12:end)+beta2;
if verbose == true
hold on;
h1 = plot(x,y_all_fitted, 'k-', 'LineWidth', 2.5);
h2 = plot(x(1:12), y_short_term_fitted, 'g-', 'LineWidth', 2.5);
h3 = plot(x(12:end), y_long_term_fitted, 'r-', 'LineWidth', 2.5);
legend([h1 h2 h3], {'prosta aproksymująca dla wszystkich lk', ...
'prosta aproksymująca dla log10(5) <= lk <=log10(16)', ...
'prosta paroksymująca dla log10(16) < lk'}, 'Location', 'northwest');
xlabel('log10(lk)');
ylabel('log10(E(lk))');
grid on;
hold off;
end
% helper - returns intervals
function [RR] = RR_intervals_from_data(data)
RR = zeros(size(data));
for t = 1:(size(data)-1)
RR(t) = data(t+1)-data(t);
end
end
end
Matlab test code (runs every sample 10 times and saves to csv)
file_numbers = ['100'; '101'; '102'; '103'; '104'; '105'; '106'; '107'; ...
'108'; '109'; '111'; '112'; '113'; '114'; '115'; '116'; ...
'117'; '118'; '119'; '121'; '122'; '123'; '124'; '201'; ...
'202'; '203'; '205'; '207'; '208'; '209'; '210'; '212'; ...
'213'; '214'; '215'; '217'; '219'; '220'; '221'; '222'; ...
'223'; '228'; '230'; '231'; '232'; '233'; '234'];
prefix = '..\Data\RPeakData';
file_names = [];
for i = 1:size(file_numbers, 1)
file_names = [file_names; [prefix, file_numbers(i, :), '.txt']];
end
for file_number_idx = 1:size(file_numbers, 1)
for test_number = 1:10
[a, a1, a2, exec_time] = hrv_dfa(file_names(file_number_idx, :), 1, false);
toStore = [str2num(file_numbers(file_number_idx,:)), a, a1, a2, exec_time];
dlmwrite('fmwrite_sw.csv', toStore, '-append', 'delimiter', ';');
end
end
for file_number_idx = 1:length(file_numbers)
for test_number = 1:10
[a, a1, a2, exec_time] = hrv_dfa(file_names(file_number_idx, :), 2, false);
toStore = [str2num(file_numbers(file_number_idx,:)), a, a1, a2, exec_time];
dlmwrite('fmwrite_mw.csv', toStore, '-append', 'delimiter', ';');
end
end
display('Done!');
Related
I have a for loop as follows:
import MDAnalysis as mda
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from tqdm import tqdm as tq
import MDAnalysis.analysis.pca as pca
import random
def PCA_projection(pdb,dcd,atomgroup):
u = mda.Universe(pdb,dcd)
PSF_pca = pca.PCA(u, select=atomgroup)
PSF_pca.run(verbose=True)
n_pcs = np.where(PSF_pca.results.cumulated_variance > 0.95)[0][0]
atomgroup = u.select_atoms(atomgroup)
pca_space = PSF_pca.transform(atomgroup, n_components=n_pcs)
PC1_proj = [pca_space[i][0] for i in range(len(pca_space))]
PC2_proj = [pca_space[i][1] for i in range(len(pca_space))]
return PC1_proj, PC2_proj
def Read_bias_potential(bias_potential):
Bias_potential = pd.read_csv(bias_potential)
Bias_potential = Bias_potential['En-User']
Bias_potential = Bias_potential.values.tolist()
W = [math.exp((-1 * i) / (0.001987*300)) for i in Bias_potential]
return W
def Bin(PC1_prj, PC2_prj, frame_num, min_br1, max_br1, min_br2, max_br2, bin_num, W):
#import pdb;pdb.set_trace()
data1 = PC1_prj[0:frame_num]
bins1 = np.linspace(min_br1, max_br1, bin_num)
bins1 = np.round(bins1,2)
digitized1 = np.digitize(data1, bins1)
binc1 = np.arange(min_br1 + (max_br1 - min_br1)/2*bin_num,
max_br1 + (max_br1 - min_br1)/2*bin_num, (max_br1 - min_br1)/bin_num, dtype = float)
binc1 = np.around(binc1,3)
data2 = PC2_prj[0:frame_num]
bins2 = np.linspace(min_br2, max_br2, bin_num)
bins2 = np.round(bins2,2)
digitized2 = np.digitize(data2, bins2)
binc2 = np.arange(min_br2 + (max_br2 - min_br2)/2*bin_num, max_br2 + (max_br2 - min_br2)/2*bin_num, (max_br2 - min_br2)/bin_num, dtype = float)
binc2 = np.around(binc2,3)
w_array = np.zeros((bin_num,bin_num))
for j in range(frame_num):
w_array[digitized1[j]][digitized2[j]] += (W[digitized1[j]] + W[digitized2[j]])
for m in range(bin_num):
for n in range(bin_num):
if w_array[m][n] == 0:
w_array[m][n] = 1e-100
return w_array, binc1, binc2
def gaussian(Sj1,Slj1,Sj2,Slj2,count):
sigma1 = 0.5
sigma2 = 0.5
Kb = 0.001987204
T = 300
h0 = 0.0001
g = 0
C1 = 0
C2 = 0
for i in range((np.where(Slj2 == Sj2)[0][0] - 5),(np.where(Slj2 == Sj2)[0][0] + 6)):
if i < 0:
C2 = i + 1000
elif i > 999:
C2 = i - 1000
else:
C2 = i
for j in range((np.where(Slj1 == Sj1)[0][0] - 5),(np.where(Slj2 == Sj2)[0][0] + 6)):
if j < 0:
C1 = j + 1000
elif j > 999:
C1 = j -1000
else:
C1 = j
g = g + count[C2,C1] * h0 * np.exp( (-(Sj1 - Slj1[C1]) ** 2 / (2 * sigma1 ** 2)) + (-(Sj2 - Slj2[C2]) ** 2 / (2 * sigma2 ** 2)) )
return np.exp(-g / (Kb * T))
def resampling(binc1, binc2, w_array):
# import pdb;pdb.set_trace()
l =1000
F = np.zeros((l,l))
count = np.zeros((l,l))
Wn = w_array
for i in tq(range(10000000)):
SK1 = random.choice(binc1)
SK2 = random.choice(binc2)
SL1 = random.choice(binc1)
SL2 = random.choice(binc2)
while SK1 == SL1:
SL1 = random.choice(binc1)
while SK2 == SL2:
SL2 = random.choice(binc2)
F[np.where(binc2 == SK2)[0][0]][np.where(binc1 == SK1)[0][0]] = gaussian(SK1,binc1,SK2,binc2,count)
F[np.where(binc2 == SK2)[0][0]][np.where(binc1 == SK1)[0][0]] = gaussian(SL1,binc1,SL2,binc2,count)
W_SK = Wn[np.where(binc2 == SK2)[0][0]][np.where(binc1 == SK1)[0][0]] * F[np.where(binc2 == SK2)[0][0]][np.where(binc1 == SK1)[0][0]]
W_SL = Wn[np.where(binc2 == SL2)[0][0]][np.where(binc1 == SL1)[0][0]] * F[np.where(binc2 == SL2)[0][0]][np.where(binc1 == SL1)[0][0]]
if W_SK <= W_SL:
SK1 = SL1
SK2 = SL2
else:
a = random.random()
if W_SL/W_SK >= a:
SK1 = SL1
SK2 = SL2
else:
SK1 = SK1
SK2 = SK2
#print('SK =',SK)
count[np.where(binc2 == SK2)[0][0]][np.where(binc1 == SK1)[0][0]] += 1
return F
where binc1 and binc2 are two np.arrays, gaussian is a gaussian fxn I defined, is there anyway I can speed up this for loop? Now 1000000 steps takes approximately 50 mins. I am thinking about using pytorch but I got no idea on how to do it. Any suggestions would be helpful!
Thanks
I tried to use pytorch, like put all the variables on gpu but it only does worse.
I have a certain number of matrix in a list and when I try to append a matrix to the NumPy array It only appends the specified row and when I try to edit the code to append the whole matrix It keep returning the following error:
Traceback (most recent call last):
File "so.py", line 129, in <module>
parents = selection(cal_fitness(t1, t2, t3, matlist, 300, arr), 2, matlist) #
File "so.py", line 124, in selection
parents[i, :] = population[max_fitness_idx[0][0]]
ValueError: could not broadcast input array from shape (3,5) into shape (5,)
The error related function:
def selection(fitness, num_parents, population):
fitness = list(fitness)
parents = numpy.empty((num_parents, len(population)))
for i in range(num_parents):
max_fitness_idx = numpy.where(fitness == numpy.max(fitness))
#parents[i, :] = population[max_fitness_idx[0][0]][2]
parents[i, :] = population[max_fitness_idx[0][0]]
fitness[max_fitness_idx[0][0]] = -999999
return parents.astype(int)
parents = selection(cal_fitness(t1, t2, t3, matlist, 300, arr), 2, matlist)
print(parents)
The full code:
import numpy
import random
import pandas
wsn = numpy.arange(1, 6)
taskn = 3
t1 = numpy.random.randint(30, 200, size=len(wsn))
t2 = numpy.random.randint(30, 200, size=len(wsn))
t3 = numpy.random.randint(30, 200, size=len(wsn))
# print('\nGenerated Data:\t\n\nNumber \t Task 1 \t Task 2 \t Task 3\n')
ni = min(len(t1), len(t2), len(t3))
# for i in range(ni):
# print('\t {0} \t {1} \t {2} \t\t {3}\n'.format(wsn[i], t1[i], t2[i], t3[i]))
# print('\n\n')
qmin = 50
qmax = 140
for i in range(len(t1)):
if t1[i] <= qmin or t1[i] >= qmax:
# t1=numpy.delete(t1,i)
t1[i] = 0
for i in range(len(t2)):
if t2[i] <= qmin or t2[i] >= qmax:
# t2=numpy.delete(t2,i)
t2[i] = 0
for i in range(len(t3)):
if t3[i] <= qmin or t3[i] >= qmax:
# t3=numpy.delete(t3,i)
t3[i] = 0
i = 0
m = max(len(t1), len(t2), len(t3))
if t1[i] == 0 and t2[i] == 0 and t3[i] == 0:
t1 = numpy.delete(t1, i)
t2 = numpy.delete(t2, i)
t3 = numpy.delete(t3, i)
i += 1
solperpop = len(wsn)
gen = 20
j = 0
pop_size = (taskn, solperpop)
# print('population size: {}'.format(pop_size))
# for j in range(ni):
# pop_size=list(solperpop,taskn)
matlist = list()
# print('\n\n')
i = 0
k = 0
nbrofindv = 5
arr = []
for i in range(nbrofindv):
init_pop = numpy.zeros(pop_size, dtype=int)
init_pop = init_pop.astype(int)
k = 0
l = 0
for k in range(taskn):
l = random.randrange(solperpop - 1)
init_pop[k][l] = 1
arr.append(l)
matlist.append(init_pop)
pandas.set_option('display.max_columns', None)
pandas.set_option('display.width', None)
zipped = pandas.DataFrame(list(zip(*matlist)))
# , columns=['Individual 1', 'Individual 2', 'Individual 3', 'Individual 4', 'Individual 5'])
print(zipped)
print('\n\n')
i = 0
for i in range(len(wsn)):
if t1[i] == 0:
if init_pop[0][i] != 0:
init_pop[0][i] == 0
if t2[i] == 0:
if init_pop[1][i] != 0:
init_pop[1][i] == 0
if t3[i] == 0:
if init_pop[2][i] != 0:
init_pop[2][i] == 0
def cal_fitness(task1, task2, task3, matix, mmax, array):
fitness = numpy.empty(len(matix))
S1 = numpy.empty(len(matix), dtype=int)
z = 0
for i in range(len(matix)):
S1[i] = task1[array[0 + z]] + task2[array[1 + z]] + task3[array[2 + z]]
z += 3
if S1[i] <= mmax:
fitness[i] = S1[i]
else:
fitness[i] = 0
return fitness.astype(int)
fitness = cal_fitness(t1, t2, t3, matlist, 300, arr)
def selection(fitness, num_parents, population):
fitness = list(fitness)
parents = numpy.empty((num_parents, len(population)))
for i in range(num_parents):
max_fitness_idx = numpy.where(fitness == numpy.max(fitness))
#parents[i, :] = population[max_fitness_idx[0][0]][2]
parents[i, :] = population[max_fitness_idx[0][0]]
fitness[max_fitness_idx[0][0]] = -999999
return parents.astype(int)
parents = selection(cal_fitness(t1, t2, t3, matlist, 300, arr), 2, matlist)
print(parents)
print('\n\n')
def crossover(parents, num_offsprings):
offsprings = numpy.empty((num_offsprings, parents.shape[1]))
crossover_point = int(parents.shape[1] / 2)
crossover_rate = 0.5
i = 0
while parents.shape[0] < num_offsprings:
parent1_index = i % parents.shape[0]
parent2_index = (i + 1) % parents.shape[0]
x = random.random()
if x > crossover_rate:
continue
parent1_index = i % parents.shape[0]
parent2_index = (i + 1) % parents.shape[0]
offsprings[i, 0:crossover_point] = parents[parent1_index, 0:crossover_point]
offsprings[i, crossover_point:] = parents[parent2_index, crossover_point:]
i += 1 # <== modified
return offsprings # <== modified
print(crossover(parents, 2)) # <== modified
This issue is related to dimensions that specified for parents, which is 2d now so must be modified to 3d. So, IIUC, you can achieve this aim by:
def selection(fitness, num_parents, population):
fitness = list(fitness)
# parents shape is modified (a new axis with the needed length is added)
parents = numpy.empty((num_parents, len(population[0]), len(population[0][0]))) # <==
for i in range(num_parents):
max_fitness_idx = numpy.where(fitness == numpy.max(fitness))
parents[i, :] = population[max_fitness_idx[0][0]]
fitness[max_fitness_idx[0][0]] = -999999
return parents.astype(int)
Hi I am trying to write a trust-region algorithm using the dogleg method with python for a class I have. I have a Newton's Method algorithm and Broyden's Method algorthm that agree with each other but I can't seem to get this Dogleg method to work.
Here is the function I am trying to find the solution to:
def test_function(x):
x1 = float(x[0])
x2 = float(x[1])
r = np.array([[x2**2 - 1],
[np.sin(x1) - x2]])
return r
and here is the jacobian I wrote
def Test_Jacobian(x, size):
e = create_ID_vec(size)
#print(e[0])
epsilon = 10e-8
J = np.zeros([size,size])
#print (J)
for i in range(0, size):
for j in range(0, size):
J[i][j] = ((test_function(x[i]*e[j] + epsilon*e[j])[i] - test_function(x[i]*e[j])[i])/epsilon)
return J
and here is my Trust-Region algorithm:
def Trust_Region(x):
trust_radius = 1
max_trust = 300
eta = rand.uniform(0,.25)
r = test_function(x) # change to correspond with the function you want
J = Test_Jacobian(r, r.size) # change to correspond with function
i = 0
iteration_table = [i]
function_table = [vector_norm(r, r.size)]
while vector_norm(r, r.size) > 10e-10:
print(x, 'at iteration', i, "norm of r is", vector_norm(r, r.size))
p = dogleg(x, r, J, trust_radius)
rho = ratio(x, J, p)
if rho < 0.25:
print('first')
trust_radius = 0.25*vector_norm(p,p.size)
elif rho > 0.75 and vector_norm(p,p.size) == trust_radius:
print('second')
trust_radius = min(2*trust_radius, max_trust)
else:
print('third')
trust_radius = trust_radius
if rho > eta:
print('x changed')
x = x + p
#r = test_function(x)
#J = Test_Jacobian(r, r.size)
else:
print('x did not change')
x = x
r = test_function(x) # change to correspond with the function you want
J = Test_Jacobian(r, r.size) # change to correspond with function
i = i + 1
#print(r)
#print(J)
#print(vector_norm(p,p.size))
print(rho)
#print(trust_radius)
iteration_table.append(i)
function_table.append(vector_norm(r,r.size))
print ('The solution to the non-linear equation is: ', x)
print ('This solution was obtained in ', i, 'iteratations')
plt.figure(figsize=(10,10))
plt.plot(iteration_table, np.log10(function_table))
plt.xlabel('iteration number')
plt.ylabel('function value')
plt.title('Semi-Log Plot for Convergence')
return x, iteration_table, function_table
def dogleg(x, r, J, trust_radius):
tau_k = min(1, vector_norm(J.transpose().dot(r), r.size)**3/(trust_radius*r.transpose().dot(J).dot(J.transpose().dot(J)).dot(J.transpose()).dot(r)))
p_c = -tau_k*(trust_radius/vector_norm(J.transpose().dot(r), r.size))*J.transpose().dot(r)
if vector_norm(p_c, p_c.size) == trust_radius:
print('using p_c')
p_k = p_c
else:
p_j = -np.linalg.inv(J.transpose().dot(J)).dot(J.transpose().dot(r))
print ('using p_j')
tau = tau_finder(x, p_c, p_j, trust_radius, r.size)
p_k = p_c + tau*(p_j-p_c)
return p_k
def ratio(x, J, p):
r = test_function(x)
r_p = test_function(x + p)
print (vector_norm(r, r.size)**2)
print (vector_norm(r_p, r_p.size)**2)
print (vector_norm(r + J.dot(p), r.size)**2)
rho_k =(vector_norm(r, r.size)**2 - vector_norm(r_p, r_p.size)**2)/(vector_norm(r, r.size)**2 - vector_norm(r + J.dot(p), r.size)**2)
return rho_k
def tau_finder(x, p_c, p_j, trust_radius, size):
a = 0
b = 0
c = 0
for i in range(0, size):
a = a + (p_j[i] - p_c[i])**2
b = b + 2*(p_j[i] - p_c[i])*(p_c[i] - x[i])
c = (p_c[i] - x[i])**2
c = c - trust_radius**2
tau_p = (-b + np.sqrt(b**2 - 4*a*c))/(2*a)
tau_m = (-b - np.sqrt(b**2 - 4*a*c))/(2*a)
#print(tau_p)
#print(tau_m)
if tau_p <= 1 and tau_p >=0:
return tau_p
elif tau_m <= 1 and tau_m >=0:
return tau_m
else:
print('error')
return 'error'
def model_function(p):
r = test_function(x)
J = Test_Jacobian(r, r.size)
return 0.5*vector_norm(r + J.dot(p), r.size)**2
The answer should be about [[1.57076525], [1. ]]
but here is the output after about 28-30 iterations:
ZeroDivisionError Traceback (most recent call last)
<ipython-input-359-a414711a1671> in <module>
1 x = create_point(2,1)
----> 2 Trust_Region(x)
<ipython-input-358-7cb77bd44d7b> in Trust_Region(x)
11 print(x, 'at iteration', i, "norm of r is", vector_norm(r, r.size))
12 p = dogleg(x, r, J, trust_radius)
---> 13 rho = ratio(x, J, p)
14
15 if rho < 0.25:
<ipython-input-358-7cb77bd44d7b> in ratio(x, J, p)
71 print (vector_norm(r_p, r_p.size)**2)
72 print (vector_norm(r + J.dot(p), r.size)**2)
---> 73 rho_k =(vector_norm(r, r.size)**2 - vector_norm(r_p, r_p.size)**2)/(vector_norm(r, r.size)**2 - vector_norm(r + J.dot(p), r.size)**2)
74 return rho_k
75
ZeroDivisionError: float division by zero
import os
import sys
import math
import cvxopt as cvx
import picos as pic
import pandas as pd
import matplotlib.pyplot as plt
from gurobipy import *
from statsmodels.tsa.arima_model import ARIMA
import numpy as np
from scipy import *
#import DeferableLoad
OPTmodel = Model('OPTIMIZER')
#general parameters
Tamb =22
N = 1440 # maximum iteration
i = range(1, N)
COP= 3.4 # Coeffient of performance
'''
Prediction need to be added here
'''
# Datacenter room defintion
R = 10 #length of room
B = 7
H = 9 #Height of room
L = 10
dT = 60
A = 2*((L*B)+(B*H)+(H*L))
Thick = 0.33 # thickness of wall
k = 0.7 # thermal conductivity of wall
mAir = 1.2 * (L * B * H)
C = 718
landa = k * A / Thick
a0 = 0.05 / dT
a1 = 1
ki = math.exp(-(landa * 60) / (mAir * C)) # value that constant and its related to property of room
kc = (1 - ki) * a0
ko = (1 - ki) * a1
kp = (1 - ki) * (COP / landa)
Tmin= 18
Tmax= 27
Tamb= 22
PcoolingRated = 100
Pbess_rated = 30.462
Pbess_ratedN = -30.462
Ebess_min = 0
Ebess_max = 300
with open ('Pcooling.csv','r') as f:
Pcooling = []
for line in f:
Pcooling.append(line)
f.close()
with open ('ITpower.csv','r') as f1:
ITload = []
for line1 in f1:
ITload.append(line1)
f1.close()
with open ('DR.csv','r') as f2:
DR =[]
for line2 in f2:
DR.append(line2)
f2.close()
print ITload
print Pcooling
print DR
for i in range(1,200):
for it in range(1, 1440):
Tm = np.empty(1440)
Tm.fill(18)
TmA = np.empty(1440)
TmA.fill(27)
Phvac_flex = {}
Phvac_up = {}
Phvac_down_= {}
Phvac_up_ = {}
Pbess_out_ = {}
Pbess_in_ = {}
Phvac_down = {}
Pbess_flex_ = {}
Pbess_flex = {}
Phvac_flex_ = {}
Pbess_in = {}
Pdc = {}
Pdc_base = {}
Pflex_i = {}
Tdc_i = {}
Pbess_out ={}
Ebess_i = {}
Phvac_flex[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS,name="PHVAC_flex"+str(i))
Phvac_up[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PHVAC_up" + str(i))
Phvac_up_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PHVAC_up_" + str(i))
Phvac_down_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PHVAC_down_" + str(i))
Pbess_out_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_out_" + str(i))
Pbess_in_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_in_" + str(i))
Phvac_down[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PHVAC_down" + str(i))
Pbess_flex_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_flex_" + str(i))
Pbess_flex[i] = OPTmodel.addVar(lb=-GRB.INFINITY,ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_flex" + str(i))
Phvac_flex_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PHVAC_flex_" + str(i))
Pbess_in[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_in" + str(i))
Pdc[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PDC" + str(i))
Pdc_base[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PDC_base" + str(i))
Pflex_i[i]= OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="Pflex_i" + str(i))
Tdc_i[i]= OPTmodel.addVar(ub=GRB.INFINITY,vtype = GRB.CONTINUOUS, name = "Tdc_i" + str(i))
Pbess_out[i] = OPTmodel.addVar(lb=-GRB.INFINITY,ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_out" + str(i))
Ebess_i[i]= OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS,name="Ebess_i" + str(i))
Pflex_i[1] = 0
Pflex_i[1] = 0
Tdc_i[0] = 18
Phvac_flex[1] = 0
# Phvac_flex_[1] = 0
Phvac_down[1] = 0
Phvac_up[1] = 0
Phvac_down_[1] = 0
Phvac_up_[1] = 0
# Phvac_down_pos[1] = 0
# Phvac_up_pos(1) = 0;
Pbess_flex[1] = 0
# Pbess_flex_[1] = 0
Pbess_out[1] = 0
Pbess_in[1] = 0
# Pbess_out_[1] = 0
Pbess_in_[1] = 0
# Pbess_out_pos[1] = -250
# Pbess_in_pos(1) = 250;
Ebess_i[1] = 150
OPTmodel.update()
'''
if float(DR[i]) > 0:
Phvac_down_[i] = 0
Phvac_up_[i] = float(DR[i])
Pbess_out_[i] = 0
Pbess_in_[i] = float(DR[i])
#Pbess_flex_[i] = Pbess_in_[i] + Pbess_out_[i]
#Phvac_flex_[i] = Phvac_down_[i] + Phvac_up_[i]
OPTmodel.update()
elif float(DR[i]) < 0:
Phvac_down_[i] = float(DR[i])
Phvac_up_[i] = 0
#Phvac_flex_[i] = Phvac_down_[i] + Phvac_up_[i]
Pbess_out_[i] = float(DR[i])
Pbess_in_[i] = 0
#Pbess_flex_[i] = Pbess_in_[i] + Pbess_out_[i]
OPTmodel.update()
else:
Phvac_down_[i] = 0
Phvac_up_[i] = 0
Phvac_flex_[i] = Phvac_down_[i] + Phvac_up_[i]
Pbess_out_[i] = 0
Pbess_in_[i] = 0
Pbess_flex_[i] = Pbess_in_[i] + Pbess_out_[i]
OPTmodel.update()
'''
#print Phvac_up.values()
#print Phvac_flex_[i]
print OPTmodel
OPTmodel.update()
ConHVAC1 = OPTmodel.addConstr(Phvac_flex[i] == Phvac_up[i] + Phvac_down[i], name='ConHVAC1')
ConHVAC2 = OPTmodel.addConstr(0 <= Phvac_flex[i] , name='ConHVAC2')
ConHVAC3 = OPTmodel.addConstr(Phvac_flex[i] <= PcoolingRated, name='ConHVAC3')
PH = pd.read_csv('Pcooling.csv')
PHVAC = PH.values
newList2 = map(lambda x: x / 1000, PHVAC)
p=[]
p=PcoolingRated-newList2[i]
#CONHVAC4 = OPTmodel.addConstr(Phvac_up[i]==np.minimum((Phvac_up_[i]),(float(newList2[i]))))
#Phvac_u(1:MaxIter) == min(Phvac_u_(1:MaxIter), (repelem(Phvac_max, MaxIter) - (Pcooling(1:MaxIter)'/1000)))
ConTemp1 = OPTmodel.addConstr(Tm[it] <= Tdc_i[i] <= TmA[it], name='ConTemp1')
ConBESS1 = OPTmodel.addConstr(Pbess_ratedN <= Pbess_flex[i] <= Pbess_rated, name='ConBESS1')
ConBESS2 = OPTmodel.addConstr(Pbess_flex[i] == Pbess_in[i] + Pbess_out[i], name='ConBESS2')
ConBESS3 = OPTmodel.addConstr(0 <= Pbess_in[i] <= min(Pbess_rated, Pbess_in_[i]), name='ConBESS3')
ConBESS4 = OPTmodel.addConstr(np.maximum(Pbess_ratedN,Pbess_out_[i]) <= Pbess_out[i]<=0 , name='ConBESS4') # need to modifty
ConEBESS1 = OPTmodel.addConstr(Ebess_min <= Ebess_i[i], name='ConEBESS1')
ConEBESS2 = OPTmodel.addConstr(Ebess_i[i] <= Ebess_max, name='ConEBESS2')
D = pd.read_csv('DR.csv').values
DRN = map(lambda x: x / 1000, D)
PDRN=map(lambda x: x / 4.8, DRN)
if float((PDRN[i])) > 0:
CON1 = OPTmodel.addConstr(Pbess_flex_[i] == Pbess_in_[i] + Pbess_out_[i],'CON1')
CON2 = OPTmodel.addConstr(Phvac_flex_[i] == Phvac_up_[i] + Phvac_down_[i],'CON2')
CON3=OPTmodel.addConstr(Phvac_down_[i] == 0, name='CON3')
CON4=OPTmodel.addConstr(Phvac_up_[i] == float((PDRN[i])),name='CON4')
CON5=OPTmodel.addConstr(Pbess_out_[i] == 0,name='CON5')
CON6=OPTmodel.addConstr(Pbess_in_[i] == float((PDRN[i])),name='CON6')
elif float(np.transpose(PDRN[i])) < 0:
CON7=OPTmodel.addConstr(Phvac_down_[i] == float(np.transpose(PDRN[i])),name='CON7')
CON8=OPTmodel.addConstr(Phvac_up_[i] == 0,name='CON8')
# Phvac_flex_[i] = Phvac_down_[i] + Phvac_up_[i]
CON9=OPTmodel.addConstr(Pbess_out_[i] == float((PDRN[i])),name='CON9')
CON10=OPTmodel.addConstr(Pbess_in_[i] == 0,name='CON10')
else:
CON11=OPTmodel.addConstr(Phvac_down_[i] == 0,name='CON11')
CON12=OPTmodel.addConstr(Phvac_up_[i] == 0,name='CON12')
CON13=OPTmodel.addConstr(Phvac_flex_[i] == Phvac_down_[i] + Phvac_up_[i],name='CON13')
CON14=OPTmodel.addConstr(Pbess_out_[i] == 0)
CON15=OPTmodel.addConstr(Pbess_in_[i] == 0,name='CON15')
CON16=OPTmodel.addConstr(Pbess_flex_[i] == Pbess_in_[i] + Pbess_out_[i],name='CON16')
OPTmodel.update()
ConPDC = OPTmodel.addConstr(Pdc[i] == Pflex_i[i] + float(ITload[i]), name='ConPDC')
# OPTmodel.addConstr(Tdc_i[i]==(ki*Tdc_i[i-1]+(ko*Tamb)))
#for x in Ebess_i:
#ConEBESS2 = OPTmodel.addConstr(Ebess_i[i] ==((Pbess_in[i] / 0.75) + (Pbess_out[i] * 0.75)))
cooling = np.array(pd.read_csv('Pcooling.csv'))
DRR = pd.read_csv('DR.csv')
DR = DRR.values
IT = pd.read_csv('ITpower.csv')
ITload = IT.values
newList = map(lambda x: x / 1000, ITload)
PH = pd.read_csv('Pcooling.csv')
PHVAC = PH.values
newList2 = map(lambda x: x / 1000, PHVAC)
#for y in Tdc_i:
T=pd.read_csv('TT.csv').values
OPTmodel.addConstr(Tdc_i[i]==((ki*float(T[i]))+(ko*Tamb)+(kc*float(newList[i]))-((kp*(float(newList2[i])))+(Phvac_flex[i]*3.14))))
print Tdc_i.values()
OPTmodel.addConstr(Pbess_out_[i]<=Phvac_flex[i] + Pbess_flex[i]<=Pbess_in_[i])
# Tdc_i[1:len(i)]==(Ki*Tdc_i[1:1438])+(Kc*array2[1:1438])+(Ko*Tamb))
ConBESS5 = OPTmodel.addConstr(Pbess_flex[i] == Pbess_in[i] + Pbess_out[i], name='ConBESS5')
#OPTmodel.addConstr(defIT[i]==DeferableLoad.j2 + DeferableLoad.j3)
# OPTmodel.addConstr(Pdc_base[i]==predictions[i])
ConFLEX = OPTmodel.addConstr(Pflex_i[i] == Pbess_flex[i] + Phvac_flex[i], name='ConFLEX')
PcoolingPredicted = pd.read_csv('PcoolingPredictionResult.csv')
PcoolingPredictedValue = PcoolingPredicted.values
ITPredicted = pd.read_csv('ITpredictionResult.csv')
ITPredictedValue = ITPredicted.values
ConPDCbase = OPTmodel.addConstr(Pdc_base[i] == np.transpose(ITPredictedValue[i]) + np.transpose(PcoolingPredictedValue[i]))
OPTmodel.update()
# OPTmodel.addConstr(Pdc_base[i]==prediction[i])
OPTmodel.setObjective((np.transpose(Pdc_base[i])-float(DR[i]) - (Pdc[i]) ), GRB.MINIMIZE)
OPTmodel.update()
OPTmodel.optimize()
print Pdc_base[i].X
#print Ebess_i[i].X
#print Phvac_flex[i].X
print Tdc_i[i]
print Pdc[i]
print Phvac_flex[i]
print Pbess_flex[i]
print Pbess_out[i]
print Pbess_in[i]
print Ebess_i[i]
print Pbess_flex_[i]
print Phvac_down[i]
print Phvac_up[i]
'''
def get_results(self):
"""
This function gets the results of the current optimization model
Returns
-------
"""
HVACresult = np.zeros(1,N)
BatteryResult = np.zeros(1,N)
SOC = np.zeros(1,N)
#r_Q_dot = np.zeros((self.gp.N_H, self.N_S))
#r_P = np.zeros((self.gp.N_H, self.N_S))
#r_P_self = np.zeros((self.gp.N_H, self.N_S))
#r_P_ex = np.zeros((self.gp.N_H, self.N_S))
#r_Q_dot_gas = np.zeros((self.gp.N_H, self.N_S))
#Load = np.zeros((self.gp.N_H, self.N_S))
try:
for t in range(1,N):
HVACresult[t]= Phvac_flex[t].X
BatteryResult[t]=Pbess_flex[t].X
SOC[t] = Ebess_i[t].X / Ebess_max
except:
pass
return { 'SOC' : SOC , 'BatteryResult': BatteryResult }
print OPTmodel.getVars()
# get results
Temp = {}
Battery = {}
Ebess_result = {}
ITloadd = {}
for t in range(1,N):
Temp[t] = OPTmodel.getVarByName("Tdc_i" )
Battery[t] = OPTmodel.getVarByName("PBESS_flex" )
Ebess_result[t] = OPTmodel.getVarByName("Ebess_i" )
#r_P_e[t] = model.getVarByName("P_export_%s_0" % t).X
fig, axes = plt.subplots(4, 1)
# plot elctricity
ax5 = axes[2]
ax6 = ax5.twinx()
ax5.plot( [Temp[t] for t in range(1,N)], 'g-')
ax6.plot([Ebess_result[t] for t in range(1,N)], 'b-')
ax5.set_xlabel('Time index')
ax5.set_ylabel('Power Import [W]', color='g')
ax6.set_ylabel('Power CHP [W]', color='b')
ax7 = axes[3]
ax7.plot([Battery[t] for t in range(1,N)], 'g-')
ax7.set_ylabel('Power Export [W]', color='g')
'''
print Pflex_i.values()
# print OPTmodel.getVars()
print OPTmodel.feasibility()
print OPTmodel.getObjective()
print Pdc_base.values()
'''
b = map(float, Phvac_flex)
plt.plot(b)
plt.show()
'''
#c = map(float, Pbess_flex_)
#plt.plot(c)
#plt.show()
print OPTmodel
print Tdc_i.values()
# get results
print OPTmodel.getVars()
# print OPTmodel.getAttr('EBESS_i')
status = OPTmodel.status
print status
# print Con10,Con12
print Phvac_flex.values()
print Pbess_flex.values()
print Ebess_i.values()
print OPTmodel.objval
print Tdc_i
print Pbess_in
print Pbess_out.values()
# print Pbess_flex
# print Phvac_flex
# print Ebess_i
print Pflex_i.values()
print Pbess_flex_.values()
#print OPTmodel.getVars()
print OPTmodel.feasibility()
print OPTmodel.getObjective()
print Ebess_i.values()
if OPTmodel.status == GRB.Status.INF_OR_UNBD:
# Turn presolve off to determine whether model is infeasible
# or unbounded
OPTmodel.setParam(GRB.Param.Presolve, 0)
OPTmodel.optimize()
OPTmodel.write("mymodel.lp")
if OPTmodel.status == GRB.Status.OPTIMAL:
print('Optimal objective: %g' % OPTmodel.objVal)
OPTmodel.write('model.sol')
exit(0)
elif OPTmodel.status != GRB.Status.INFEASIBLE:
print('Optimization was stopped with status %d' % OPTmodel.status)
exit(0)
# Model is infeasible - compute an Irreducible Inconsistent Subsystem (IIS)
print('')
print('Model is infeasible')
OPTmodel.computeIIS()
OPTmodel.write("model.ilp")
print("IIS written to file 'model.ilp'")
I want to plot the computed values from gurobi but when I want to get the X attribute of gurobi variable it says that AttributeError: it has no attribute 'X' and the when I cast the value from float to int it just showed me the empty plot but at the lp file I could see the result of each iteration
I am anxiously waiting for your response
cherrs
I have multiple for-loops inside a while loop in my Python code. For the first iteration, everything works fine. For the second iteration of the while-loop, I get the following error:
File ".\simulated_annealing.py", line 209, in <module>
for ii in range(0, 8, 1) :
TypeError: 'float' object is not callable
Below is the relevant piece of my code:
while numpy.absolute(FcostOld) >= 0.001 and l <= L :
Fx = []
Fy = []
Fz = []
V = []
ii = 0
for ii in range(0, 8, 1) : # ... LINE 209
Fx.append([])
Fy.append([])
Fz.append([])
for j in range(0, 13, 1) :
Fx[ii].append(0)
Fy[ii].append(0)
Fz[ii].append(0)
V.append(0.0)
print "\n l = ", l
j = 0
print "j = ", j
i = 0
for i in range(0, 8) :
print "i = ", i
"""
V[i] = 0.0
for j in range(0, 13, 1) :
Fx[i][j] = 0.0
Fy[i][j] = 0.0
Fz[i][j] = 0.0
"""
for j in range(0, 6, 1) :
for k in range(0, Natoms, 1) :
dxxC = x[i][j] - Layer15[k][0]
dyyC = y[i][j] - Layer15[k][1]
dzzC = zC - Layer15[k][2]
rrC = numpy.sqrt(dxxC*dxxC + dyyC*dyyC + dzzC*dzzC)
if rrC <= rcut :
V[i] = V[i] + VrealC(rrC, DeC, alphaC, rC, s6)
Fx[i][j] = Fx[i][j] + frealC(rrC, DeC, alphaC, rC, dxxC, s6)
Fy[i][j] = Fy[i][j] + frealC(rrC, DeC, alphaC, rC, dyyC, s6)
Fz[i][j] = Fz[i][j] + frealC(rrC, DeC, alphaC, rC, dzzC, s6)
for j in range(6, 12, 1) :
for k in range(0, Natoms, 1) :
dxxH = x[i][j] - Layer15[k][0]
dyyH = y[i][j] - Layer15[k][1]
dzzH = zH - Layer15[k][2]
rrH = numpy.sqrt(dxxH*dxxH + dyyH*dyyH +dzzH*dzzH)
if rrH <= rcut :
V[i] = V[i] + VrealH(rrH, DeH, alphaH, rH, s6)
Fx[i][j] = Fx[i][j] + frealH(rrH, DeH, alphaH, rH, dxxH, s6)
Fy[i][j] = Fy[i][j] + frealH(rrH, DeH, alphaH, rH, dyyH, s6)
Fz[i][j] = Fz[i][j] + frealH(rrH, DeH, alphaH, rH, dzzH, s6)
j = 12
for k in range(0, Natoms, 1) :
dxxX = x[i][j] - Layer15[k][0]
dyyX = y[i][j] - Layer15[k][1]
dzzX = zX - Layer15[k][2]
rrX = numpy.sqrt(dxxX*dxxX + dyyX*dyyX +dzzX*dzzX)
if rrX <= rcutX :
V[i] = V[i] + VrealX(rrH, DeH, alphaH, rH, s6)
Fx[i][j] = Fx[i][j] + frealX(rrX, DeX, alphaX, rX, dxxX, s6)
Fy[i][j] = Fy[i][j] + frealX(rrX, DeX, alphaX, rX, dyyX, s6)
Fz[i][j] = Fz[i][j] + frealX(rrX, DeX, alphaX, rX, dzzX, s6)
print "i = ", i
if flag == False :
FcostOld_V = 0 * numpy.sqrt( sum(numpy.power(V[n]-VTarget[n], 2) for n in range(0,8)) ) / numpy.sqrt( sum((V[n]*V[n]) for n in range(0,8)) )
FcostOld_F = numpy.absolute( sum(Fz[n][m] for n in range(0,8) for m in range(0,13)) ) / 8
FcostOld = FcostOld_V + FcostOld_F
if flag == True :
FcostNew_V = 0 * numpy.sqrt( sum(numpy.power(V[n]-VTarget[n], 2) for n in range(0,8)) ) / numpy.sqrt( sum((V[n]*V[n]) for n in range(0,8)) )
FcostNew_F = numpy.absolute( sum(Fz[n][m] for n in range(0,8) for m in range(0,13)) ) / 8
FcostNew = FcostNew_V + FcostNew_F
if (FcostNew - FcostOld) < 0:
s6Old = s6
FcostOld = FcostNew
DeCOld = DeC
alphaCOld = alphaC
rCOld = rC
DeHOld = DeH
alphaHOld = alphaH
rHOld = rH
DeXOld = DeX
alphaXOld = alphaX
rXOld = rX
if (FcostNew - FcostOld) >= 0 :
P = numpy.exp( -(FcostNew-FcostOld) / kT )
r0 = numpy.random.rand()
if r0 < P :
s6Old = s6
FcostOld = FcostNew
DeCOld = DeC
alphaCOld = alphaC
rCOld = rC
DeHOld = DeH
alphaHOld = alphaH
rHOld = rH
DeXOld = DeX
alphaXOld = alphaX
rXOld = rX
flag = True
range = 0.1
DeC = NewParameter(DeCOld, range)
alphaC = NewParameter(alphaCOld, 2*range)
rC = NewParameter(rC, range/2)
DeH = NewParameter(DeHOld, 5*range)
alphaH = NewParameter(alphaHOld, 2*range)
rH = NewParameter(rH, range/3)
DeX = NewParameter(DeXOld, range)
alphaX = NewParameter(alphaXOld, 2*range)
rX = NewParameter(rX, range/2)
s6 = NewParameter(s6Old, range)
if numpy.mod(l,1) == 0 :
print "\nFcost = ", FcostOld
print Fx[7]
print " l = ", l
l = l + 1
Don't use range as a variable name. It shadows builtin functionrange:
>>> range = 0.1
>>> range(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object is not callable
range is a builtin that returns a list of values to iterate over. On line 317 you have range = 0.1, which is replacing the builtin range function with a float value.
Thus, the second time through, instead of using the normal range function, your program instead sees a float, this will be like saying for ii in 0.1(0, 8, 1): which obviously doesn't make sense.
To fix this, just use a different variable name than range such as interval = 0.1 for example.
The error message you are receiving comes from you trying to call a float.
>>> x = 1.1
>>> x()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object is not callable
the () are used for function calls. Since x is a float in the above example, it fails because you can't call a float.