Created
July 3, 2014 05:54
-
-
Save jstorry/6521537a9a4f759ebfc8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import urllib, json, re | |
recipe_url = 'http://diy.soylent.me/recipes/people-chow-301-tortilla-perfection' | |
profile_url = 'http://diy.soylent.me/nutrient-profiles/51e4e6ca7789bc0200000007' | |
s = urllib.urlopen(recipe_url + "/json" + str(profile_url and "?nutrientProfile=" + profile_url.split("/")[-1] or "")).read() | |
recipe = json.loads(s, 'iso-8859-15') | |
import pulp | |
#initialise the model | |
soylent_model = pulp.LpProblem('Soylent', pulp.LpMinimize) | |
# make a list of ingredients removing any non ascii characters | |
ingredients = [i["name"].encode('ascii', 'ignore') for i in recipe['ingredients']] | |
# create variable dict | |
x = pulp.LpVariable.dict('x_%s', ingredients, lowBound =0) | |
# calculate cost data | |
cost = dict(zip(ingredients, [i["container_size"] and float(i["item_cost"])/i["container_size"] or 0 | |
for i in recipe['ingredients']])) | |
# set objective | |
soylent_model += sum([cost[i] * x[i] for i in ingredients]) | |
# get nutrients values | |
nutrient_dict = dict([(n[:-4],{"min":recipe['nutrientTargets'][n[:-4]],"max":recipe['nutrientTargets'][n]}) | |
for n in recipe['nutrientTargets'] if n.endswith('_max')]) | |
nutrients = nutrient_dict.keys() | |
# calculate ingredient parameters | |
ingredient_parameters = {} | |
for n in nutrients: | |
ingredient_parameters[n] = dict(zip(ingredients, [i["serving"] and float(i[n])/i["serving"] or i[n] for i in recipe['ingredients']])) | |
# set constraints | |
for n in nutrients: | |
soylent_model += sum([ingredient_parameters[n][i]*x[i] for i in ingredients]) >= nutrient_dict[n]["min"] | |
if nutrient_dict[n]["max"]: | |
soylent_model += sum([ingredient_parameters[n][i]*x[i] for i in ingredients]) <= nutrient_dict[n]["max"] | |
# solve | |
soylent_model.solve() | |
# output status | |
# Note: if status isn't optimal the recipe won't be 100 percent and will have weird amounts | |
print "Status: ", pulp.LpStatus[soylent_model.status] | |
# output required amounts | |
for ingredient in ingredients: | |
cost_per_unit = x[ingredient].value() | |
print 'The amount of %s is %s units per batch'%(ingredient, | |
cost_per_unit) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment