Dictionary of Constraints Python SciPy.Optimize - python-3.x

I'm working on creating a dictionary of constraints for a large SCED power problem for minimization. However, I'm being given a ValueError saying an unknown type is passed despite only using Optimize.LinearConstraints at present. When I change to NonlinearConstraints (shown below), indicating that 'NonlinearConstraint' object has no attribute 'A'.
I have a feeling it's due to recursive elements, as even using a single constraint as I've defined them returns the same error
Any idea how I can create the recursive linear constraints?
##EDIT
I've been told to copy the code and provide a bit more context. "gen_supply_seg" is a three dimensional array that, depending on different points in time, has different constraints
def con2a():
for t in range(len(LOAD)):
for g in range(len(GEN)):
nlc2a = optimize.NonlinearConstraint(gen_supply_seg[t,g,1],lb=0,ub=P2Max[g])
return(nlc2a)
def con2b():
for t in range(len(LOAD)):
for g in range(len(GEN)):
nlc2b = optimize.NonlinearConstraint(gen_supply_seg[t,g,2],lb=0,ub=P3Max[g])
return (nlc2b)
def con2c():
for t in range(len(LOAD)):
for g in range(len(GEN)):
nlc2c = optimize.NonlinearConstraint(gen_supply_seg[t,g,3],lb=0,ub=P4Max[g])
return (nlc2c)
con2a = con2a()
con2b = con2b()
con2c = con2c()
These constraints are then added to a set like shown
cons = (con2a,
con2b,
con2c)

Related

TypeError: 'int' object is not subscriptable - I have been looking into this for hours now and i can not understand why it is spitting out this error

