PYOMO: Indexing set of tuples - pyomo

I want to create an indexing set of tuples, i mean if i do:
LINEAS_DOWNSTREAM_BARRA[1] I want to see [(1,3),(1,2),(1,4)].
My code is:
m=ConcreteModel()
m.BARRAS = Set()
m.LINEAS_DOWNSTREAM_BARRA = Set(dimen = 2)
m.LINEAS_DOWNSTREAM_BARRA = Set(m.BARRAS, initialize=lambda m, i:
set(tuple(z) for z in m.LINEAS if (i == z[0])))
And the problem is:
ValueError: The value=(1, 2) is a tuple for
set=LINEAS_DOWNSTREAM_BARRA, which has dimen=1
Thanks!!

You should declare the Set m.LINEAS_DOWNSTREAM_BARRA on a single line. Also, make sure that your lambda function is returning a list of tuples
m.LINEAS_DOWNSTREAM_BARRA = Set(m.BARRAS, dimen=2, initialize=your_lambda_fcn)

Related

How to display interaction element with order way of list one in Kotlin

I have two lists and I want to return a result in the following way:
the result should contain elements that are in list one and list two
output should be same order as per first list
Input :
val first = listOf(1, 2, 3, 4, 5,7,9,15,11)
val second = listOf(2, 15 , 4,3, 11)
Output:
val output = listOf(2,3,4,15,11)
Please help me to learn how to get common values in both lists in order of list first in Kotlin.
You can do
val output = first.filter { second.contains(it) }
What you are looking for is the intersection of the two lists:
val output = first.intersect(second)
As pointed out by #Ivo the result is a Set which can be turned into a list with output.toList(). However, since the result is a set, it contains no duplicates, e.g. if first is listOf(1,2,3,1,2,3) and second is listOf(2,4,2,4), the result will be equal to setOf(2).
If this is not acceptable, the solution of #Ivo should be used instead.

List will not sort after appending variables to it (python 3)

I am working on another piece of code right now, however, I took a snippet out to show what happens when I try and sort a list after appending two variables to it. Any idea how I can fix this?
player1score = 10
player2score = 20
listwin = list()
listwin.append(player1score)
listwin.append(player2score)
sorted(listwin)
print(sorted(listwin))
Calling the sorted method does not update your list. You need to use list.sort():
player1score = 10
player2score = 20
listwin = list()
listwin.append(player1score)
listwin.append(player2score)
listwin.sort()
print(listwin)
The difference between those methods is that sorted(listwin) returns a copy of listwin without changing it, while listwin.sort() changes listwin.

Convert List into a integer or float

so i'm having a problem converting to a list to integer or float. what i mean in converting is like this. i have a list that has one element.
newList = ['2.0G']
i want that to convert into this
numFloat = 2.0
or
numInt = 2
i tried regex to extract the number from string so i can assign it to another variable
firstVariable = re.findall(r"[-+]?\d*\.\d+|\d+", newList[0])
i have to keep calling the index in firstVariable to access the 2.0 or 2
Does this work ?
newList = ['2.0G']
numFloat = ''.join([i for i in newList[0] if i.isdigit() or i == '.'])
print(numFloat)
The above code will print 2.0 to the console.
What I am doing here, is that I am going through each and every item in the first item of the list , and then checking if its a digit or a .. If its not any one of these I move to the next character.
Please note that I am doing newList[0] because you mentioned that your list has only one element.
Please let me know if this works for you.
Thanks.

Select a batch from a matrix in a loop

Assume I have the following matrix:
X = np.array([[1,2,3], [4,5,6], [7,8,9], [70,80,90], [45,43,68], [112,87,245]])
I want to draw a batch of 2 random rows at each time loop, and send it to a function. For instance, a batch in iteration i can be batch = [[4,5,6], [70,80,90]]
I do the following:
X = np.array([[1,2,3], [4,5,6], [7,8,9], [70,80,90], [45,43,68], [112,87,245]])
def caclulate_batch(batch):
pass
for i in range(X.shape[0]/2):
batch = np.array([])
for _ in range(2):
r = random.randint(0, 5)
batch = np.append(batch, X[r])
caclulate_batch(batch)
There are two problems here: (1) It returns appended array (2) The random number can be repeated which can choose the same row many times. How can modify the code to fit my requirement.
r = np.random.randint(0, len(x), 2) should get you the indices. That lets you use fancy indexing to get the subset: batch = x[r, :].
If you want to accumulate arrays along a new dimension, as your loop does, use np.stack or np.block instead of np.append.
(1) You can use numpy.stack instead of append. EDIT: But this function would be called when you have all your batch in a list like:
list = ([1,2], [3,4])
numpy.stack(list)
# gives [[1,2],
# [3,4]]
(2) You can shuffle X array, loop through the results and extract two by two. Look at numpy.random.shuffle
It would look like that:
S = np.random.shuffle(X)
for i in range(S.shape[0]/2):
batch = S[i*2:i*2+1]
caclulate_batch(batch)

Sequence of dictionaries in python

I am trying to create a sequence of similar dictionaries to further store them in a tuple. I tried two approaches, using and not using a for loop
Without for loop
dic0 = {'modo': lambda x: x[0]}
dic1 = {'modo': lambda x: x[1]}
lst = []
lst.append(dic0)
lst.append(dic1)
tup = tuple(lst)
dic0 = tup[0]
dic1 = tup[1]
f0 = dic0['modo']
f1 = dic1['modo']
x = np.array([0,1])
print (f0(x) , f1(x)) # 0 , 1
With a for loop
lst = []
for j in range(0,2):
dic = {}
dic = {'modo': lambda x: x[j]}
lst.insert(j,dic)
tup = tuple(lst)
dic0 = tup[0]
dic1 = tup[1]
f0 = dic0['modo']
f1 = dic1['modo']
x = np.array([0,1])
print (f0(x) , f1(x)) # 1 , 1
I really don't understand why I am getting different results. It seems that the last dictionary I insert overwrite the previous ones, but I don't know why (the append method does not work neither).
Any help would be really welcomed
This is happening due to how scoping works in this case. Try putting j = 0 above the final print statement and you'll see what happens.
Also, you might try
from operator import itemgetter
lst = [{'modo': itemgetter(j)} for j in range(2)]
You have accidentally created what is know as a closure. The lambda functions in your second (loop-based) example include a reference to a variable j. That variable is actually the loop variable used to iterate your loop. So the lambda call actually produces code with a reference to "some variable named 'j' that I didn't define, but it's around here somewhere."
This is called "closing over" or "enclosing" the variable j, because even when the loop is finished, there will be this lambda function you wrote that references the variable j. And so it will never get garbage-collected until you release the references to the lambda function(s).
You get the same value (1, 1) printed because j stops iterating over the range(0,2) with j=1, and nothing changes that. So when your lambda functions ask for x[j], they're asking for the present value of j, then getting the present value of x[j]. In both functions, the present value of j is 1.
You could work around this by creating a make_lambda function that takes an index number as a parameter. Or you could do what #DavisYoshida suggested, and use someone else's code to create the appropriate closure for you.