I have this function that generate the initial population for a genetic algorithm.
import random
def initial_pop(pop_size):
pop = list()
for i in range(pop_size):
aux = list()
for j in range(2):
signal = bin(random.randint(0, 1))[2:].zfill(1)
int_part = bin(random.randint(0, 2))[2:].zfill(2)
real_part = bin(random.randint(0, 5000))[2:].zfill(13)
x = ''.join([signal, int_part, real_part])
aux.append(x)
pop.append(aux)
return pop
population = initial_pop(5)
print(population)
The function returns something like this:
[['1001000001111101', '1100111001001010'], ['0000111110100111', '0011001000100011'], ['1000010101001101', '0000101001100011'], ['1100000011011010', '0011000010001110'], ['0100010101001010', '1001000010001110']]
And I have this function that make the crossover between parents:
def crossover(pai1, pai2, cross_rate):
p1x = pai1[0]
p1y = pai1[1]
p2x = pai2[0]
p2y = pai2[1]
if np.random.rand() < tx_cruzamento:
f1x = p1x[:PONTO_CRUZAMENTO_1] + p2x[PONTO_CRUZAMENTO_1:PONTO_CRUZAMENTO_2] + p1x[:PONTO_CRUZAMENTO_2]
f1y = p1y[:PONTO_CRUZAMENTO_1] + p2y[PONTO_CRUZAMENTO_1:PONTO_CRUZAMENTO_2] + p1y[:PONTO_CRUZAMENTO_2]
f2x = p2x[:PONTO_CRUZAMENTO_1] + p1x[PONTO_CRUZAMENTO_1:PONTO_CRUZAMENTO_2] + p2x[:PONTO_CRUZAMENTO_2]
f2y = p2y[:PONTO_CRUZAMENTO_1] + p1y[PONTO_CRUZAMENTO_1:PONTO_CRUZAMENTO_2] + p2y[:PONTO_CRUZAMENTO_2]
f1 = [f1x] + [f1y]
f2 = [f2x] + [f2y]
return [f1] + [f2]
else:
return [pai1] + [pai2]
The call for this function is:
children.append(crossover(selected[j], selected[j+1], CROSS_RATE))
However, this function return something like this:
[[['1100101011000010', '1101100011010000'], ['1010001010101010', '1010000010101000']], [['1010101011010010', '1010100011001100'], ['1100010000100001', '1011000111101000']], [['1100010011000010', '1101000111010000'], ['1100001011000100', '1011000010110001']]]
How do I format the output to look exactly like the first one? The one that generated the initial population? I tried everything ([f1] + [f2], [[f1]+[f2]], [f1, f2], etc)
The problem seems to be in how selected is defined. When I call your cross-over function like this:
crossover(population[0],population[1],0.3)
I get output which looks like:
[['0000110000101001', '1010100101111111'], ['0010101110111110', '0001001010110001'], ['0100100110000010', '0100111100011001'], ['0011000100010010', '0010110110111111'], ['0010010111000110', '0010010101111011']]
[['0000110000101001', '1010100101111111'], ['0010101110111110', '0001001010110001']]
which matches the form of your intended output.
This suggests that the problem lies with code that you didn't show. Alternatively, crossover needs to do some preprocessing to extract the data that it needs from that which is passed to it. If this isn't the case, you really need to provide the missing details that would allow others to replicate the problem.
Related
This is the code. I think the solver could be glpk instead of gurobi. I got the error before it tries to solve the problem.
from pyomo.environ import *
from pyomo.opt import SolverFactory, SolverStatus
PrintSolverOutput = False ###
model = ConcreteModel()
model.dual = Suffix(direction =Suffix.IMPORT)
model.X = Var(I,T, within = NonNegativeReals)
model.In = Var(I,T, within = NonNegativeReals)
model.S = Var(T, within = NonNegativeReals)
def Objetivo(model):
return (sum(C[i]*model.X[i,t]*((1+tau[i])**(t-1))+Ch[i]*model.In[i,t]
for i in I for t in T)
+sum(Cs*model.S[t]
for t in T)
)
model.Total_Cost = Objective(rule = Objetivo, sense= minimize)
def Balance(model,i,t):
if t==1:
return model.X[i,t]+I0[i]-model.In[i,t]==D[i,t]
elif t>=2:
return model.X[i,t]+model.IN[i,t-1]-model.In[i,t]==D[i,t]
def Horas(model, t):
return sum(r[i]*model.X[i,t] for i in I) <= H+model.S[t]
def Limite(model,t):
return model.S[T]<=LS
model.RBalance = Constraint(I,T,rule=Balance)
model.RHoras = Constraint(T,rule=Horas)
model.RLimiteoras = Constraint(T,rule=Limite)
opt = SolverFactory("gurobi")
This is the data
I forgot to put the data before.
T = [1,2,3,4,5,6]
I = ['A','B']
D = {('A',1):300,
('A',2):400,
('A',3):500,
('A',4):600,
('A',5):800,
('A',6):700,
('B',1):700,
('B',2):600,
('B',3):500,
('B',4):400,
('B',5):300,
('B',6):400}
tau = {'A':0.02,'B':0.01}
r = {'A':5,'B':3}
H = 3520
LS = 800
C = {'A':150,'B':120}
Ch = {'A':8,'B':4}
Cs = 6
I0 = {'A':100,'B':250}
error
The code is from a youtube tutorial and it worked for him but not for me. Why?
Aside from fixing two typos in your code, this model computes and solves for me without that error. Make these fixes, run it again, re-post the exact error with line number and the exact code that produces the error if stuck...
I have the following function from which I would like to obtain its solution. I'm trying to use Scipy to get them but I observe that the solution being given by Scipy is quite different from that of Matlab, using same settings.
What am I doing wrong?
def WandG(GW,Zin):
G,W = GW # define real variables to be used for the function
R = (G**2)*(Zin.real - 0.1164) +(( 70e-12 * ( W/100 ) )**2)*( 2.9036155068866304e+16*(Zin.real - 0.1164) ) - G
I = (G**2)*( Zin.imag - 18.743998408378143 * (1-W/200) ) + (((W/100)*70e-12)**2)*( 2.9036155068866304e+16*(Zin.imag - 18.743998408378143 * (1-W/200)) ) + 170399985.53071037*(70e-12*(W/100) )
return R,I
sol = optimize.root(WandG, [0.136879496, 47.04],(12.652884410928804+14.632724423763523j), jac=False,tol=1e-14, method='lm',options={'maxiter':100*400,'epsfcn':1e-14,'xtol':1e-14})
The solution using Scipy would be
sol.x[0] = 0.0795283512113496 # G
sol.x[1] = 36.53727146377749 # W
Whereas with MATLAB for the same initial conditions, solver and Zin, it returns, which I trust more since it resembles better to the final result of W which is W=50
G = 0.0794
W = 44.5234
EDIT : added Matlab code
% configuration of fsolve
options = optimoptions('fsolve','Display','iter-detailed','PlotFcn',#optimplotfirstorderopt);
options.StepTolerance = 1e-14;
%options.OptimalityTolerance = 1e-14
options.FunctionTolerance = 1e-14;
options.MaxIterations = 100000;
options.MaxFunctionEvaluations = 400;
options.Algorithm = 'levenberg-marquardt';%'trust-region'%
fun= #WandG;
x0 = [0.136879496', 47.04'];
% Solve the function fun
gw =fsolve(fun,x0,options);
% Function to be solved by fsolve
function F = WandG(x)
F(:,1) = (x(:,1).^2).*(real(Zin) - 0.1164) +(( 70e-12 .* ( x(:,2)./100 ) ).^2).*( w.^2.*(real(Zin) - 0.1164) ) - x(:,1);
F(:,2) = (x(:,1).^2).*( img(Zin) - 18.743998408378143 * (1-x(:,2)./200) ) + (((x(:,2)./100).*70e-12).^2).*( 2.9036155068866304e+16*(img(Zin) - 18.743998408378143 .* (1-x(:,2)./200)) ) + 170399985.53071037.*(70e-12.*(x(:,2)./100) );
end
I've been working on a project that is a calculator for an electronic part. This is my first full-scale Python project and it has gone through many iterations along the way.
The data is not organized as well as I would like, which I think is making it difficult to improve the program.
I have a class for the module, which has two parts inside of it. Each part has its own attributes that are independent of each other, and the whole module itself has some attributes that the parts don't care about, and some attributes that the parts need. The module also has to do some calculations based on the results of the independent calculations done inside the parts. Here is a photo of the idea I'm trying to explain. As an aside, sometimes there are modules with only one part, but I can suppress the other part by applying some 0's arrays. I would like to be able to have a module where the one part is entirely missing, but that is not my current goal.
The problem is that my class has ~100 lines of self.XXX = None at the beginning to initialize everything, and several functions which IMO are repetitive. It is also quite difficult to traverse the data when stepping through the code - for example, I have to find variables like self.current__partA and self.current__partB. What I think would be helpful is to have something like self.partA.current. If it is done this way, I think it would be more readable.
The problem is, I tried subclasses and it seems like I can't achieve this kind of idea because when I initialize the subclass, I have to initalize a new superclass, meaning that there are two superclasses (two modules with a total of 4 parts, when I want 1 module/2 parts), so I can't really access the info of both subclasses from the superclass because each subclass will have its own instance of the superclass.
I also looked at inner classes but there is an issue where I don't think I can truly access the outer class from the inner class, which kind of defeats the purpose of using this. That could work to a degree, but it would make my code longer and less readable, from what I am seeing.
The first solutions I had were things like dictionaries, which I don't totally hate, but that lead to really janky code that had very little tolerance for errors. The reason is, when you add a list to a dictionary, you can't have a function that automatically throws an error. I can check the dictionary, but it just feels unnatural. It seems to me that it would make more sense to keep each value as a class variable and use functions, getters and setters to manipulate it through the calculation.
My main goal is to organize the data and code effectively so that I am using less lines of code and the program is easier to modify, and it is easier to step through the process. I am not entirely sold on the class structure, it just seemed to be the best way to accommodate what I am trying to do. Is there a way to achieve what I am asking here, or is there a generally more pythonic way to organize my code that would result in a more effective solution?
class Module:
def __init__(self, module_file):
temp_ic, temp_value = self.get__corrected_value(module_file)
temp_if, temp_vf = self.get__corrected_value(module_file)
self.ic_value = interp1d(temp_ic, temp_value, fill_value='extrapolate')
self.ic_esw_on = interp1d(self.get__corrected_esw(module_file), self.get__corrected_esw(module_file["ESWON - IC ESWON"]), fill_value='extrapolate')
self.ic_esw_off = interp1d(self.get__corrected_esw(module_file["IC - IC ESWOFF"]), self.get__corrected_esw(module_file["ESWOFF - IC ESWOFF"]), fill_value='extrapolate')
self.rg_on_esw_on = interp1d(module_file["RGON - ESWON RGON"], module_file["ESWON - ESWON RGON"], fill_value='extrapolate')
self.rg_off_esw_off = interp1d(module_file["RGOFF - ESWOFF RGOFF"], module_file["ESWOFF - ESWOFF RGOFF"], fill_value='extrapolate')
self.ic_err = interp1d(self.get__corrected_esw(module_file["IC - IC ERR"]), self.get__corrected_esw(module_file["ERR - IC ERR"]), fill_value='extrapolate')
self.if_vf = interp1d(temp_if, temp_vf, fill_value='extrapolate')
self.rg_on_err = interp1d(module_file["RGON - ERR RGON"], module_file["ERR - ERR RGON"], fill_value='extrapolate')
self.nameplate_vcc = module_file['Nameplate VCC']
if module_file['vcc_ratio'] > 0:
self.vcc_ratio = module_file['vcc_ratio']
else:
self.vcc_ratio = 0
self.name = self.get__module_name(module_file)
self.current__PartA = []
self.current__PartB = []
self.some_thing_loss__PartA = []
self.esw_on_loss = []
self.esw_off_loss = []
self.esw_loss__PartA = []
self.energy__PartA = []
self.value__PartA = []
self.some_thing_loss__PartB = []
self.err_loss = []
self.energy__PartB = []
self.value__PartB = []
self.rg_scalar_esw_on = None
self.rg_scalar_esw_off = None
self.rg_scalar_err = None
self.value_dc__PartA = module_file['PartA value DC']
self.value_dc__PartB = module_file['PartB value DC']
self.value_dc__module = module_file['Module value DC']
self.trans_r_values__PartA = module_file["PartA R Values"]
self.trans_t_values__PartA = module_file["PartA T Values"]
self.trans_r_values__PartB = module_file["PartB R Values"]
self.trans_t_values__PartB = module_file["PartB T Values"]
self.some_thing_loss_total__PartA = None
self.some_thing_loss_total__PartB = None
self.esw_on_loss_total = None
self.esw_off_loss_total = None
self.esw_loss_total = None
self.err_loss_total = None
self.device_loss_total__PartA = None
self.device_loss_total__PartB = None
self.module_loss_total = None
self.delta_tcase_ave = None
self.delta_value_ave__PartA = None
self.delta_value_ave__PartB = None
self.nominal_value_ave__PartA = None
self.nominal_value_ave__PartB = None
self.delta_value_max__PartA = None
self.delta_value_max__PartB = None
self.nominal_value_max__PartA = None
self.nominal_value_max__PartB = None
self.value_max_PartA_list = []
self.value_max_PartB_list = []
self.thermal_interp_is_four_degree = self.check__thermal_interp()
self.switches_per_degree = None
self.input_output_freq = None
self.time_division = None
self.input_t_sink = None
self.step_size = None
self.step_range = None
self.sec_per_cycle_degree = None
self.duty_p = None
self.value_PartA_list = None
self.value_PartB_list = None
self.time_list = None
self.rad_list = None
self.value_max__PartA_thermo = None
self.value_max__PartB_thermo = None
self.value_max__time_value = None
def check__some_input_conditions_and_change_input(self): # todo could this be cleaned?
blah
def get__max_current(self):
return max(self.nominal_value_max__PartB, self.nominal_value_max__PartA)
def set__some_module_values(self, is_three_level, system): # todo call this something different, and break it out for 3-level
blah
def set_values_for_both_parts(self, input_instance, system_instance, module_location=None):
lots of blah
def set__current_PartA(self, current):
self.current__PartA = current
def set__current_partB(self, current):
blah
def calculate__another_other_loss_for_part_A(self, duty):
blah
def calculate__another_loss_for_partB(self, duty):
blah
def calculate__another_loss_for_partA(self, duty=None):
blah
def calculate__some_loss_for_partA(self, duty=None):
blah
def calculate__some_loss_for_partB(self, duty=None):
blah
def calculate__energy_power_for_both_parts(self):
blah
def calculate__temperatures_for_both_parts(self):
blah
def calculate__max_temp(self): # maybe split into PartA and PartB separately?
self.create_thermal_resistance_dict()
value_PartA_list = []
value_PartB_list = []
next_array_PartA = self.value__PartA
next_array_PartA = self.rotate(next_array_PartA, -1)
delta_p_PartA = [next_el - last_el for next_el, last_el in zip(next_array_PartA, self.value__PartA)]
last_power_PartA = self.value__PartA[-1] - self.device_loss_total__PartA
first_power_PartA = self.value__PartA[0] - self.device_loss_total__PartA
value_dict_PartA_added = [self.get_PartA_value_from_time(i * self.sec_per_cycle_degree + self.value_max__time_value) for i in range(self.step_range)]
value_dict_PartA_added = [old + new for old, new in zip(self.value_max__PartA_thermo, value_dict_PartA_added)]
value_PartA_inst_init = [self.input_t_sink + self.delta_value_ave__PartA + self.delta_tcase_ave - last_power_PartA * self.value_max__PartA_thermo[i] + first_power_PartA * value_dict_PartA_added[i] for i in range(self.step_range)]
delta_value_PartB = self.device_loss_total__PartB * self.value_dc__PartB
next_array_PartB = self.value__PartB
next_array_PartB = self.rotate(next_array_PartB, -1)
delta_p_PartB = [next_el - last_el for next_el, last_el in zip(next_array_PartB, self.value__PartB)]
last_power_PartB = self.value__PartB[-1] - self.device_loss_total__PartB
first_power_PartB = self.value__PartB[0] - self.device_loss_total__PartB
value_dict_PartB_added = [self.get_PartB_value_from_time(i * self.sec_per_cycle_degree + self.value_max__time_value) for i in range(self.step_range)]
value_dict_PartB_added = [old + new for old, new in zip(self.value_max__PartB_thermo, value_dict_PartB_added)]
value_PartB_inst_init = [self.input_t_sink + delta_value_PartB + self.delta_tcase_ave - last_power_PartB * self.value_max__PartB_thermo[i] + first_power_PartB * value_dict_PartB_added[i] for i in range(self.step_range)]
for index in range(self.step_range):
value_dict_PartA_fix = [value_dict_PartA_added[i] if i <= index else self.value_max__PartA_thermo[i] for i in range(self.step_range)]
# value_dict_PartA_fix_orig = [val for val in value_dict_PartA_fix]
value_dict_PartA_fix.reverse()
new_value_PartA = self.rotate(value_dict_PartA_fix, index)
new_value_PartA = new_value_PartA[:359]
temp_add_vals_PartA = [delta_p * value for delta_p, value in zip(delta_p_PartA, new_value_PartA)]
sum_temp_add_vals_PartA = sum(temp_add_vals_PartA)
value_PartA_list.append(sum_temp_add_vals_PartA)
value_dict_PartB_fix = [value_dict_PartB_added[i] if i <= index else self.value_max__PartB_thermo[i] for i in range(self.step_range)]
# value_dict_PartB_fix_orig = [val for val in value_dict_PartB_fix]
value_dict_PartB_fix.reverse()
new_value_PartB = self.rotate(value_dict_PartB_fix, index)
new_value_PartB = new_value_PartB[:359]
temp_add_vals_PartB = [delta_p * value for delta_p, value in zip(delta_p_PartB, new_value_PartB)]
sum_temp_add_vals_PartB = sum(temp_add_vals_PartB)
value_PartB_list.append(sum_temp_add_vals_PartB)
value_PartA_list = [value + diff for value, diff in zip(value_PartA_inst_init, value_PartA_list)]
value_ave_PartA = self.nominal_value_ave__PartA - np.average(value_PartA_list)
self.value_PartA_list = [value + value_ave_PartA for value in value_PartA_list]
value_PartB_list = [value + diff for value, diff in zip(value_PartB_inst_init, value_PartB_list)]
value_ave_PartB = self.nominal_value_ave__PartB - np.average(value_PartB_list)
self.value_PartB_list = [value + value_ave_PartB for value in value_PartB_list]
self.time_list = [i * self.sec_per_cycle_degree + self.value_max__time_value for i in range(self.step_range)]
self.rad_list = [i * self.step_size for i in range(self.step_range)]
self.nominal_value_max__PartA = max(value_PartA_list)
self.nominal_value_max__PartB = max(value_PartB_list)
self.delta_value_max__PartA = max(self.value_PartA_list) - self.input_t_sink
self.delta_value_max__PartB = max(self.value_PartB_list) - self.input_t_sink
self.value_max_PartA_list = value_PartA_list
self.value_max_PartB_list = value_PartB_list
def rotate(self, l, n):
return l[-n:] + l[:-n]
def do_calculation_for_either_part(self, step, spcd, index, scalar, growth, time): # todo does everything need to be passed in?
blah
def get_other_part's_value(self, time): # todo could this be folded into below
blah
def get_one_part's_value(self, time):
blah
def integrate_value_for_other_part(self, step, spcd, start_time, index): # todo could this be folded into below
blah
def integrate_value_for_one_part(self, step, spcd, start_time, index): # todo remove interp check
blah
def create_some_dict_for_both_parts(self): # todo could this be cleaned
50 lines of blah
def get__other_corrected_array(self, array): # todo could this be simplified?
blah
def get__corrected_array(self, input arrays): # todo is this necessary
blah
def get__some_value(self, value): # todo isn't there one of these already?
blah
def get__module_name(self, module_file):
blah
The commentators are correct that an MCVE would definitely enhance your post and so my answer is a bit limited. I just want to point out that your data members can be any python object.
So if your data access pattern would benefit from storing your data in pandas and interacting with it as pandas:
class YourClass:
def __init__(self, data):
self.data = # Your pandas df
Or json:
import json
class YourClass:
def __init__(self, data):
self.data = json.loads(data)
Or numpy:
class YourClass:
def __init__(self, data):
self.data = # Your numpy ndarray
And then your class can be called simply as YourClass(data)
Edit: Looking at your code, literally ALL of your self.value = None lines are superfluous in my view. if they are a members of a tabular data input they can be initialized:
class Module:
def __init__(self, data):
self.data = pd.DataFrame()
Once they are initialized as an empty dataframe their CRUD operations can map to the very mature pandas CRUD operations. Similarly self.data = {} for key-value pairs data structure like JSON, and so on. For the rest, you can catch the case where data.key is undefined in generic getters and setters and not bother with initializing them.
I have this model:
class Image(models.Model):
title = models.CharField(max_length=200)
image = models.ImageField(upload_to='img/')
signature = models.TextField(null = True)
The signature is a numpy monodimensional vector encoded in json. In order to make my query, I have to decode each object signature into a nparray, and make a dot product between each object's signature and a given vector, then annotate as a float (named "score") field beside each raw. Lastly I have to order from max to min.
I tried this in view.py
def image_sorted(request):
query_signature = extract_feat(settings.MEDIA_ROOT + "/cache" + "/003_ant_image_0003.jpg") # a NParray object
image_list = Image.objects.annotate(score=np.dot(
JSONVectConverter.json_to_vect(F('signature')), query_signature.T
).astype(float)).order_by('score') #JSONVectConverter is a class of mine
return render(request, 'images/sorted.html', {'image_sorted': image_list})
of course it doesn't work. I think "F()" operator is out of scope...
If you're wondering, I'm writing an image retrieval webapp for my university thesis.
Thank you.
EDIT:
I found this that is quite the same problem (He use postgres instead of MySQL)
EDIT2: I just remember now what is the last solution I've adopted! First I pull out every vector from the DB and mantain it in RAM, then I make some simple computes to find the K-Nearest Neighbors. Then, I retrieve from the DB the respective image using its index (primary key). So I decouple this task from Django ORM. Here's the code (from the Rest API)
def query_over_db(query_signature, page):
query_signature = np.array(query_signature)
t0 = time.time()
descriptor_matrix = cache.get('descriptor_matrix')
id_vector = cache.get('id_vector')
if not descriptor_matrix:
id_vector = []
descriptor_matrix = []
images_dict = Image.objects.all().values('id', 'signature')
for image in images_dict:
s = image['signature']
descriptor = np.array(s)
descriptor_matrix.append(descriptor)
id_vector.append(image['id'])
cache.set('id_vector', id_vector)
cache.set('descriptor_matrix', descriptor_matrix)
t1 = time.time()
print("time to pull out the descriptors : " + str(t1 - t0))
t1 = time.time()
#result = np.abs(np.dot(descriptor_matrix, query_signature.T))
#result = np.sum((descriptor_matrix - query_signature)**2, axis=1)
result = ne.evaluate('sum((descriptor_matrix - query_signature)**2, axis=1)')
t2 = time.time()
print("time to calculate similarity: " + str(t2 - t1))
perm = np.argsort(result)[(page - 1) * 30:page * 30]
print(perm.shape)
print(len(id_vector))
perm_id = np.array(id_vector)[perm]
print(len(perm_id))
print("printing sort")
print(np.sort(result)[0])
t4 = time.time()
print("time to order the result: " + str(t4 - t2))
qs = Image.objects.defer('signature').filter(id__in=perm_id.tolist())
qs_new = []
for i in range(len(perm_id)):
qs_new.append(qs.get(id=perm_id[i]))
t3 = time.time()
print("time to get the results from the DB : " + str(t3 - t2))
print("total time : " + str(t3 - t0))
print(result[perm])
return qs_new
I didn't come close to trying something this complex, however I've solved a similar issue here:
Combining Django F, Value and a dict to annotate a queryset
I haven't tried this but you could give it a go:
from django.db.models import Case, When, FloatField
query_signature = extract_feat(settings.MEDIA_ROOT + "/cache" + "/003_ant_image_0003.jpg") # a NParray object
value_dict = {}
for image in Image.objects.all():
value_dict[image.signature] = np.dot(
JSONVectConverter.json_to_vect(image.signature),
query_signature.T
).astype(float)
whens = [
When(signature=k, then=v) for k, v in value_dict.items()
]
qs = Image.objects.all().annotate(
score=Case(
*whens,
default=0,
output_field=FloatField()
)
).order_by('score')
Hope it helps
So that's the final working code:
def image_sorted(request):
query_signature = extract_feat(settings.MEDIA_ROOT + "/cache" + "/001_accordion_image_0001.jpg") # a NParray object
#query_signature = extract_feat(settings.MEDIA_ROOT + "/cache" + "/003_ant_image_0003.jpg") # a NParray object
value_dict = {}
for image in Image.objects.all():
S = image.signature
value_dict[image.signature] = np.dot(
JSONVectConverter.json_to_vect(S),
query_signature.T
).astype(float)
whens = [
When(signature=k, then=v) for k, v in value_dict.items()
]
qs = Image.objects.all().annotate(
score=Case(
*whens,
default=0,
output_field=FloatField()
)
).order_by('-score')
for image in qs:
print(image.score)
return render(request, 'images/sorted.html', {'image_sorted': qs})
Thanks to Omar for helping me! Of course I'm still here if there are finer solutions.
I'm pretty new to Python, but learning. I'm trying to sort out class and self after talking to professor today. Here's a SIMPLE experiment I am trying with one "calling", Main program, and a separate class with called functions, called from Main and called from inside the class. I've written enough to try to test some of the flexibilities but I'm now debugging and I fear I'll put A BUNCH of stupid garbage in this to try to get it to run. Can someone see what needs to be done please, to get it to run without any excess complication? Thanks!
#######################################################################################################
#
# BoxDemoMain.py calling program
# demonstration of using and calling BoxClass.py pgm
#
#
import numpy as np
import BoxClassPgm
#
#
def ReportBoxDimensions(anySizeBox):
Ht = anySizeBox.boxHeight
Wd = anySizeBox.boxWidth
Dp = anySizeBox.boxDepth
print "The Height, Width, and Depth of this box is " + str(Ht) + "," + str(Wd) + "," + str(Dp)
print "The Surface Area of this box is " + str(BoxClassPgm.BoxClass(anySizeBox).CalcSurfArea())
print "The Volume of this box is " + str(BoxClassPgm.BoxClass(anySizeBox).CalcVolume())
#
#
largeBox = BoxClass(6,8,4)
mediumBox = BoxClass(4,5,3)
smallBox = BoxClass(3,3,3)
#
#
ReportBoxDimensions(largeBox)
ReportBoxDimensions(mediumBox)
ReportBoxDimensions(smallBox)
#######################################################################################################
#
# BoxClassPgm.py class program
# class demonstration
#
#
import numpy as np
#
#
class BoxClass:
def __init__(self,boxHeight=0,boxWidth=0,boxDepth=0):
self.boxHeight = boxHeight
self.boxWidth = boxWidth
self.boxDepth = boxDepth
def CalcVolume(self):
print "height is " + str(self.boxHeight)
boxVol = self.boxHeight * self.boxWidth * self.boxDepth
return boxVol
def CalcSurfArea(self):
areaOf3Faces = BoxClass().CalcFaceAreas()
boxSurfArea = 2 * areaOf3Faces
return boxSurfArea
def CalcFaceAreas(self):
frontBack = self.boxHeight * self.boxWidth
leftRight = self.boxHeight * self.boxDepth
topBottom = self.boxWidth * self.boxDepth
box3Faces = frontBack + leftRight + topBottom