I am coding a heuristic for an optimization problem from the field of production. In this heuristic I have various conditions, stop criteria etc. In order to account for these different criteria, I worked with multiple nested loops, as you can see in the code below:
for tao in PERIODS:
print ("Iteration:", tao)
print ("-----------------------------------------")
print (SETUP_ITEMS)
for z in range(1,periods_count+1-tao):
print("z =",z)
for k in SETUP_ITEMS[tao+z]:
print("k =",k)
#### EXCEPTION 1
if production.loc[k][tao] == 0:
print("There is no setup in this period for product {}.".format(k))
counter =+ 1
continue
#### EXCEPTION 2
if demand.loc[k][tao+z] > spare_capacity[tao]['Spare Capacity']:
print("Capacity in period {} is insufficient to pre-produce demands for product {} from period {}.\n".format(tao, k, tao+z))
counter =+ 1
continue
if counter == k:
print("Stop Criterion is met!")
break
##########################################################################
if SM == 1:
if SilverMeal(k,z) == True:
print("Silver Meal Criterion is", SilverMeal(k,z))
production.loc[k][tao] += demand.loc[k][tao+z]
production.loc[k][tao+z] = 0
else:
print("Else: Silver Meal Criterion is", SilverMeal(k,z))
for t in range(tao,periods_count+1):
for k in PRODUCTS:
spare_capacity[t] = capacity[t][1]-sum(production.loc[k][t] for k in PRODUCTS)
SETUP_ITEMS = [[] for t in range(0,periods_count+1)]
for t in PERIODS:
for k in PRODUCTS:
if production.loc[k][t]==(max(0,demand.loc[k][t]-stock.loc[k][t-1])) > 0:
SETUP_ITEMS[t].append(k)
print(productionplan(production,spare_capacity,CF), '\n\n')
print(productionplan(production,spare_capacity,CF), '\n\n')
The idea is, that if for one tao
, there is an exception true for all k
, all the loops terminate early, apart from the most outer one, so that we would go to the next tao
in PERIODS
and it all starts again.
I tried to use it with the counter
variable, but this did not turn out to be functioning really well.
I currently have for example this output (extract):
z = 1
k = 1
Capacity in period 1 is insufficient to pre-produce demands for product 1 from period 2.
k = 2
Capacity in period 1 is insufficient to pre-produce demands for product 2 from period 2.
z = 2
k = 2
Capacity in period 1 is insufficient to pre-produce demands for product 2 from period 3.
After the k=2
in z=1
the iteration should terminate, but it keeps on checking further z
values.
Could anyone give me a tip how to solve this issue? I read about putting loops into functions, so that one can break out of multiple loops, but I am not sure how to formulate this here, as I would have multiple points of exit..
Thanks!