Pyomo scheduling - optimization

I am trying to formulate a flowshop scheduling problem in Pyomo. This is an Abstract model
Problem description
There are 3 jobs (chest, door and chair) and 3 machines (cutting, welding, packing in that order). Objective is to minimise the makespan. The python code and the data are as follows.
## flowshop.py ##
from pyomo.environ import *
flowshop = AbstractModel()
flowshop.jobs = Set()
flowshop.machines = Set()
flowshop.machinesN = Param()
flowshop.jobsN = Param()
flowshop.proc_T = Param(flowshop.jobs,
flowshop.machines,
within=NonNegativeReals)
flowshop.start_T = Var(flowshop.jobs,
flowshop.machines,
within=NonNegativeReals)
flowshop.makespan = Var(within=NonNegativeReals)
def makespan_rule(flowshop,i,j):
return flowshop.makespan >= flowshop.start_T[i,j]+flowshop.proc_T[i,j]
flowshop.makespan_cons = Constraint(flowshop.jobs,
flowshop.machines,
rule=makespan_rule)
def objective_rule(flowshop):
return flowshop.makespan
flowshop.objc = Objective(rule=objective_rule,sense=minimize)
## data.dat ##
set jobs := chest door chair ;
set machines := cutting welding packing ;
param: machinesN := 3 ;
param: jobsN := 3 ;
param proc_T:
cutting welding packing :=
chest 10 40 45
door 30 20 25
chair 05 30 15
;
I havent added all the constraints yet, I plan to add them after this issue gets fixed. In the code (flowhop.py) above, for the makespan_rule, I want the makespan to be more that the completion time of only the last machine.
Currently, it is set to be more than completion times of all the machines.
For that, I believe, I have to get the last index of the machines set.
For that, I tried flowshop.machines[-1], but it gives an error saying:
Cannot index unordered set machines
How do I solve this issue?
Thanks for the help.
PS - I am also struggling to model the binary variables used to define the precedence of a job. If you have any ideas regarding that, that would also be helpful.

As the error says Cannot index unordered sets, the set flowshop.machines is not ordered. One needs to provide ordered=True argument in the while declaring the set -
flowshop.machines = Set(ordered=True)
After this, one can access any element by normal indexing - flowshop.machines[i]
For the binary variables, one can declare them as -
c = flowshop.jobsN*(flowshop.jobsN-1)/2
flowshop.prec = Var(RangeSet(1,c),within=Binary)
Then, this variable can be used to decide the precedence between 2 jobs and to formulate the assignment constraints. The precedence variable corresponding to a pair of jobs can be found out using the indices of the jobs (for which the flowshop.jobs has to be an ordered set - flowshop.jobs = Set(ordered=True))

Related

Print multiple data sets in a range

