import cobra.test

model = cobra.test.create_test_model("textbook")
solver = cobra.solvers.cglpk

"""
Explanation: Solver Interface
Each cobrapy solver must expose the following API. The solvers all will have their own distinct LP object types, but each can be manipulated by these functions. This API can be used directly when implementing algorithms efficiently on linear programs because it has 2 primary benefits:


Avoid the overhead of creating and destroying LP's for each operation


Many solver objects preserve the basis between subsequent LP's, making each subsequent LP solve faster


We will walk though the API with the cglpk solver, which links the cobrapy solver API with GLPK's C API.
End of explanation
"""


solver.solver_name

model.optimize(solver="cglpk")

"""
Explanation: Attributes and functions
Each solver has some attributes:
solver_name
The name of the solver. This is the name which will be used to select the solver in cobrapy functions.
End of explanation
"""


solver._SUPPORTS_MILP

"""
Explanation: _SUPPORTS_MILP
The presence of this attribute tells cobrapy that the solver supports mixed-integer linear programming
End of explanation
"""


solver.solve(model)

"""
Explanation: solve
Model.optimize is a wrapper for each solver's solve function. It takes in a cobra model and returns a solution
End of explanation
"""


lp = solver.create_problem(model, objective_sense="maximize")
lp

"""
Explanation: create_problem
This creates the LP object for the solver.
End of explanation
"""


solver.solve_problem(lp)

"""
Explanation: solve_problem
Solve the LP object and return the solution status
End of explanation
"""


solver.format_solution(lp, model)

"""
Explanation: format_solution
Extract a cobra.Solution object from a solved LP object
End of explanation
"""


solver.get_objective_value(lp)

"""
Explanation: get_objective_value
Extract the objective value from a solved LP object
End of explanation
"""


solver.get_status(lp)

"""
Explanation: get_status
Get the solution status of a solved LP object
End of explanation
"""


model.reactions.index("Biomass_Ecoli_core")

solver.change_variable_objective(lp, 12, 2)
solver.solve_problem(lp)
solver.get_objective_value(lp)

solver.change_variable_objective(lp, 12, 1)
solver.solve_problem(lp)
solver.get_objective_value(lp)

"""
Explanation: change_variable_objective
change the objective coefficient a reaction at a particular index. This does not change any of the other objectives which have already been set. This example will double and then revert the biomass coefficient.
End of explanation
"""


solver.change_variable_bounds(lp, 12, 1000, 1000)
solver.solve_problem(lp)

solver.change_variable_bounds(lp, 12, 0, 1000)
solver.solve_problem(lp)

"""
Explanation: change variable_bounds
change the lower and upper bounds of a reaction at a particular index. This example will set the lower bound of the biomass to an infeasible value, then revert it.
End of explanation
"""


model.metabolites.index("atp_c")

model.reactions.index("ATPM")

solver.change_coefficient(lp, 16, 10, -10)
solver.solve_problem(lp)

solver.change_coefficient(lp, 16, 10, -1)
solver.solve_problem(lp)

"""
Explanation: change_coefficient
Change a coefficient in the stoichiometric matrix. In this example, we will set the entry for ADP in the ATMP reaction to in infeasible value, then reset it.
End of explanation
"""


solver.set_parameter(lp, "tolerance_feasibility", 1e-9)

solver.set_parameter(lp, "objective_sense", "minimize")
solver.solve_problem(lp)
solver.get_objective_value(lp)

solver.set_parameter(lp, "objective_sense", "maximize")
solver.solve_problem(lp)
solver.get_objective_value(lp)

"""
Explanation: set_parameter
Set a solver parameter. Each solver will have its own particular set of unique paramters. However, some have unified names. For example, all solvers should accept "tolerance_feasibility."
End of explanation
"""


%%time
# work on a copy of the model so the original is not changed
m = model.copy()

# set the lower bound on the objective to be the optimal value
f = m.optimize().f
for objective_reaction, coefficient in m.objective.items():
    objective_reaction.lower_bound = coefficient * f

# now maximize and minimze every reaction to find its bounds
fva_result = {}
for r in m.reactions:
    m.change_objective(r)
    fva_result[r.id] = {
        "maximum": m.optimize(objective_sense="maximize").f,
        "minimum": m.optimize(objective_sense="minimize").f
    }

"""
Explanation: Example with FVA
Consider flux variability analysis (FVA), which requires maximizing and minimizing every reaction with the original biomass value fixed at its optimal value. If we used the cobra Model API in a naive implementation, we would do the following:
End of explanation
"""


%%time
# create the LP object
lp = solver.create_problem(model)

# set the lower bound on the objective to be the optimal value
solver.solve_problem(lp)
f = solver.get_objective_value(lp)
for objective_reaction, coefficient in model.objective.items():
    objective_index = model.reactions.index(objective_reaction)
    # old objective is no longer the objective
    solver.change_variable_objective(lp, objective_index, 0.)
    solver.change_variable_bounds(
        lp, objective_index, f * coefficient,
        objective_reaction.upper_bound)

# now maximize and minimze every reaction to find its bounds
fva_result = {}
for index, r in enumerate(model.reactions):
    solver.change_variable_objective(lp, index, 1.)
    result = {}
    solver.solve_problem(lp, objective_sense="maximize")
    result["maximum"] = solver.get_objective_value(lp)
    solver.solve_problem(lp, objective_sense="minimize")
    result["minimum"] = solver.get_objective_value(lp)
    solver.change_variable_objective(lp, index, 0.)
    fva_result[r.id] = result

"""
Explanation: Instead, we could use the solver API to do this more efficiently. This is roughly how cobrapy implementes FVA. It keeps uses the same LP object and repeatedly maximizes and minimizes it. This allows the solver to preserve the basis, and is much faster. The speed increase is even more noticeable the larger the model gets.
End of explanation
"""