I am trying to nest multiple lists in a single 'master' list, when ever i go through the lists to add the items in other lists to the master in order, so i can create a save file using pickle in another piece of code (not related to this problem at all),
I have not been able to find an alternative
a = [123456789]
b = [2, 6, "CF"]
c=["Helo", 4567]
d=[3,5,6,4,4,3,5]
e=["345sadf fg", 48736541546]
master = []
for i in range(5):
master.append([])
#insert items into list - Format = homework, tnotes, pnotes, camau, studentname
for a in range(len(a)):
master[0].append(a[a])
for b in range(len(b)):
master[1].append(b[b])
for c in range(len(c)):
master[2].append(c[c])
for d in range(len(d)):
master[3].append(d[d])
for e in range(len(e)):
master[4].append(e[e])
print(str(master))
I would expect:
[[123456789],
[2,6, "CF"],
["Helo",4657],
[3,5,6,4,4,3,5],
["345sadf fg",48736541546]]
The a in for a in range(len(a)): shadows the name a = [123456789] from outer scope. So, when you do master[0].append(a[a]), both as refer to the integer a you got from range. The same thing happens in all the other loops.
So, a[a] (side note: this is highly confusing to begin with because it's unclear what a this refers to; Python establishes strict rules concerning this) attempts to index the integer a with the index a, which makes no sense because "int objects are not subscriptable", so you get an error.
You should name the index variables of your loops differently.

Class attributes in Python objects "erasing" themselves

I'm working with some old Python2 code from a differential power analysis (DPA) contest from way back (http://www.dpacontest.org/home/index.html). The code I'm modifying can be found here (https://svn.comelec.enst.fr/dpacontest/code/reference/)
Current issue that is driving me nuts:
Essentially, Some python objects in this code will "erase" themselves or go to their default values, and I have no idea why. I cannot find any code in the logic flow that does this, and I don't think it's a scope issue.
I've tried rewriting parts of the code to use numpy instead of mapping lambda functions. I've also tried a myriad of different orderings of code and pulling methods out of their classes and trying to run them locally/inline.
main.py:
loc_subkeys = brk.get_subkeys()
des_breaker.py
def get_subkeys(self):
"""
Returns a vector of currently best sboxes subkeys.
This is an array of 8 integers.
"""
sk = np.array([])
for i in range(8):
sk = np.append(sk, self.__sbox_breakers[i].get_key())
return sk
sbox_breaker.py
def get_key(self):
"Gives the current best key"
if self.__best_key is None:
marks = np.array([])
print("p0: ", len(list(self.__key_estimators[0]._key_estimator__p0)))
print("p1: ", len(list(self.__key_estimators[0]._key_estimator__p1)))
print("p0: ", len(list(self.__key_estimators[0]._key_estimator__p0)))
print("p1: ", len(list(self.__key_estimators[0]._key_estimator__p1)))
for i in range(64):
ke = self.__key_estimators[i]
marks = np.append(marks, ke.get_mark())
self.__best_key = np.argmax(marks)
return self.__best_key
key_estimator.py - attributes
class key_estimator:
"""
Provides methods to give a mark to the key relatively to the probability f
the correctness of the key.
"""
__sbox = None
__key = None
__cnt0 = 0 # The accumulated traces count in partition 0
__cnt1 = 0 # The accumulated traces count in partition 1
__p0 = None # The bit=0 estimated partition
__p1 = None # The bit=1 estimated partition
__diff = np.array([]) # The differential trace
Print statements in sbox_breaker are mine. Their output is the only clue I have right now:
p0: 5003 (Good)
p1: 5003 (Good)
p0: 0 (???)
p1: 0
What gives? The second time around the attributes of the key_estimator class have seemed to erase themselves. This happens to all the attributes, not just p0 and p1.
The first loop through this program works, but on the second iteration (starting from main) it fails because the attributes have erased themselves. I can "erase" them manually just by printing the object's attributes.
So I seemed to have fixed the problem after sleeping on it. The class attributes were being created by map which returns a list in Python2, but not Python3. Making them into lists with list() solves the persistence issue. I couldn't tell you why printing a map attribute causes it to clear itself though.

Is it possible to modify a cp_sat model after construction?

I have a model for finding a particular class of integer numbers (the "Keith numbers"), which works well, but is quite slow as it requires constructing a new model many times. Is there a way to update a model, in particular to change the coefficient in the constraint. In other words, change the model to match a different mat, without reconstructing the whole thing?
def _construct_model(self, mat):
model = cp_model.CpModel()
digit = [model.NewIntVar(0, 9, f'digit[{i}]') for i in range(self.k)]
# Creates the constraint.
model.Add(sum([mat[i] * digit[i] for i in range(self.k)]) == 0)
model.Add(digit[0] != 0)
return model, digit
Yes, but you are on your own.
You can access the underlying cp_model_proto protobuf from the model, and modify it directly.
He have no plan currently to add a modification API on top of the cp_model API.

Defining labels in Tkinter using values from another list

Well, I was trying to define Labels from another list that contain hours but no sucess.
def loop_label():
for item in Acd_horario:
Acd_horario[item] = Label(framerajada, text=[Acd_horario[item]],
font=font_acd, bg=bg_acd, fg=fg_acd, bd=bd_acd,
relief=relief_acd)
loop_label()
I tried like above, but no sucess. The other list I`m using is from another class, with gets the hour of another list of objects from the class itself:
Acd_lista = [Acd_0715, Acd_0745, Acd_0815, Acd_0845, Acd_0915, Acd_0945,
Acd_1015, Acd_1045, Acd_1115, Acd_1145,
Acd_1215, Acd_1245, Acd_1315, Acd_1345, Acd_1415, Acd_1445,
Acd_1515, Acd_1545, Acd_1615, Acd_1645,
Acd_1715, Acd_1745, Acd_1815, Acd_1845, Acd_1915, Acd_1945,
Acd_2015]
Acd_horario = [i.horario for i in Acd_lista]
Maybe is my logic that isn't right. Anyone has any idea on this?
The error I receive is: TypeError list indices must be integers or slices, not str

rpy2 access R named list items by name, low-level interface

How do I access elements of a named list by name?
I have 3 functions, all of which return a ListSexpVector of class htest. One of them has 5 elements, ['method', 'parameter', 'statistic', 'p.value', 'data.name'], others have a different number, and order. I am interested in extracting the p.value, statistic and parameter from this list. In R I can use $, like so:
p.value <- fit$p.value
statistic <- fit$statistic
param <- fit$parameter
The best equivalent I found in rpy2 goes like:
p_val = fit[list(fit.do_slot('names')).index('p.value')]
stat = fit[list(fit.do_slot('names')).index('statistic')]
param = fit[list(fit.do_slot('names')).index('parameter')]
Which is quite long-winded. Is there a better (shorter, sweeter, Pythonic) way?
There is the good-old-fashioned integer based indexing:
p_val = fit[3]
stat = fit[2]
param = fit[1]
But it doesn't work when the positions are changed, and therefore is a serious limitation because I am fitting 3 different functions, and each return a different order.
The high-level interface is meant to provide a friendlier interface as the low-level interface is quite close to R's C-API. With it one can do:
p_val = fit.rx2('p.value')
or
p_val = fit[fit.names.index('p.value')]
If working with the low-level interface, you will essentially have to implement your own convenience wrapper to reproduce these functionalities. For example:
def dollar(obj, name):
"""R's "$"."""
return obj[fit.do_slot('names').index(name)]

Resources