I've made a small program that is supposed to read data in a range input it into an object oriented program, and then return the full data set. the issue is that when I run the file it only return data on the third procedure
I tried printing other procedure sets but idk how to do that, i'm thinking this will only work if i replace the procedures from generic to specific. as in instead of Procedure name for all of them procedures 1, 2, and 3
for i in range (3):
procedure_name = ('Physical Exam')
date_of = ("Nov 6th 2022")
doctor = ('Dr. Irvine')
charge = ('$ 250.00')
procedure_name = ('X-ray')
date_of = ("Nov 6th 2022")
doctor = ('Dr. Jamison')
charge = ('$ 500.00')
procedure_name = ('Blood test')
date_of = ("Nov 6th 2022")
doctor = ('Dr. Smith')
charge = ('$ 200.00')
procedure = HW6_RODRIGUEZ_1.Procedure(procedure_name,date_of,doctor,charge)
print(f'Procedure {i+1}')
print(procedure)
print(i, end=" ")
if name == 'main':
main()
So, I think you may have misunderstood some things when it comes to variables, OOP and looping.
When you define a variable, that variable is set to the last value it is assigned. So if you have the following code:
a = 1
a = 2
a = 3
The final value of the variable 'a' will be 3, as that is the last value it is assigned.
As for loops, whatever you have written in a for loop will be repeated for a specified number of times. This means if you want to write a loop that prints "hello" 5 times, you'd write the following:
for i in range(5):
print("hello")
What your loop is essentially doing is overwriting the same 3 variables 3 times over, this won't be assigning new values to an object.
When it comes to creating an object that you assign variable to, you need to first write the code for your class. Your class can have attributes like the variables you've stated. It could look something like this:
class procedure:
def __init__(self, procedure_name, date_of, doctor, charge):
self.procedure_name = procedure_name
self.date_of = date_of
self.doctor = doctor
self.charge = charge
Now, to set up a procedure object, you just assign a variable to procedure with the desired variables as parameters, like so:
new = procedure('X-ray','Nov 6th 2022','Dr. Jamison','$ 500.00')
And to access a variable, you just need to write procedureName.attribute. For example, using the object I just set up:
print(new.doctor)
Would output 'Dr. Jamison'.
If you want to store a bunch of them, I would recommend storing them in a list or a dictionary, depending on how you want to look them up.
I hope this helps! If you are new to programming, I would recommend some simpler programs such as a program that prints the nursery rhyme 10 green bottles using loops, or maybe making a quiz.
Best of luck.

Problem with decision variabile when there are more choices

I have a series of jobs. For each job I have a series of operations and each operation requires a machine. But there are some operations that have the ability to choose multiple machines.
Ex:
job 1: operation 1 machine 4
operation 2 machine 2
operation 3 (machine 2 or machine 3)
I have a binary decision variable Y (ijm) where i is the operation, j the job and m the machine.
What must happen is that Y(114) = 1, Y (212) = 1 but for operation 3 we have two choices Y(312) = 0 and Y(313) = 1 or the opposite.
How can I implement it on Cplex? I can't find a way.
You could use a logical constraint like this in OPL:
((x==2) && (y==1)) || ((x==1) && (y==2));
But you could also have a look at CPOptimizer within CPLEX because your model looks like a scheduling problem.
A simple way to model your requirement that Y(312) = 0 and Y(313) = 1 or the opposite would be to add a constraint that the sum of the alternatives must be 1, i.e. in your case add a constraint:
Y(312) + Y(313) = 1
Then if the variables are binary or integer then this will achieve your aim.

TensorFlow2 beginner, recalculating after assigning new value

I'm new to TensorFlow (using TensorFlow2).
Trying to understand how to re-calculate a simple calculation, after re-assigning a value to variable. It sounds simple, but I'm having a hard time finding it in the new TF2 documentation.
Simple example: define a tensor which is a sum two variables (3+4). Then, if I re-assign one of the variables, I'd like to re-use this "sum tensor" - making it re-calculate (without having to create a new "sum tensor"). Is there a way to achieve this please? thank!
v1 = tf.Variable(3)
v2 = tf.Variable(4)
sum1=tf.add(v1,v2)
print("Original sum 3+4:",sum1) # This hows 7 as expected
v1.assign(9)
print("Sum after re-assign",sum1) # Fails, shows the old 7
You forgot to reassign the sum.
It's just like in plain programming:
a = 5
b = 10
c = a + b #yields 15
b = 100
print(c) #of course here, if you print c it would still be 15.
new_sum = tf.add(v1,v2)
print("Sum after re-assign", new_sum)

How do I represent this data using Redis?

