buy = {f: mdl.add_var(name=f) for f in dat.foods} # Nutrition constraints for c in dat.categories: mdl.add_constraint(mdl.sum(dat.nutrition_quantities[f, c]["Quantity"] * buy[f] for f in dat.foods) == nutrition[c], name=c) mdl.set_objective(mdl.sum(buy[f] * c["Cost"] for f, c in dat.foods.items())) if mdl.optimize(): sln = solution_schema.TicDat() for f, x in buy.items(): if mdl.get_solution_value(x) > 0: sln.buy_food[f] = mdl.get_solution_value(x) for c, x in nutrition.items(): sln.consume_nutrition[c] = mdl.get_solution_value(x) sln.parameters['Total Cost'] = sum(dat.foods[f]["Cost"] * r["Quantity"] for f, r in sln.buy_food.items()) return sln # --------------------------------------------------------------------------------- # ------------------------ provide stand-alone functionality ---------------------- # when run from the command line, will read/write xls/csv/db/sql/mdb files if __name__ == "__main__": standard_main(input_schema, solution_schema, solve) # ---------------------------------------------------------------------------------
class CogStopProgress(Progress): def mip_progress(self, theme, lower_bound, upper_bound): super(CogStopProgress, self).mip_progress(theme, lower_bound, upper_bound) print("%s:%s:%s"%(theme.ljust(30), "Percent Error".ljust(20), percent_error(lower_bound, upper_bound))) # return False (to stop optimization) if the cog.stop file exists return not os.path.exists("cog.stop") # creating a single argument version of solve to pass to standard_main def _solve(dat): # create local text files for logging with LogFile("output.txt") as out : with LogFile("error.txt") as err : solution = solve(dat, out, err, CogStopProgress()) if solution : print('\n\nUpper Bound : %g' % solution.parameters["Upper Bound"]["value"]) print('Lower Bound : %g' % solution.parameters["Lower Bound"]["value"]) print('Percent Error : %s' % percent_error(solution.parameters["Lower Bound"]["value"], solution.parameters["Upper Bound"]["value"])) return solution else : print('\nNo solution') standard_main(dataFactory, solutionFactory, _solve) # ---------------------------------------------------------------------------------