I want to be able to store data such as "store x is open between 9am and 5pm on Monday but it's only open during 9am and 12pm on Saturday"
What's the best way to store this using redis?
I would later like to query it using something like this. Show me all stores that are open on Saturday at 10:30am
In Redis, like most if not all other NoSQL databases, you want to store your data in the manner that's most suitable for answering the query. There are quite a few ways you can represent this data and answer the query, choosing between them requires knowledge about the other access patterns that you need to support.
However, in the context of this specific question alone, the simplest way of doing that IMO is to use two Sorted Sets per for each day of the week. Assuming that stores are open continuously and at most once each day (i.e. no siestas), the members of these Sorted Sets should be the store ids and the scores their opening hours - the first Sort Set's scores will denote the time that the store opens whereas the second's the time it closes. For example:
ZADD monday:open 9 store:x
ZADD monday:close 17 store:x
ZADD saturday:open 9 store:x
ZADD saturday:close 12 store:x
Once you have all the Sorted Sets in place, answering the query requires two calls to ZRANGEBYSCORE and intersecting the results. The snippet below demonstrates how to do it using Lua since doing using server scripts will be more efficient than moving the entire thing to the client in most cases.
Note: an alternative approach to doing the intersect in Lua is actually storing the temporary results in Redis' Sets and calling SINTER.
-- helper function to make a "set" out of a table
local function makeset(t)
local r = {}
for _, v in ipairs(t) do r[v] = true end
return(r)
end
-- get opening and closing hours for a given day
local ot = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', ARGV[1])
local ct = redis.call('ZRANGEBYSCORE', KEYS[2], '(' .. ARGV[1], '+inf')
-- convert to sets and choose the smaller set as s1
local s1 = {}
local s2 = {}
if #ot < #ct then
s1 = makeset(ot)
s2 = makeset(ct)
else
s1 = makeset(ct)
s2 = makeset(ot)
end
-- intersect s1 and s2
local t = {}
for k in pairs(s1) do
t[k] = s2[k]
end
-- prepare a response table
local r = {}
for k in pairs(t) do
r[#r+1] = k
end
return(r)
Run this script by passing to it the two keys and the hour, like so:
redis-cli --eval storehours.lua saturday:open saturday:close , 10.5

Deterministic/non-deterministic state system mapping

I read in a book on non-deterministic mapping there is mapping from Q*∑ to 2Q for M=(Q,∑,trans,q0,F)
where Q is a set of states.
But I am not able to understand how it's 2Q;
if there are 3 states a, b, c, how does it map to 8 states?
I always found that the easiest way to think about these (since the set of states is finite) is as having each of those subsets be an encoding of a base-2 number that ranges from 0 (all bits zero) to 2|Q|-1 (all bits one), where there are as many bits in the number as there are members in the state set, Q. Then, you can just take one of these numbers and map it into a subset by using whether a particular bit in the number is set. Easy!
Here's a worked example where Q = {a,b,c}. In this case, |Q| is 3 (there are three elements) and so 23 is 8. That means we get this if we say that the leading bit is for element a, the next bit is for b, and the trailing bit for c:
0 = 000 = {}
1 = 001 = {c}
2 = 010 = {b}
3 = 011 = {b,c}
4 = 100 = {a}
5 = 101 = {a,c}
6 = 110 = {a,b}
7 = 111 = {a,b,c}
See? That initial three states has been transformed into 8, and we have a natural numbering of them that we could use to create the labels of those states if we chose.
Now, to the interpretations of this within a non-deterministic context. Basically, the non-determinism means that we're uncertain about what state we're in. We represent this by using a pseudo-state that is the set of “real” states that we might be in; if we have total non-determinism then we are in the pseudo-state where all real-states are possible (i.e., {a,b,c}) whereas the pseudo-state where no real-states are possible (i.e., {}) is the converse (and really ought to be impossible to reach in the transition system). In a real system, you're usually not dealing with either of those extremes.
The logic of how you convert the deterministic transition system into a non-deterministic one is rather more complex than I want to go into here. (I had to read a substantial PhD thesis to learn it so it's definitely more than an SO answer's worth!)
2Q means the set of all subsets of Q. For each state q and each letter x from sigma, there is a subset of Q states to which you can go from q with letter x. So yeah, if there are three states abc the set 2Q consists of 8 elements {{}, {a}, {b}, {c}, {a,b}, {a,c}, {b,c}, {a,b,c}}. It doesn't map to 8 states, it maps to one of these 8 sets. HTH