Skip to content

Base Classes

Model

Source code in minimod_opt/base/model.py
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
class Model:


    def __init__(self, data:pd.DataFrame, sense:str, solver_name:str, show_output:bool):
        """A class that instantiates a `mip` model.

        Args:
            data (pd.DataFrame): The input dataframe that includes benefit/cost data
            sense (str): Whether the model should minimize (MINIMIZE) or maximize (MAXIMIZE)
            solver_name (str): The solver type (CBC or some other mip solver)
            show_output (bool):  Whether to show output of model construction
        """


        ## Tell the fitter whether to maximize or minimize
        self.model = mip.Model(sense=sense, solver_name=solver_name)

        self._df = data

        self.show_output = show_output

        if self.show_output:
            self.model.verbose = 1
        else:
            self.model.verbose = 0
        ## set tolerances based on GAMS tolerances
        # primal tol -> infeas
        # dual tol -> opt tol
        # integer  tol -> integer_tol
        # self.model.opt_tol = 1e-10
        # self.model.infeas_tol = 1e-10
        # self.model.integer_tol = 1e-06
        # self.model.seed = 0
        # # self.model.clique = 0

        # # # # # allowable gap/ optca -> max_mip_gap_abs
        # # # # # ratioGap/ optcr -> max_mip_gap

        # self.model.max_mip_gap_abs = 0
        # self.model.max_mip_gap = 0.1

        # self.model.preprocess = 0
        # self.model.lp_method = -1
        # self.cut_passes = 1

    def _stringify_tuple(self, tup:tuple)->str:
        """This function converts all the items of a tuple into one string

        Args:
            tup (tuple): general tuple 

        Returns:
            str: output string generated from all items in the tuple
        """

        strings = [str(x) for x in tup]

        stringified = "".join(strings)

        return stringified

    def _model_var_create(self):

        self._df["mip_vars"] = self._df.apply(
            lambda x: self.model.add_var(
                var_type=mip.BINARY, name=f"x_{self._stringify_tuple(x.name)}"
            ),
            axis=1,
        )

    def _base_constraint(self, space:str, time:str):
        """Constraint making the 'ones' constraint, making an intervention a binary intervention.

        Args:
            space (str): name of dataframe's column with information on regions/locations
            time (str): name of dataframe's column with information on time/years
        """
        grouped_df = self._df["mip_vars"].groupby([space, time]).agg(mip.xsum)

        base_constrs = grouped_df.values

        # Get constraint name
        names = list(
            map(
                self._stringify_tuple,
                grouped_df.index.to_list()
            )
        )

        for constr, name in zip(base_constrs, names):

            self.model += constr <= 1, "ones_" + name

    def _intervention_subset(self, intervention:str, strict:bool, subset_names:list =[])-> dict:
        """This function creates a dictionary for the subset of specified interventions

        Args:
            intervention (str): name of dataframe's column with set of interventions 
            strict (bool): whether to look for specific intervention names (using DataFrame.isin) or whether to look for a regex (using DataFrame.str.contains)
            subset_names (list, optional): Which intervention names to look for. Defaults to [].

        Returns:
            dict: dictionary with subset of interventions
        """

        subset_dict = {}

        for i in subset_names:

            if strict:
                subset_dict[i[0]] = self._df.loc[
                    lambda df: df.index.get_level_values(level=intervention).isin([i])
                ]

                if subset_dict[i[0]].empty:
                    raise Exception(f"'{i[0]}' not found in dataset.")

            else:
                subset_dict[i] = self._df.loc[
                    lambda df: df.index.get_level_values(
                        level=intervention
                    ).str.contains(i, case=False)
                ]

                if subset_dict[i].empty:
                    raise Exception(f"'{i}' not found in dataset.")

        return subset_dict

    def _all_constraint(
        self,
        strict:bool,
        intervention:str=None,
        space:str=None,
        time:str=None,
        subset_names:list=None,
        over:str=None,
        subset_list:list=None,
    ):
        """A constraint across space or time, where an intervention is tied to other interventions across space time (for a given subset). For instance, if you wanted to
        create a national intervention, for some intervention X, with 2 regions, this constraint would do the following:

        $X_{region1,t} == X_{region2,t}$ -> _all_constraint(over='space', subset_names=None)

        If you wanted to make sure that interventions were tied across time so that period 2 could only be used if period 1 was used:

        $X_{region1, 1} == X_{region1, 2}$

        Args:
            strict (bool): whether to look for specific intervention names (using DataFrame.isin) or whether to look for a regex (using DataFrame.str.contains)
            intervention (str, optional): name of dataframe's column with set of interventions. Defaults to None.
            space (str, optional): name of dataframe's column with information on regions/locations. Defaults to None.
            time (str, optional): name of dataframe's column with information on time/year. Defaults to None.
            subset_names (list, optional): Which intervention names to look for. Defaults to None.
            over (str, optional): name of dataframe's column  with attribute used to group data by (e.g., time, region). Defaults to None.
            subset_list (list, optional): A list of interventions that are being constrained. Defaults to None.
        """

        subset_dict = self._intervention_subset(
            intervention=intervention, strict=strict, subset_names=subset_names
        )
        for sub in subset_dict.keys():

            mip_vars_grouped_sum = (
                subset_dict[sub].groupby([space, time])["mip_vars"].agg(mip.xsum)
            )

            if over == time:
                slicer = space
            elif over == space:
                slicer = time

            unstacked = mip_vars_grouped_sum.unstack(level=slicer)

            if subset_list is None:
                subset_list = unstacked.index

            # get combinations of different choices
            constraint_combinations = permutations(unstacked.index.tolist(), 2)

            constraint_list = [
                (i, j) for (i, j) in constraint_combinations if i in subset_list
            ]

            for col in unstacked.columns:
                for (comb1, comb2) in constraint_list:
                    self.add_constraint(
                        unstacked[col].loc[comb1], unstacked[col].loc[comb2], 
                        "eq",
                        name = str(sub) + "_" + str(col) + "_" + str(comb1) + "_" + str(comb2)
                    )

    def _all_space_constraint(
        self,
        strict:bool,
        intervention:str=None,
        space:str=None,
        time:str=None,
        subset_names:list=None,
        over:str=None,
        subset_list:list=None,
    )->None:
        """This function invokes the function `_all_constraint' to create national interventions

        Args:
            strict (bool): whether to look for specific intervention names (using DataFrame.isin) or whether to look for a regex (using DataFrame.str.contains)
            intervention (str, optional): name of dataframe's column with set of interventions. Defaults to None.
            space (str, optional): name of dataframe's column with informaiton on regions/locations. Defaults to None.
            time (str, optional): name of dataframe's column with information on time/year. Defaults to None.
            subset_names (list, optional): Which intervention names to look for. Defaults to None.
            over (str, optional): name of dataframe's column  with attribute used to group data by (e.g., time, region). Defaults to None.
            subset_list (list, optional): A list of interventions that are being constrained. Defaults to None.
        """

        return self._all_constraint(
            strict,
            intervention=intervention,
            space=space,
            time=time,
            subset_names=subset_names,
            over=over,
            subset_list=subset_list,
        )

    def _all_time_constraint(
        self,
        strict:bool,
        intervention:str=None,
        space:str=None,
        time:str=None,
        subset_names:list=None,
        over:str=None,
        subset_list:list=None,
    )->None:
        """This function invokes the function `_all_constraint'

        Args:
            strict (bool): whether to look for specific intervention names (using DataFrame.isin) or whether to look for a regex (using DataFrame.str.contains)
            intervention (str, optional): name of dataframe's column with set of interventions. Defaults to None.
            space (str, optional): name of dataframe's column with information on regions/locations. Defaults to None.
            time (str, optional): name of dataframe's column with information on time/year. Defaults to None.
            subset_names (list, optional): Which intervention names to look for. Defaults to None.
            over (str, optional): name of dataframe's column  with attribute used to group data by (e.g., time, region). Defaults to None.
            subset_list (list, optional): A list of interventions that are being constrained. Defaults to None.
        """

        return self._all_constraint(
            strict,
            intervention=intervention,
            space=space,
            time=time,
            subset_names=subset_names,
            over=over,
            subset_list=subset_list,
        )


    def get_equation(self, name:str=None, show:bool=True)->str or mip.LinExpr or mip.Constr :
        """This function returns a constraint by its name. If no name is specified, returns all constraints

        Args:
            name (str, optional): a string corresponding to the name of the constraint. Defaults to None.
            show (bool, optional): whether to return the contraint in string type or not. Defaults to True.

        Returns:
            str or mip.LinExpr or mip.Constr: A `mip` constraint object
        """

        if name is None:
            return self.model.constrs
        elif name == 'objective':
            if show:
                return str(self.model.objective)
            else:
                return self.model.objective
        else:
            if show:
                return str(self.model.constr_by_name(name))
            else:
                return self.model.constr_by_name(name)

    def add_objective(self, eq:mip.LinExpr):
        """Sets the objective function of the problem as a linear expression

        Args:
            eq (mip.LinExpr): equation defining the objective function
        """

        self.model.objective = eq

    def add_constraint(self, eq:mip.LinExpr, constraint:mip.LinExpr, way:str="ge", name:str=""):
        """This function merges the objective function of the model with its constraint

        Args:
            eq (mip.LinExpr): equation defining the objective function
            constraint (mip.LinExpr):equation defining the constraint function
            way (str, optional): whether greater or equal (ge), less or equal(le), or equal(eq). Defaults to "ge".
            name (str, optional): optional name for the constraint. Defaults to "".
        """

        if isinstance(constraint, pd.Series):
            # Merge equation with constraint
            df = eq.merge(constraint, left_index = True, right_index= True)

            for i, ee, c in df.itertuples():
                if way == "ge":
                    self.model += ee >= c, name
                elif way == "le":
                    self.model += ee <= c, name
                elif way == "eq":
                    self.model += ee == c, name


        else:
            if way == "ge":
                self.model += eq >= constraint, name
            elif way == "le":
                self.model += eq <= constraint, name
            elif way == "eq":
                self.model += eq == constraint, name

    def base_model_create(
        self,
        intervention:str,
        space:str,
        time:str,
        all_time:list=None,
        all_space:list=None,
        time_subset:list=None,
        space_subset:list=None,
        strict:bool=False,
    ):
        """A function   

        Args:
            intervention (str): name of dataframe's column with set of interventions
            space (str): name of dataframe's column with information on regions/locations
            time (str): name of dataframe's column with information on time/years
            all_time (list, optional): list of intervention vehicles that are active during all periods (e.g., cube, oil). Defaults to None.
            all_space (list, optional): list of intervention vehicles that are targeted at a country-wide level (e.g., cube, oil). Defaults to None.
            time_subset (list, optional): list with subset of periods. Defaults to None.
            space_subset (list, optional):list with subset of regions/locations. Defaults to None.
            strict (bool, optional): whether to look for specific intervention names (using DataFrame.isin) or whether to look for a regex (using DataFrame.str.contains). Defaults to False.

        """

        ## Now we create the choice variable, x, which is binary and is the size of the dataset.
        ## In this case, it should just be a column vector with the rows equal to the data:

        self._model_var_create()

        ## First add base constraint, which only allows one intervention per time and space
        self._base_constraint(space, time)

        ## Add all_space or all_time constraints if necessary
        if all_time is not None:

            if intervention is None or space is None:
                raise Exception("One of the subset columns were not found")

            self._all_time_constraint(
                strict,
                intervention=intervention,
                space=space,
                time=time,
                subset_names=all_time,
                over=time,
                subset_list=time_subset,
            )

        if all_space is not None:

            if intervention is None or time is None:
                raise Exception("One of the subset columns were not found")

            self._all_space_constraint(
                strict,
                intervention=intervention,
                space=space,
                time=time,
                subset_names=all_space,
                over=space,
                subset_list=space_subset,
            )

    def optimize(self, **kwargs):
        """This function conducts the optimization procedure 

        Args:
            **kwargs: Other parameters for optimization procedure using `mip.optimize' (max_seconds, max_nodes, max_solutions)
        """

        self.status = None

        if self.model.num_cols == 0:
            raise NoVars("No Variables added to the model")
        if self.model.num_rows == 0:
            raise NoConstraints("No constraints added to the model.")
        try:
            self.model.objective
        except Exception:
            raise NoObjective("No Objective added to the model")

        # Now, allow for arguments to the optimize function to be given:

        max_seconds = kwargs.pop("max_seconds", mip.INF)
        max_nodes = kwargs.pop("max_nodes", mip.INF)
        max_solutions = kwargs.pop("max_solutions", mip.INF)

        if self.show_output:
            self.status = self.model.optimize(max_seconds, max_nodes, max_solutions)
        else:
            with suppress_stdout_stderr():
                self.status = self.model.optimize(max_seconds, max_nodes, max_solutions)
        if self.show_output:
            if self.status == mip.OptimizationStatus.OPTIMAL:
                print("[Note]: Optimal Solution Found")
            elif self.status == mip.OptimizationStatus.FEASIBLE:
                print("[Note]: Feasible Solution Found. This may not be optimal.")
            elif self.status == mip.OptimizationStatus.NO_SOLUTION_FOUND:
                print("[Warning]: No Solution Found")
            elif self.status == mip.OptimizationStatus.INFEASIBLE:
                print("[Warning]: Infeasible Solution Found")

    def process_results(self, benefit_col:str, cost_col:str, intervention_col:str, space_col:str, sol_num:int = None)->pd.DataFrame:
        """This function creates a dataframe with information on benefits and costs for the optimal interventions

        Args:
            benefit_col (str): name of dataframe's column with benefits
            cost_col (str): name of dataframe's column with costs
            intervention_col (str): name of dataframe's column with set of interventions
            space_col (str): name of dataframe's column with information on regions/locations
            sol_num (int, optional): index of solution. Defaults to None.

        Returns:
            pd.DataFrame: dataframe with optimal interventions
        """


        if isinstance(sol_num, int):
            opt_df = self._df.copy(deep=True).assign(opt_vals=lambda df: df["mip_vars"].apply(lambda y: y.xi(sol_num)))
        else:
            opt_df = self._df.copy(deep=True).assign(
                opt_vals=lambda df: df["mip_vars"].apply(lambda y: y.x))

        opt_df = (opt_df.assign(
            opt_benefit=lambda df: df[benefit_col] * df["opt_vals"],
            opt_costs=lambda df: df[cost_col] * df["opt_vals"],
            opt_costs_discounted=lambda df: df["discounted_costs"] * df["opt_vals"],
            opt_benefit_discounted=lambda df: df["discounted_benefits"]* df["opt_vals"])
                  .infer_objects()
                  .assign(
            cumulative_discounted_benefits = lambda df: (df
                                                         .groupby([space_col])['opt_benefit_discounted']
                                                         .transform('cumsum')),
            cumulative_discounted_costs = lambda df: (df
                                                         .groupby([space_col])['opt_costs_discounted']
                                                         .transform('cumsum')),
            cumulative_benefits = lambda df: (df
                                                         .groupby([space_col])['opt_benefit']
                                                         .transform('cumsum')),
            cumulative_costs = lambda df: (df
                                                         .groupby([space_col])['opt_costs']
                                                         .transform('cumsum'))
        )[
            [
                "opt_vals",
                "opt_benefit",
                "opt_costs",
                "opt_costs_discounted",
                "opt_benefit_discounted",
                "cumulative_discounted_benefits",
                "cumulative_discounted_costs",
                "cumulative_benefits",
                "cumulative_costs"
                ]
        ])


        return opt_df

    def write(self, filename:str="model.lp"):
        """Thi function saves model to file

        Args:
            filename (str, optional): name of file. Defaults to "model.lp".
        """
        self.model.write(filename)

    def get_model_results(self)->list:
        """This function returns a list with additional results of the optimization procedure

        Returns:
            list: model's results
        """

        return (
            self.model.objective_value,
            self.model.objective_values,
            self.model.objective_bound,
            self.model.num_solutions,
            self.model.num_cols,
            self.model.num_rows,
            self.model.num_int,
            self.model.num_nz,
            self.status,
        )

__init__(data, sense, solver_name, show_output)

A class that instantiates a mip model.

Parameters:

Name Type Description Default
data pd.DataFrame

The input dataframe that includes benefit/cost data

required
sense str

Whether the model should minimize (MINIMIZE) or maximize (MAXIMIZE)

required
solver_name str

The solver type (CBC or some other mip solver)

required
show_output bool

Whether to show output of model construction

required
Source code in minimod_opt/base/model.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def __init__(self, data:pd.DataFrame, sense:str, solver_name:str, show_output:bool):
    """A class that instantiates a `mip` model.

    Args:
        data (pd.DataFrame): The input dataframe that includes benefit/cost data
        sense (str): Whether the model should minimize (MINIMIZE) or maximize (MAXIMIZE)
        solver_name (str): The solver type (CBC or some other mip solver)
        show_output (bool):  Whether to show output of model construction
    """


    ## Tell the fitter whether to maximize or minimize
    self.model = mip.Model(sense=sense, solver_name=solver_name)

    self._df = data

    self.show_output = show_output

    if self.show_output:
        self.model.verbose = 1
    else:
        self.model.verbose = 0

add_constraint(eq, constraint, way='ge', name='')

This function merges the objective function of the model with its constraint

Parameters:

Name Type Description Default
eq mip.LinExpr

equation defining the objective function

required
constraint mip.LinExpr

equation defining the constraint function

required
way str

whether greater or equal (ge), less or equal(le), or equal(eq). Defaults to "ge".

'ge'
name str

optional name for the constraint. Defaults to "".

''
Source code in minimod_opt/base/model.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
def add_constraint(self, eq:mip.LinExpr, constraint:mip.LinExpr, way:str="ge", name:str=""):
    """This function merges the objective function of the model with its constraint

    Args:
        eq (mip.LinExpr): equation defining the objective function
        constraint (mip.LinExpr):equation defining the constraint function
        way (str, optional): whether greater or equal (ge), less or equal(le), or equal(eq). Defaults to "ge".
        name (str, optional): optional name for the constraint. Defaults to "".
    """

    if isinstance(constraint, pd.Series):
        # Merge equation with constraint
        df = eq.merge(constraint, left_index = True, right_index= True)

        for i, ee, c in df.itertuples():
            if way == "ge":
                self.model += ee >= c, name
            elif way == "le":
                self.model += ee <= c, name
            elif way == "eq":
                self.model += ee == c, name


    else:
        if way == "ge":
            self.model += eq >= constraint, name
        elif way == "le":
            self.model += eq <= constraint, name
        elif way == "eq":
            self.model += eq == constraint, name

add_objective(eq)

Sets the objective function of the problem as a linear expression

Parameters:

Name Type Description Default
eq mip.LinExpr

equation defining the objective function

required
Source code in minimod_opt/base/model.py
291
292
293
294
295
296
297
298
def add_objective(self, eq:mip.LinExpr):
    """Sets the objective function of the problem as a linear expression

    Args:
        eq (mip.LinExpr): equation defining the objective function
    """

    self.model.objective = eq

base_model_create(intervention, space, time, all_time=None, all_space=None, time_subset=None, space_subset=None, strict=False)

A function

Parameters:

Name Type Description Default
intervention str

name of dataframe's column with set of interventions

required
space str

name of dataframe's column with information on regions/locations

required
time str

name of dataframe's column with information on time/years

required
all_time list

list of intervention vehicles that are active during all periods (e.g., cube, oil). Defaults to None.

None
all_space list

list of intervention vehicles that are targeted at a country-wide level (e.g., cube, oil). Defaults to None.

None
time_subset list

list with subset of periods. Defaults to None.

None
space_subset list

list with subset of regions/locations. Defaults to None.

None
strict bool

whether to look for specific intervention names (using DataFrame.isin) or whether to look for a regex (using DataFrame.str.contains). Defaults to False.

False
Source code in minimod_opt/base/model.py
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def base_model_create(
    self,
    intervention:str,
    space:str,
    time:str,
    all_time:list=None,
    all_space:list=None,
    time_subset:list=None,
    space_subset:list=None,
    strict:bool=False,
):
    """A function   

    Args:
        intervention (str): name of dataframe's column with set of interventions
        space (str): name of dataframe's column with information on regions/locations
        time (str): name of dataframe's column with information on time/years
        all_time (list, optional): list of intervention vehicles that are active during all periods (e.g., cube, oil). Defaults to None.
        all_space (list, optional): list of intervention vehicles that are targeted at a country-wide level (e.g., cube, oil). Defaults to None.
        time_subset (list, optional): list with subset of periods. Defaults to None.
        space_subset (list, optional):list with subset of regions/locations. Defaults to None.
        strict (bool, optional): whether to look for specific intervention names (using DataFrame.isin) or whether to look for a regex (using DataFrame.str.contains). Defaults to False.

    """

    ## Now we create the choice variable, x, which is binary and is the size of the dataset.
    ## In this case, it should just be a column vector with the rows equal to the data:

    self._model_var_create()

    ## First add base constraint, which only allows one intervention per time and space
    self._base_constraint(space, time)

    ## Add all_space or all_time constraints if necessary
    if all_time is not None:

        if intervention is None or space is None:
            raise Exception("One of the subset columns were not found")

        self._all_time_constraint(
            strict,
            intervention=intervention,
            space=space,
            time=time,
            subset_names=all_time,
            over=time,
            subset_list=time_subset,
        )

    if all_space is not None:

        if intervention is None or time is None:
            raise Exception("One of the subset columns were not found")

        self._all_space_constraint(
            strict,
            intervention=intervention,
            space=space,
            time=time,
            subset_names=all_space,
            over=space,
            subset_list=space_subset,
        )

get_equation(name=None, show=True)

This function returns a constraint by its name. If no name is specified, returns all constraints

Parameters:

Name Type Description Default
name str

a string corresponding to the name of the constraint. Defaults to None.

None
show bool

whether to return the contraint in string type or not. Defaults to True.

True

Returns:

Type Description

str or mip.LinExpr or mip.Constr: A mip constraint object

Source code in minimod_opt/base/model.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
def get_equation(self, name:str=None, show:bool=True)->str or mip.LinExpr or mip.Constr :
    """This function returns a constraint by its name. If no name is specified, returns all constraints

    Args:
        name (str, optional): a string corresponding to the name of the constraint. Defaults to None.
        show (bool, optional): whether to return the contraint in string type or not. Defaults to True.

    Returns:
        str or mip.LinExpr or mip.Constr: A `mip` constraint object
    """

    if name is None:
        return self.model.constrs
    elif name == 'objective':
        if show:
            return str(self.model.objective)
        else:
            return self.model.objective
    else:
        if show:
            return str(self.model.constr_by_name(name))
        else:
            return self.model.constr_by_name(name)

get_model_results()

This function returns a list with additional results of the optimization procedure

Returns:

Name Type Description
list list

model's results

Source code in minimod_opt/base/model.py
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
def get_model_results(self)->list:
    """This function returns a list with additional results of the optimization procedure

    Returns:
        list: model's results
    """

    return (
        self.model.objective_value,
        self.model.objective_values,
        self.model.objective_bound,
        self.model.num_solutions,
        self.model.num_cols,
        self.model.num_rows,
        self.model.num_int,
        self.model.num_nz,
        self.status,
    )

optimize(**kwargs)

This function conducts the optimization procedure

Parameters:

Name Type Description Default
**kwargs

Other parameters for optimization procedure using `mip.optimize' (max_seconds, max_nodes, max_solutions)

{}
Source code in minimod_opt/base/model.py
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
def optimize(self, **kwargs):
    """This function conducts the optimization procedure 

    Args:
        **kwargs: Other parameters for optimization procedure using `mip.optimize' (max_seconds, max_nodes, max_solutions)
    """

    self.status = None

    if self.model.num_cols == 0:
        raise NoVars("No Variables added to the model")
    if self.model.num_rows == 0:
        raise NoConstraints("No constraints added to the model.")
    try:
        self.model.objective
    except Exception:
        raise NoObjective("No Objective added to the model")

    # Now, allow for arguments to the optimize function to be given:

    max_seconds = kwargs.pop("max_seconds", mip.INF)
    max_nodes = kwargs.pop("max_nodes", mip.INF)
    max_solutions = kwargs.pop("max_solutions", mip.INF)

    if self.show_output:
        self.status = self.model.optimize(max_seconds, max_nodes, max_solutions)
    else:
        with suppress_stdout_stderr():
            self.status = self.model.optimize(max_seconds, max_nodes, max_solutions)
    if self.show_output:
        if self.status == mip.OptimizationStatus.OPTIMAL:
            print("[Note]: Optimal Solution Found")
        elif self.status == mip.OptimizationStatus.FEASIBLE:
            print("[Note]: Feasible Solution Found. This may not be optimal.")
        elif self.status == mip.OptimizationStatus.NO_SOLUTION_FOUND:
            print("[Warning]: No Solution Found")
        elif self.status == mip.OptimizationStatus.INFEASIBLE:
            print("[Warning]: Infeasible Solution Found")

process_results(benefit_col, cost_col, intervention_col, space_col, sol_num=None)

This function creates a dataframe with information on benefits and costs for the optimal interventions

Parameters:

Name Type Description Default
benefit_col str

name of dataframe's column with benefits

required
cost_col str

name of dataframe's column with costs

required
intervention_col str

name of dataframe's column with set of interventions

required
space_col str

name of dataframe's column with information on regions/locations

required
sol_num int

index of solution. Defaults to None.

None

Returns:

Type Description
pd.DataFrame

pd.DataFrame: dataframe with optimal interventions

Source code in minimod_opt/base/model.py
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
def process_results(self, benefit_col:str, cost_col:str, intervention_col:str, space_col:str, sol_num:int = None)->pd.DataFrame:
    """This function creates a dataframe with information on benefits and costs for the optimal interventions

    Args:
        benefit_col (str): name of dataframe's column with benefits
        cost_col (str): name of dataframe's column with costs
        intervention_col (str): name of dataframe's column with set of interventions
        space_col (str): name of dataframe's column with information on regions/locations
        sol_num (int, optional): index of solution. Defaults to None.

    Returns:
        pd.DataFrame: dataframe with optimal interventions
    """


    if isinstance(sol_num, int):
        opt_df = self._df.copy(deep=True).assign(opt_vals=lambda df: df["mip_vars"].apply(lambda y: y.xi(sol_num)))
    else:
        opt_df = self._df.copy(deep=True).assign(
            opt_vals=lambda df: df["mip_vars"].apply(lambda y: y.x))

    opt_df = (opt_df.assign(
        opt_benefit=lambda df: df[benefit_col] * df["opt_vals"],
        opt_costs=lambda df: df[cost_col] * df["opt_vals"],
        opt_costs_discounted=lambda df: df["discounted_costs"] * df["opt_vals"],
        opt_benefit_discounted=lambda df: df["discounted_benefits"]* df["opt_vals"])
              .infer_objects()
              .assign(
        cumulative_discounted_benefits = lambda df: (df
                                                     .groupby([space_col])['opt_benefit_discounted']
                                                     .transform('cumsum')),
        cumulative_discounted_costs = lambda df: (df
                                                     .groupby([space_col])['opt_costs_discounted']
                                                     .transform('cumsum')),
        cumulative_benefits = lambda df: (df
                                                     .groupby([space_col])['opt_benefit']
                                                     .transform('cumsum')),
        cumulative_costs = lambda df: (df
                                                     .groupby([space_col])['opt_costs']
                                                     .transform('cumsum'))
    )[
        [
            "opt_vals",
            "opt_benefit",
            "opt_costs",
            "opt_costs_discounted",
            "opt_benefit_discounted",
            "cumulative_discounted_benefits",
            "cumulative_discounted_costs",
            "cumulative_benefits",
            "cumulative_costs"
            ]
    ])


    return opt_df

write(filename='model.lp')

Thi function saves model to file

Parameters:

Name Type Description Default
filename str

name of file. Defaults to "model.lp".

'model.lp'
Source code in minimod_opt/base/model.py
491
492
493
494
495
496
497
def write(self, filename:str="model.lp"):
    """Thi function saves model to file

    Args:
        filename (str, optional): name of file. Defaults to "model.lp".
    """
    self.model.write(filename)

BaseSolver

Source code in minimod_opt/base/basesolver.py
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
class BaseSolver:


    def __init__(
        self,
        data: pd.DataFrame,
        benefit_col: str = 'benefits',
        cost_col: str = 'costs',
        intervention_col: str = 'intervention',
        space_col: str = 'space',
        time_col: str = 'time',
        interest_rate_cost: float = 0.0,  # Discount factor for costs
        interest_rate_benefit: float = 0.03,  # Discount factor for benefits 
        va_weight: float = 1.0,  # VA Weight
        sense: str = None,  # MIP optimization type (maximization or minimization)
        solver_name: str = mip.CBC,  # Solver for MIP to use
        show_output: bool = True,
        benefit_title: str = "Benefits",
    ):       

        """The base solver for the Optimization. This sets up the basic setup of the model, which includes:
        - data handling
        - BAU constraint creation
        - base model constraint creation

        Args:
                data (pd.DataFrame): dataframe with benefits and cost data.
                benefit_col (str, optional): name of dataframe's column with benefit data. Defaults to 'benefits'.
                cost_col (str, optional): name of dataframe's column with cost data. Defaults to 'costs'.
                intervention_col (str, optional): name of dataframe's column with intervention data. Defaults to 'intervention'.
                space_col (str, optional): name of dataframe's column with space/region data . Defaults to 'space'.
                time_col (str, optional): name of dataframe's column with time period data . Defaults to 'time'.
                interest_rate_cost (float, optional): interest rate of costs. Defaults to 0.0.
                benefit_title (str, optional): title for benefits to use in plots and reports. Defaults to "Benefits".

        ``BaseSolver`` is inherited by ``CostSolver`` and ``BenefitSolver`` to then run optimizations.
        """        

        self.interest_rate_cost = interest_rate_cost
        self.interest_rate_benefit = interest_rate_benefit
        self.va_weight = va_weight
        self.discount_costs = 1 / (1 + self.interest_rate_cost)
        self.discount_benefits = 1 / (1 + self.interest_rate_benefit)
        self.benefit_title = benefit_title

        if sense is not None:
            self.sense = sense
        else:
            raise Exception("No Optimization Method was specified")

        self.solver_name = solver_name
        self.show_output = show_output

        # Process Data

        if self.show_output:
            print("[Note]: Processing Data...")

        self._df = self._process_data(
            data=data,
            intervention=intervention_col,
            space=space_col,
            time=time_col,
            benefits=benefit_col,
            costs=cost_col,
        )


        self.benefit_col = benefit_col
        self.cost_col = cost_col
        self.intervention_col = intervention_col
        self.space_col = space_col
        self.time_col = time_col

        if self.show_output:
            print("[Note]: Creating Base Model with constraints")


        self.minimum_benefit = None
        self.total_funds = None

        self.message = f"""
                MiniMod Nutrition Intervention Tool
                Optimization Method: {str(self.sense)}
                Solver: {str(self.solver_name)},
                Show Output: {self.show_output}

                """

        if self.show_output:
            print(self.message)



    def _discounted_sum_all(self, col_name:str) -> mip.LinExpr:

        """Multiply each ``mip_var`` in the data by benefits or costs (``data``) and then create a ``mip`` expression from it.

        Args:
            col_name (str): name of dataframe's column with benefits or costs data

        Returns:
            mip.LinExpr: ``mip`` Expression
        """    

        eq = (self._df['mip_vars'] * self._df[col_name]).agg(mip.xsum)

        return eq

    def _discounted_sum_over(self, col_name: str, over: str) -> pd.DataFrame :
        """Abstract function used for constructing the objective function and main constraint of the model

        Args:
            col_name (str): name of dataframe's column with benefits or costs data
            over (str): name of dataframe's column with attribute used to group data by (e.g. time)

        Returns:
            (pd.Dataframe): pd.Dataframe with mip variables as observations
        """

        # Merge data with self._df   
        eq = (self._df['mip_vars'] * self._df[col_name]).groupby(over).agg(mip.xsum)

        return eq.to_frame().rename({0 : col_name + '_vars'}, axis=1)


    def _is_dataframe(self, data: Any):
        """Checks if input dataset is a ``pandas.DataFrame``

        Args:
            data (Any): input data

        Raises:
            NotPandasDataframe: Exception if not a ``pandas.DataFrame``
        """    

        if not isinstance(data, pd.DataFrame):
            raise NotPandasDataframe(
                "[Error]: Input data is not a dataframe. Please input a dataframe."
            )


    def _process_data(
        self,
        data: pd.DataFrame = None,
        intervention: str ="intervention",
        space: str = "space",
        time: str = "time",
        benefits: str = "benefits",
        costs: str = "costs",
    ) -> pd.DataFrame :      
        """Processes the input data by creating discounted benefits and costs.

        Args:
            data (pd.DataFrame, optional): raw data to be processed. Defaults to None.
            intervention (str, optional): name of dataframe's column with intervention data. Defaults to "intervention".
            space (str, optional): name of dataframe's column with space/region data. Defaults to "space".
            time (str, optional): name of dataframe's column with time period data. Defaults to "time".
            benefits (str, optional): name of dataframe's column with benefits data. Defaults to "benefits".
            costs (str, optional): name of dataframe's column with cost data. Defaults to "costs".

        Returns:
            (pd.DataFrame): dataframe ready to be used in the problem


        |k     | j   |t   | benefits   | costs |
        |------|-----|----|------------|-------|
        |maize |north|0   | 100        | 10    |
        |maize |south|0   | 50         | 20    |
        |maize |east |0   | 30         |30     |
        |maize |west |0   | 20         |40     |

        """

        ## First do some sanity checks
        if data is None:
            raise MissingData("No data specified.")

        # Check if dataframe
        self._is_dataframe(data)

        df_aux = (
            data.reset_index()
            .assign(
                time_col=lambda df: df[time].astype(int),
                time_rank=lambda df: (
                    df[time].rank(numeric_only=True, method="dense") - 1
                ).astype(int),
                time_discount_costs=lambda df: self.discount_costs ** df["time_rank"],
                time_discount_benefits=lambda df: self.discount_benefits
                ** df["time_rank"],
                discounted_costs=lambda df: df["time_discount_costs"] * df[costs],
                discounted_benefits=lambda df: df["time_discount_benefits"]*df[benefits]
            )
        )

        df_aux[intervention] = df_aux[intervention].str.lstrip().str.rstrip()

        df = (
            df_aux
            .set_index([intervention, space, time])
            .sort_index(level=(intervention, space, time))
        )

        return df

    def _constraint(self):
        """This function defines the constraints for the mips model.
        To be overridden by BenefitSolver and CostSolver classes.
        """
        self.constraint_called = 0

    def _objective(self):
        """This function defines the objective function for a model.
        To be overridden by BenefitSolver and CostSolver classes.
        """
        pass


    def _fit(self, **kwargs) -> str:
        """Fits data to model. The instantiation of the class creates the base model. Uses ``mip.optimize`` to find the optimal point.

        Args:
            *kwargs: Other parameters to send to mip.optimize

        Returns:
            str: return self
        """


        if self.show_output:
            print("[Note]: Optimizing...")

        self.model.optimize(**kwargs)  

        (self.objective_value,
         self.objective_values, 
         self.objective_bound, 
         self.num_solutions, 
         self.num_cols, 
         self.num_rows, 
         self.num_int, 
         self.num_nz, 
         self.status) = self.model.get_model_results()

        return self

    def write(self, filename:str="model.lp"):
        """Save model to file

        Args:
            filename (str, optional):name of the file. Defaults to "model.lp".
        """

        self.model.write(filename)

    def process_results(self, sol_num:int=None):
        """Processes results of optimization to be used in visualization and reporting functions

        Args:
            sol_num (int, optional): index of solution. Defaults to None.
        """

        self.opt_df = self.model.process_results(self.benefit_col, 
                                            self.cost_col, 
                                            self.intervention_col,
                                            self.space_col,
                                            sol_num=sol_num)


    def report(self, sol_num:int=None, quiet:bool=False) -> str:
        """Prints out a report of optimal model parameters and useful statistics.

        Args:
            sol_num (int, optional): index of solution to be displayed. Defaults to None.
            quiet (bool, optional): whether we want the report printed out or not. Defaults to False.
        """

        self.opt_df = self.model.process_results(self.benefit_col, 
                                            self.cost_col, 
                                            self.intervention_col,
                                            self.space_col,
                                            sol_num=sol_num)

        if quiet:
            return
        header = [
            ('MiniMod Solver Results', ""),
            ("Method:" , str(self.sense)),
            ("Solver:", str(self.solver_name)),
            ("Optimization Status:", str(self.status)),
            ("Number of Solutions Found:", str(self.num_solutions))

        ]

        features = [
            ("No. of Variables:", str(self.num_cols)),
            ("No. of Integer Variables:", str(self.num_int)),
            ("No. of Constraints", str(self.num_rows)),
            ("No. of Non-zeros in Constr.", str(self.num_nz))
        ]

        s = OptimizationSummary(self)

        s.print_generic(header, features)

        print("Interventions Chosen:")

    @property
    def optimal_interventions(self) -> list:
        opt_intervention = (
            self.opt_df
            .loc[lambda df: df['opt_vals']>0]
            .index
            .get_level_values(level=self.intervention_col)
            .unique()
            .tolist()
        )
        """Outputs the unique set of optimal interventions as a list

        Returns:
            list: The list of optimal interventions
        """

        return opt_intervention

    @property
    def _intervention_list_space_time(self) -> pd.DataFrame:
        """Returns a data frame with multindex (space_col, time_col) where each row is the optimal intervention.

        Returns:
            pd.DataFrame: A dataframe where each row is the optimal intervention for each time period and space
        """

        df = (
            self.opt_df['opt_vals']
            .reset_index(level=self.intervention_col)
            .assign(int_appeared= lambda df: df[self.intervention_col]*df['opt_vals'].astype(int))
            .groupby([self.space_col, self.time_col])
            ['int_appeared']
            .agg(set)
            .str.join('')
        )

        return df

    @property
    def bau_list(self) -> pd.DataFrame:
        """Returns a dataframe with the name of the bau intervention. Mostly done for compatibility with other methods.

        Returns:
            pd.DataFrame: dataframe with the name of the bau intervention
        """

        df = (
            self.bau_df
            .reset_index(level=self.intervention_col)
            .rename({self.intervention_col : 'int_appeared'}, axis=1)
            ['int_appeared']
        )

        return df


    def plot_time(self, 
                  fig: mpl.figure = None, 
                  ax: mpl.axis= None,
                  save: str = None,
                  cumulative: bool = False,
                  cumulative_discount: bool = False) -> mpl.figure:
        """Plots optimal benefits and costs across time after model optimization

        Args:
            fig (matplotlib.figure, optional): matplotlib figure. Defaults to None.
            ax (matplotlib.axis, optional): matplotlib axis to use. Defaults to None.
            save (str, optional): path to save the figure. Defaults to None.
            cumulative (bool, optional): whether to plot cumulative benefits or costs. Defaults to False.
            cumulative_discount (bool, optional): whether to plot cumulative benefits or costs, discounted. Defaults to False.

        Returns:
            matplotlib.figure: figure with optimal benefits and cost across time
        """

        p = Plotter(self)

        if cumulative:
            return p._plot_lines(to_plot = ['cumulative_benefits', 'cumulative_costs'],
                    title= "Optima over Time",
                    xlabel = 'Time',
                    ylabel = self.benefit_title,
                    twin =True,
                    twin_ylabel= "Currency",
                    save = save,
                    legend = ['Cumm. ' + self.benefit_title,
                            'Cumm. Costs'],
                    figure=fig,
                    axis=ax)
        elif cumulative_discount:
            return p._plot_lines(to_plot = ['cumulative_discounted_benefits', 'cumulative_discounted_costs'],
                    title= "Optima over Time",
                    xlabel = 'Time',
                    ylabel = self.benefit_title,
                    twin =True,
                    twin_ylabel= "Currency",
                    save = save,
                    legend = ['Cumm. Dis. '+ self.benefit_title,
                            'Cumm. Dis. Costs'],
                    figure=fig,
                    axis=ax)
        else:
            return p._plot_lines(to_plot = ['opt_benefit', 'opt_costs'],
                                title= "Optima over Time",
                                xlabel = 'Time',
                                ylabel = self.benefit_title,
                                twin =True,
                                twin_ylabel= "Currency",
                                save = save,
                                legend = ['Optimal ' + self.benefit_title,
                                        'Optimal Costs'],
                                figure=fig,
                                axis=ax)

    def plot_bau_time(self,
                      opt_variable: str = 'b',
                      fig: mpl.figure = None,
                      ax: mpl.axis = None,
                      save: str = None):
        """Plots benefits and costs of optimal and benchark interventions across time 

        Args:
            opt_variable (str, optional): optimal variable to be plotted, where
                b = optimal benefits
                c = 'optimal costs
                cdb = cumulative discounted benefits
                cdc = cumulative discounted costs
                cb = cumulative benefits
                cc = cumulative costs
            Defaults to 'b'.
            fig (matplotlib.figure, optional): matplotlib figure. Defaults to None.
            ax (matplotlib.axis, optional):matplotlib axis to use. Defaults to None.
            save (str, optional): path to save the figure. Defaults to None.

        Raises:
            Exception: not one of the allowed variables for map plotting
        """

        if ax is None:
            fig, ax = plt.subplots()

        p = Plotter(self)

        if opt_variable == 'b':
            opt = 'opt_benefit'
            bau_col = self.benefit_col
            title = "Optimal " + self.benefit_title + " vs. BAU"
        elif opt_variable == 'c':
            opt = 'opt_costs'
            bau_col = self.cost_col
            title = "Optimal Costs vs. BAU"
        elif opt_variable == 'cdb':
            opt = 'cumulative_discounted_benefits'
            bau_col = 'discounted_benefits'
            title = 'Cumulative Discounted ' + self.benefit_title
        elif opt_variable == 'cdc':
            opt = 'cumulative_discounted_costs'
            bau_col = 'discounted_costs'
            title = 'Cumulative Discounted Costs'
        elif opt_variable == 'cb':
            opt = 'cumulative_benefits'
            bau_col = self.benefit_col
            title = 'Cumulative ' + self.benefit_title      
        elif opt_variable == 'cc':
            opt = 'cumulative_costs'
            bau_col = self.cost_col
            title = 'Cumulative Costs'
        else:
            raise Exception("Not one of the allowed variables for map plotting. Try again.")

        if opt_variable in ['cdb', 'cdc', 'cb', 'cc']:

            bench_df = (
                self.bau_df
                .groupby([self.time_col])
                .sum().cumsum()
                .assign(bench_col = lambda df: df[bau_col])
                )

        else:
            bench_df = (
                self.bau_df
                .assign(bench_col = lambda df: df[bau_col])
                .groupby([self.time_col])
                .sum()
                        )

        p._plot_lines(to_plot = opt,
                    title= title,
                    xlabel = 'Time',
                    figure=fig,
                    axis=ax)

        bench_df['bench_col'].plot(ax=ax)

        ax.legend(['Optimal', 'BAU'])
        ax.set_xlabel('Time')

        if save is not None:
            plt.savefig(save)



    def plot_opt_val_hist(self, 
                          fig: mpl.figure = None, 
                          ax: mpl.axis = None, 
                          save: str = None) -> mpl.figure:
        """A histogram of the optimally chosen interventions

        Args:
            fig (matplotlib.figure, optional): figure instance to use. Defaults to None.
            ax (matplotlib.axis, optional): axis instance to use. Defaults to None.
            save (str, optional): path to save the figure. Defaults to None.

        Returns:
            matplotlib.figure: histogram figure
        """      

        p = Plotter(self)

        return p._plot_hist(to_plot = 'opt_vals',
                            title = "Optimal Choices",
                            xlabel = "Time",
                            ylabel= "",
                            figure = fig,
                            axis = ax,
                            save = save)  

    def plot_chloropleth(self,
                         intervention: str = None,
                         time: Union[int,list] = None,
                         optimum_interest: str = 'b',
                         map_df: gpd.GeoDataFrame  = None,
                         merge_key: Union[str,list] = None,
                         intervention_bubbles: bool = False,
                         intervention_bubble_names: Union[str,list] = None,
                         save: str = None):
        """Creates a chloropleth map of the specified intervention and time period for the optimal variable. 
        If more than one intervention is specified, then aggregates them. If more than one time period is specified, then creates a subplots of len(time) and show each.

        Args:
            intervention (str, optional): intervention to use. Defaults to None.
            time (Union[int,list], optional): time periods to plot. Defaults to None.
            optimum_interest (str, optional): optimal variable to use (Options include: 'b' for optimal benefits, 'c' for optimal costs, and 'v' for optimal variable). Defaults to 'b'.
            map_df (geopandas.GeoDataFrame, optional): geopandas dataframe with geometry information. Defaults to None.
            merge_key (Union[str,list], optional): column to merge geo-dataframe. Defaults to None.
            intervention_bubbles (bool, optional): whether to show optimal intervention names in map. Defaults to False.
            intervention_bubble_names (Union[str,list], optional): key to merge on to geo dataframe. Defaults to None.
            save (str, optional): path to save map. Defaults to None.

        Raises:
            Exception: Not one of the allowed variables for map plotting
        """


        if intervention is None:
            intervention = self.optimal_interventions

        p = Plotter(self)

        if optimum_interest == 'b':
            opt = 'opt_benefit'
            title = self.benefit_title
        elif optimum_interest == 'c':
            opt = 'opt_costs'
            title = "Optimal Costs"
        elif optimum_interest == 'v':
            opt = 'opt_vals'
            title = "Optimal Interventions"
        elif optimum_interest == 'cdb':
            opt = 'cumulative_discounted_benefits'
            title = 'Cumulative Discounted ' + self.benefit_title
        elif optimum_interest == 'cdc':
            opt = 'cumulative_discounted_costs'
            title = 'Cumulative Discounted Costs'
        elif optimum_interest == 'cb':
            opt = 'cumulative_benefits'
            title = 'Cumulative ' + self.benefit_title      
        elif optimum_interest == 'cc':
            opt = 'cumulative_costs'
            title = 'Cumulative Costs'
        else:
            raise Exception("Not one of the allowed variables for map plotting. Try again.")


        plotter = p._plot_chloropleth_getter(time = time)
        plot = plotter(data = self.opt_df,
                                          intervention = intervention,
                                            time = time,
                                            optimum_interest=opt,
                                            map_df = map_df,
                                            merge_key=merge_key,
                                            aggfunc = 'sum',
                                            title = title,
                                            intervention_bubbles = intervention_bubbles,
                                            intervention_bubble_names = intervention_bubble_names,
                                            save = save)
        # return plot


    def plot_grouped_interventions(self, 
                                    data_of_interest: str = 'benefits', 
                                    title: str = None,
                                    intervention_subset: Union[str,list] = slice(None),
                                    save: str = None):
        """Shows Optimal level of benefits or costs in a grouped bar plots for every optimally chosen variable across regions.

        Args:
            data_of_interest (str, optional): variable to show. Defaults to 'benefits'.
            title (str, optional):title for resulting plot. Defaults to None.
            intervention_subset (Union[str,list], optional): subset of interventions to show on bar plot. Defaults to slice(None).
            save (str, optional): path to save the figure. Defaults to None.
        """


        p = Plotter(self)

        if data_of_interest == 'benefits':
            col_of_interest = 'opt_benefit'
        elif data_of_interest == 'costs':
            col_of_interest = 'opt_costs'

        p._plot_grouped_bar(intervention_col= self.intervention_col,
                            space_col = self.space_col,
                            col_of_interest= col_of_interest,
                            ylabel = "Optimal Level",
                            intervention_subset= intervention_subset,
                            save = save)



    def plot_map_benchmark(self,
                           intervention: list = None,
                           time: list = None,
                           optimum_interest: str = 'b',
                           bench_intervention: list = None,
                           map_df: gpd.GeoDataFrame = None,
                           merge_key: Union[str,list] = None,
                           save: str = None,
                           intervention_in_title: bool = True,
                           intervention_bubbles: bool = False,
                           intervention_bubble_names: Union[str,list] = None,
                           millions: bool = True,
                           bau_intervention_bubble_names: Union[str,list] = None
                           ):
        """Maps the optimal level on a map against a benchmark, optionally the BAU level chosen from ``minimum_benefit`` or ``total_funds``.

        Args:
            intervention (list, optional): interventions to map. Defaults to None.
            time (list, optional): time periods to map. Defaults to None.
            optimum_interest (str, optional):  optimal value to use. Options include 'b' (benefits), 'c' (costs), 'v' (variables). Defaults to 'b'.
            bench_intervention (list, optional): interventions to use for benchmark. Defaults to None.
            map_df (geopandas.GeoDataFrame, optional):  geo dataframe with geometry data. Defaults to None.
            merge_key (Union[str,list], optional): key to merge data from opt_df to geo dataframe. Defaults to None.
            save (str, optional): path to save the map. Defaults to None.
            intervention_in_title (bool, optional): True if intervention name will be included in the title of the figure. Defaults to True.
            intervention_bubbles (bool, optional): True if intervention bubbles. Defaults to False.
            intervention_bubble_names (Union[str,list], optional): names of intervention bubbles. Defaults to None.
            millions (bool, optional): True if values displayed in millions. Defaults to True.
            bau_intervention_bubble_names (Union[str,list], optional): name for bau intervention bubble. Defaults to None.

        """

        if intervention is None:
            intervention = self.optimal_interventions   

        if figsize is not None:   
            fig = plt.figure(figsize=figsize)
        else:
            fig = plt.figure(figsize=(10,12))

        gs = gridspec.GridSpec(2,2, height_ratios = [6,1])
        optimal = fig.add_subplot(gs[0,0])
        bench = fig.add_subplot(gs[0,1])
        cbar = fig.add_subplot(gs[1,:])

        p = Plotter(self)

        if optimum_interest == 'b':
            opt = 'opt_benefit'
            bench_col = self.benefit_col
            title = self.benefit_title
        elif optimum_interest == 'c':
            opt = 'opt_costs'
            bench_col = self.cost_col
            title = "Costs"
        elif optimum_interest == 'v':
            opt = 'opt_vals'
            title = "Interventions"
        elif optimum_interest == 'cdb':
            opt =  'cumulative_discounted_benefits'
            bench_col = 'discounted_benefits'
            title = 'Cumulative Discounted ' + self.benefit_title
        elif optimum_interest == 'cdc':
            opt =  'cumulative_discounted_costs'
            title = 'Cumulative Discounted Costs'
            bench_col = 'discounted_costs'
        elif optimum_interest == 'cb':
            opt =  'cumulative_benefits'
            title = 'Cumulative ' + self.benefit_title   
            bench_col = self.benefit_col   
        elif optimum_interest == 'cc':
            opt =  'cumulative_costs'
            title = 'Cumulative Costs'
            bench_col = self.cost_col
        else:
            raise Exception("Not one of the allowed variables for map plotting. Try again.")

        if bench_intervention is None:
            bench_intervention = self.minimum_benefit

        if merge_key is None:
            merge_key = self.space_col

        if optimum_interest in ['cdb', 'cdc', 'cb', 'cc']:

            bench_df = self.bau_df.assign(bench_col = lambda df: (df
                                                            .groupby([self.intervention_col, 
                                                                    self.space_col])
                                                            [bench_col]
                                                            .transform('cumsum')))

        else:
            bench_df = self.bau_df.assign(bench_col = lambda df: df[bench_col])

        y = 1.05

        if intervention_in_title:
            title = title + f"\nOptimal Interventions:\n{', '.join(intervention)}"
            y = y + .05

        fig.suptitle(title, y=y)
        plotter = p._plot_chloropleth_getter(time)

        # Get min and max values for color map
        opt_max = self.opt_df[opt].max()
        opt_min = self.opt_df[opt].min()

        bench_max = bench_df['bench_col'].max()
        bench_min = bench_df['bench_col'].min()

        vmax = max(opt_max, bench_max)
        vmin = min(opt_min, bench_min)

        if intervention_bubbles:
            bau_intervention_bubbles = 'bau'
        else:
            bau_intervention_bubbles = False


        plotter(data = self.opt_df,
                    intervention = intervention,
                    time = time,
                    optimum_interest=opt,
                    map_df = map_df,
                    merge_key=merge_key,
                    aggfunc = 'sum',
                    ax = optimal,
                    cax = cbar,
                    title = "Optimal Scenario",
                    intervention_bubbles = intervention_bubbles,
                    intervention_bubble_names = intervention_bubble_names,
                    vmin = vmin,
                    vmax = vmax,
                    legend_kwds = {'orientation' : 'horizontal'})

        plotter(data = bench_df,
                        intervention = bench_intervention,
                        time = time,
                        optimum_interest= 'bench_col',
                        map_df = map_df,
                        merge_key=merge_key,
                        aggfunc = 'sum',
                        ax = bench,
                        show_legend = False,
                        title = f"BAU* Scenario",
                         vmin = vmin,
                        vmax = vmax,
                        intervention_bubbles = bau_intervention_bubbles,
                        intervention_bubble_names = bau_intervention_bubble_names)

        plt.tight_layout()

        fig_text = 'Note: Colors describe ' + title

        if millions:
            fig_text = fig_text + ' (in millions)'

        # if intervention_bubble_names:
        #     fig_text = fig_text + '\nBAU* scenario made up of ' + ', '.join(intervention_bubble_names)

        fig.text(0.5,-.05, fig_text, ha='center')

        if save is not None:
            plt.savefig(save, dpi = p.dpi, bbox_inches="tight")

    @classmethod  
    def supply_curve(cls, data, 
                    full_population,
                    bau,
                    all_space,
                    all_time,
                    time_subset,
                    benefit_col='effective_coverage',
                    cost_col='cost',
                    intervention_col='intervention',
                    space_col='space',
                    time_col='time',
                    ec_range=None,
                    above_ul = False,
                    above_ul_col = None,
                    **kwargs): 

        if ec_range is None:
            ec_range = np.arange(.1,1,.1)

        if above_ul and above_ul_col is None:
            above_ul_col = 'above_ul'


        ratio_to_constraint = lambda ratio: ratio*full_population

        model_dict = {}

        for _, benefit_constraint in enumerate([bau] + list(ec_range)):

            if isinstance(benefit_constraint, str):
                minimum_benefit = benefit_constraint
            else:
                minimum_benefit = ratio_to_constraint(benefit_constraint)

            c = cls(minimum_benefit = minimum_benefit,
                        data = data, 
                        benefit_col = benefit_col,
                        cost_col = cost_col,
                        intervention_col = intervention_col,
                        space_col = space_col,
                        time_col = time_col,
                        all_space =all_space, 
                        all_time = all_time,
                        time_subset = time_subset,
                        **kwargs)

            opt = c.fit()

            model_dict[benefit_constraint] = opt

        results_dict = {'benefit' : [],
                        'opt_benefits' : [],
                        'opt_costs' : [],
                        'opt_interventions' : [],
                        'convergence' : [],
                        'vas_regions' : []}
        if above_ul:
            results_dict['opt_above_ul'] = []
            data = data.set_index([intervention_col,space_col,time_col])

        for benefit_constraint, model in model_dict.items():

            model.report(quiet=True)
            results_dict['benefit'].append(benefit_constraint)
            results_dict['opt_benefits'].append(model.opt_df.opt_benefit_discounted.sum())
            results_dict['opt_costs'].append(model.opt_df.opt_costs_discounted.sum())
            results_dict['opt_interventions'].append(model.optimal_interventions)
            results_dict['convergence'].append(model.status)
            results_dict['vas_regions'].append(model.opt_df
                                               .query("opt_vals > 0")
                                               .query("index.get_level_values('intervention').str.contains('vas', case=False)")
                                               .index.get_level_values('region').unique().values.tolist())

            if above_ul:
                above_ul_df = (
                        data[above_ul_col]
                        # .reset_index()
                        # # .assign(intervention = lambda df: df[intervention_col].str.lower())
                        # .set_index([intervention_col, space_col, time_col])
                        )

                opt_above_ul = (model.opt_df['opt_vals'] * above_ul_df).sum()

                results_dict['opt_above_ul'].append(opt_above_ul)

        return SupplyCurve(pd.DataFrame(results_dict, index=[results_dict['opt_benefits'][0]/full_population] + list(ec_range)) 
                           , full_population=full_population,
                           bau=bau,
                           data=data,
                           ec_range=ec_range,
                           intervention_col = intervention_col,
                           space_col=space_col,
                           time_col = time_col,
                           cost_col=cost_col,
                           benefit_col=benefit_col)        


    @classmethod      
    def plot_supply_curve(cls, 
                        supply_curve: SupplyCurve = None,
                          data: DataFrame = None, 
                    full_population: Union[int, float] = None,
                    bau: str=None,
                    all_space: List[float]=None,
                    all_time=None,
                    time_subset=None,
                    benefit_col='effective_coverage',
                    cost_col='cost',
                    intervention_col='intervention',
                    space_col='space',
                    time_col='time',
                    ec_range=None,
                    above_ul = False,
                    above_ul_col = None,
                    ec_thousands = 1_000,
                    ul_thousands = 1_000,
                    save=None,
                    subplot_multiple=10,
                    **kwargs):

        if supply_curve is None:
            supply_curve = cls.supply_curve(
                        data=data, 
                        full_population=full_population,
                        bau=bau,
                        all_space=all_space,
                        all_time=all_time,
                        time_subset=time_subset,
                        benefit_col=benefit_col,
                        cost_col=cost_col,
                        intervention_col=intervention_col,
                        space_col=space_col,
                        time_col=time_col,
                        ec_range=ec_range,
                        above_ul = above_ul,
                        above_ul_col=above_ul_col
                        **kwargs
                        )

        N_ec = len(supply_curve.ec_range)
        full_population = supply_curve.full_population
        bau = supply_curve.bau
        data=supply_curve.data
        sc = supply_curve.supply_curve # Now that we have all info. make `supply_curve` just the dataframe

        # make nan of infeasible solutions
        sc = sc.replace(0, np.nan)

        only_bau_opt = sc.query("benefit == @bau")

        # # get places where interventions change
        # transitions = supply_curve[~(supply_curve['opt_interventions'] == supply_curve['opt_interventions'].shift(-1))]

        def start_from_bau(df):
            df = df.loc[lambda df: df.index >= only_bau_opt.index.values[0]]
            if df.empty:
                raise SupplyCurveTransitionException("All transitions less than BAU. Try increasing the number of points in ec_range")

            return df


        # Now get additions of interventions by converting to set and doing difference
        sc = (
            sc
            .dropna()
            .assign(opt_interventions = lambda df: df['opt_interventions'].apply(lambda x: [i.split(' + ') for i in x]))
            .assign(opt_interventions = lambda df: df['opt_interventions'].apply(lambda x: reduce(lambda y, z: y + z, x)))
            .assign(opt_interventions = lambda df: df['opt_interventions'].apply(lambda x: set(x)))
            .assign(int_transitions_lag = lambda df: df['opt_interventions'].shift(-1))
            .dropna()
            .assign(transitions_plus = lambda df: df.apply(lambda col: col['int_transitions_lag'].difference(col['opt_interventions']), axis=1).shift(1).fillna(df['opt_interventions']))
            .assign(transitions_minus = lambda df: df.apply(lambda col: col['opt_interventions'].difference(col['int_transitions_lag']), axis=1).shift(1).fillna(df['opt_interventions']))
            .query("benefit != @bau")
            # .pipe(start_from_bau)
            )

        if above_ul:
            subplot_col = 2
        else:
            subplot_col = 1

        with plt.style.context('seaborn-whitegrid'):
            fig, ax = plt.subplots(subplot_col+1, 1, figsize=(subplot_multiple*subplot_col,12))


            if above_ul:
                ax0 = ax[0]
                ax1 = ax[1]
                ax_region=ax[2]
            else:
                ax0 = ax[0]
                ax_region=ax[1]

            sc['opt_costs'].plot(ax=ax0)

            ax0.set_xlabel('Effective Coverage (%)')

            ax0.set_xticks(sc.index.tolist())

            ax0.set_xticklabels([f"{x*100:.0f}" for x in sc.index.tolist()])

            ax0.ticklabel_format(axis='y', useMathText=True)

            ax0.yaxis.set_major_formatter(tick.FuncFormatter(lambda y, _: f"{y/ec_thousands:,.0f}"))

            ax0.set_title(f'Total Cost (x {ec_thousands:,.0f})')

            if bau is not None:
                if data is None:
                    raise Exception("If `bau` is specified, `data` must also be specified")

                if len(data.index.names) == 1:
                    data = data.set_index([supply_curve.intervention_col,
                                           supply_curve.space_col,
                                           supply_curve.time_col])

                bau_ec, bau_costs = BAUConstraintCreator().bau_df(data, bau, [supply_curve.benefit_col,
                                                                              supply_curve.cost_col]).sum()

                ax0.scatter(bau_ec/full_population, bau_costs, color='tab:green', marker='s')
                ax0.annotate("BAU", (bau_ec/full_population, bau_costs), xytext=(5, 5),  
                            textcoords="offset pixels", color='black')

            opt_b, opt_c = only_bau_opt[['opt_benefits', 'opt_costs']].values.tolist()[0]

            ax0.annotate("Optimum", (opt_b/full_population, opt_c), xytext=(5, -10),  
                        textcoords="offset pixels", color='black')
            ax0.scatter(opt_b/full_population, opt_c,  color='tab:orange', marker="s")

            if above_ul:
                try:
                    sc[above_ul_col]
                except KeyError:
                    raise Exception(f"No above ul in the data")
                # Now get above_ul
                sc['opt_above_ul'].plot(ax=ax1, color='tab:red')
                ax1.yaxis.set_major_formatter(tick.FuncFormatter(lambda y, _: f"{y/ul_thousands:,.0f}"))
                ax1.set_title(f'Population Above UL (x {ul_thousands:,.0f})')
                ax1.set_xticks(sc.index.tolist())
                ax1.set_xticklabels([f"{x*100:.0f}" for x in sc.index.tolist()])
                ax1.set_xlabel('Effective Coverage (%)')

            def message_writer(x):
                if len(x['transitions_plus']) != 0 and len(x['transitions_minus'])!=0:
                    message= "+ " + ', '.join(x['transitions_plus']) +  " - " + ", ".join(x['transitions_minus'])
                    message = '\n'.join(textwrap.wrap(message, width=50))

                    # ns_needed = len(message)//25

                    # # for i in range(ns_needed):
                    # #     message = message[i*25:i+25] + r'-len\n' + message[25+1+i:]

                    return message

            # print(sc)


            (
                sc['vas_regions']
                .explode()
                .to_frame()
                .assign(yes=lambda df: \
                    (~df['vas_regions'].isnull())
                    .astype(int))
                .set_index('vas_regions', 
                           append=True)
                .unstack()
                # .drop(columns=('yes', pd.NA))
                .plot.bar(stacked=True, legend=False, 
                          ax=ax_region, cmap='tab20')
                )

            # ax_region.set_xticks(sc.index.tolist())
            ax_region.set_xticklabels([f"{x*100:.0f}" for x in sc.index.tolist()],
                                      rotation=0)
            ax_region.set_xlabel('Effective Coverage (%)')
            ax_region.set_yticklabels([])
            ax_region.set_title("VAS Regions")

            texts = (
                sc
                .assign(message = lambda df: df.apply(lambda x: message_writer(x), axis=1))
                .apply(lambda df: ax0.text(df.name+.01, df['opt_costs'], 
                                                s=df['message'],
                                                color='black', wrap=True), axis=1) 
                .values.tolist()
                )   

            # adjust_text(texts, arrowprops=dict(arrowstyle='->', color='green'))

            figtext = f"Note: BAU refers to a nutritional intervention of {bau.title()}." \
            f" Optimum solution consists of {', '.join(only_bau_opt['opt_interventions'].values[0])}." \
            " Vitamin A Supplementation taking place at various level of effective coverage in: " \
                           f"{', '.join(list(set(np.concatenate(sc['vas_regions'].values))))}"

            txt = fig.text(.05, -.1, s='\n'.join(textwrap.wrap(figtext, width=100)))

            handles, labels = ax_region.get_legend_handles_labels()

            new_labels = [i.split(',')[1].replace(')', '').strip() for i in labels]
            plt.legend(handles, new_labels, ncol=4, loc='lower center', 
                       bbox_to_anchor = (.5,-.6),
                       title='Regions')                 

            plt.tight_layout()

            if save is not None:
                plt.savefig(save, dpi=300, bbox_inches='tight')

        return ax

bau_list: pd.DataFrame property

Returns a dataframe with the name of the bau intervention. Mostly done for compatibility with other methods.

Returns:

Type Description
pd.DataFrame

pd.DataFrame: dataframe with the name of the bau intervention

__init__(data, benefit_col='benefits', cost_col='costs', intervention_col='intervention', space_col='space', time_col='time', interest_rate_cost=0.0, interest_rate_benefit=0.03, va_weight=1.0, sense=None, solver_name=mip.CBC, show_output=True, benefit_title='Benefits')

The base solver for the Optimization. This sets up the basic setup of the model, which includes: - data handling - BAU constraint creation - base model constraint creation

Parameters:

Name Type Description Default
data pd.DataFrame

dataframe with benefits and cost data.

required
benefit_col str

name of dataframe's column with benefit data. Defaults to 'benefits'.

'benefits'
cost_col str

name of dataframe's column with cost data. Defaults to 'costs'.

'costs'
intervention_col str

name of dataframe's column with intervention data. Defaults to 'intervention'.

'intervention'
space_col str

name of dataframe's column with space/region data . Defaults to 'space'.

'space'
time_col str

name of dataframe's column with time period data . Defaults to 'time'.

'time'
interest_rate_cost float

interest rate of costs. Defaults to 0.0.

0.0
benefit_title str

title for benefits to use in plots and reports. Defaults to "Benefits".

'Benefits'

BaseSolver is inherited by CostSolver and BenefitSolver to then run optimizations.

Source code in minimod_opt/base/basesolver.py
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
def __init__(
    self,
    data: pd.DataFrame,
    benefit_col: str = 'benefits',
    cost_col: str = 'costs',
    intervention_col: str = 'intervention',
    space_col: str = 'space',
    time_col: str = 'time',
    interest_rate_cost: float = 0.0,  # Discount factor for costs
    interest_rate_benefit: float = 0.03,  # Discount factor for benefits 
    va_weight: float = 1.0,  # VA Weight
    sense: str = None,  # MIP optimization type (maximization or minimization)
    solver_name: str = mip.CBC,  # Solver for MIP to use
    show_output: bool = True,
    benefit_title: str = "Benefits",
):       

    """The base solver for the Optimization. This sets up the basic setup of the model, which includes:
    - data handling
    - BAU constraint creation
    - base model constraint creation

    Args:
            data (pd.DataFrame): dataframe with benefits and cost data.
            benefit_col (str, optional): name of dataframe's column with benefit data. Defaults to 'benefits'.
            cost_col (str, optional): name of dataframe's column with cost data. Defaults to 'costs'.
            intervention_col (str, optional): name of dataframe's column with intervention data. Defaults to 'intervention'.
            space_col (str, optional): name of dataframe's column with space/region data . Defaults to 'space'.
            time_col (str, optional): name of dataframe's column with time period data . Defaults to 'time'.
            interest_rate_cost (float, optional): interest rate of costs. Defaults to 0.0.
            benefit_title (str, optional): title for benefits to use in plots and reports. Defaults to "Benefits".

    ``BaseSolver`` is inherited by ``CostSolver`` and ``BenefitSolver`` to then run optimizations.
    """        

    self.interest_rate_cost = interest_rate_cost
    self.interest_rate_benefit = interest_rate_benefit
    self.va_weight = va_weight
    self.discount_costs = 1 / (1 + self.interest_rate_cost)
    self.discount_benefits = 1 / (1 + self.interest_rate_benefit)
    self.benefit_title = benefit_title

    if sense is not None:
        self.sense = sense
    else:
        raise Exception("No Optimization Method was specified")

    self.solver_name = solver_name
    self.show_output = show_output

    # Process Data

    if self.show_output:
        print("[Note]: Processing Data...")

    self._df = self._process_data(
        data=data,
        intervention=intervention_col,
        space=space_col,
        time=time_col,
        benefits=benefit_col,
        costs=cost_col,
    )


    self.benefit_col = benefit_col
    self.cost_col = cost_col
    self.intervention_col = intervention_col
    self.space_col = space_col
    self.time_col = time_col

    if self.show_output:
        print("[Note]: Creating Base Model with constraints")


    self.minimum_benefit = None
    self.total_funds = None

    self.message = f"""
            MiniMod Nutrition Intervention Tool
            Optimization Method: {str(self.sense)}
            Solver: {str(self.solver_name)},
            Show Output: {self.show_output}

            """

    if self.show_output:
        print(self.message)

plot_bau_time(opt_variable='b', fig=None, ax=None, save=None)

Plots benefits and costs of optimal and benchark interventions across time

Parameters:

Name Type Description Default
opt_variable str

optimal variable to be plotted, where b = optimal benefits c = 'optimal costs cdb = cumulative discounted benefits cdc = cumulative discounted costs cb = cumulative benefits cc = cumulative costs

'b'
fig matplotlib.figure

matplotlib figure. Defaults to None.

None
ax matplotlib.axis

matplotlib axis to use. Defaults to None.

None
save str

path to save the figure. Defaults to None.

None

Raises:

Type Description
Exception

not one of the allowed variables for map plotting

Source code in minimod_opt/base/basesolver.py
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
def plot_bau_time(self,
                  opt_variable: str = 'b',
                  fig: mpl.figure = None,
                  ax: mpl.axis = None,
                  save: str = None):
    """Plots benefits and costs of optimal and benchark interventions across time 

    Args:
        opt_variable (str, optional): optimal variable to be plotted, where
            b = optimal benefits
            c = 'optimal costs
            cdb = cumulative discounted benefits
            cdc = cumulative discounted costs
            cb = cumulative benefits
            cc = cumulative costs
        Defaults to 'b'.
        fig (matplotlib.figure, optional): matplotlib figure. Defaults to None.
        ax (matplotlib.axis, optional):matplotlib axis to use. Defaults to None.
        save (str, optional): path to save the figure. Defaults to None.

    Raises:
        Exception: not one of the allowed variables for map plotting
    """

    if ax is None:
        fig, ax = plt.subplots()

    p = Plotter(self)

    if opt_variable == 'b':
        opt = 'opt_benefit'
        bau_col = self.benefit_col
        title = "Optimal " + self.benefit_title + " vs. BAU"
    elif opt_variable == 'c':
        opt = 'opt_costs'
        bau_col = self.cost_col
        title = "Optimal Costs vs. BAU"
    elif opt_variable == 'cdb':
        opt = 'cumulative_discounted_benefits'
        bau_col = 'discounted_benefits'
        title = 'Cumulative Discounted ' + self.benefit_title
    elif opt_variable == 'cdc':
        opt = 'cumulative_discounted_costs'
        bau_col = 'discounted_costs'
        title = 'Cumulative Discounted Costs'
    elif opt_variable == 'cb':
        opt = 'cumulative_benefits'
        bau_col = self.benefit_col
        title = 'Cumulative ' + self.benefit_title      
    elif opt_variable == 'cc':
        opt = 'cumulative_costs'
        bau_col = self.cost_col
        title = 'Cumulative Costs'
    else:
        raise Exception("Not one of the allowed variables for map plotting. Try again.")

    if opt_variable in ['cdb', 'cdc', 'cb', 'cc']:

        bench_df = (
            self.bau_df
            .groupby([self.time_col])
            .sum().cumsum()
            .assign(bench_col = lambda df: df[bau_col])
            )

    else:
        bench_df = (
            self.bau_df
            .assign(bench_col = lambda df: df[bau_col])
            .groupby([self.time_col])
            .sum()
                    )

    p._plot_lines(to_plot = opt,
                title= title,
                xlabel = 'Time',
                figure=fig,
                axis=ax)

    bench_df['bench_col'].plot(ax=ax)

    ax.legend(['Optimal', 'BAU'])
    ax.set_xlabel('Time')

    if save is not None:
        plt.savefig(save)

plot_chloropleth(intervention=None, time=None, optimum_interest='b', map_df=None, merge_key=None, intervention_bubbles=False, intervention_bubble_names=None, save=None)

Creates a chloropleth map of the specified intervention and time period for the optimal variable. If more than one intervention is specified, then aggregates them. If more than one time period is specified, then creates a subplots of len(time) and show each.

Parameters:

Name Type Description Default
intervention str

intervention to use. Defaults to None.

None
time Union[int, list]

time periods to plot. Defaults to None.

None
optimum_interest str

optimal variable to use (Options include: 'b' for optimal benefits, 'c' for optimal costs, and 'v' for optimal variable). Defaults to 'b'.

'b'
map_df geopandas.GeoDataFrame

geopandas dataframe with geometry information. Defaults to None.

None
merge_key Union[str, list]

column to merge geo-dataframe. Defaults to None.

None
intervention_bubbles bool

whether to show optimal intervention names in map. Defaults to False.

False
intervention_bubble_names Union[str, list]

key to merge on to geo dataframe. Defaults to None.

None
save str

path to save map. Defaults to None.

None

Raises:

Type Description
Exception

Not one of the allowed variables for map plotting

Source code in minimod_opt/base/basesolver.py
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
def plot_chloropleth(self,
                     intervention: str = None,
                     time: Union[int,list] = None,
                     optimum_interest: str = 'b',
                     map_df: gpd.GeoDataFrame  = None,
                     merge_key: Union[str,list] = None,
                     intervention_bubbles: bool = False,
                     intervention_bubble_names: Union[str,list] = None,
                     save: str = None):
    """Creates a chloropleth map of the specified intervention and time period for the optimal variable. 
    If more than one intervention is specified, then aggregates them. If more than one time period is specified, then creates a subplots of len(time) and show each.

    Args:
        intervention (str, optional): intervention to use. Defaults to None.
        time (Union[int,list], optional): time periods to plot. Defaults to None.
        optimum_interest (str, optional): optimal variable to use (Options include: 'b' for optimal benefits, 'c' for optimal costs, and 'v' for optimal variable). Defaults to 'b'.
        map_df (geopandas.GeoDataFrame, optional): geopandas dataframe with geometry information. Defaults to None.
        merge_key (Union[str,list], optional): column to merge geo-dataframe. Defaults to None.
        intervention_bubbles (bool, optional): whether to show optimal intervention names in map. Defaults to False.
        intervention_bubble_names (Union[str,list], optional): key to merge on to geo dataframe. Defaults to None.
        save (str, optional): path to save map. Defaults to None.

    Raises:
        Exception: Not one of the allowed variables for map plotting
    """


    if intervention is None:
        intervention = self.optimal_interventions

    p = Plotter(self)

    if optimum_interest == 'b':
        opt = 'opt_benefit'
        title = self.benefit_title
    elif optimum_interest == 'c':
        opt = 'opt_costs'
        title = "Optimal Costs"
    elif optimum_interest == 'v':
        opt = 'opt_vals'
        title = "Optimal Interventions"
    elif optimum_interest == 'cdb':
        opt = 'cumulative_discounted_benefits'
        title = 'Cumulative Discounted ' + self.benefit_title
    elif optimum_interest == 'cdc':
        opt = 'cumulative_discounted_costs'
        title = 'Cumulative Discounted Costs'
    elif optimum_interest == 'cb':
        opt = 'cumulative_benefits'
        title = 'Cumulative ' + self.benefit_title      
    elif optimum_interest == 'cc':
        opt = 'cumulative_costs'
        title = 'Cumulative Costs'
    else:
        raise Exception("Not one of the allowed variables for map plotting. Try again.")


    plotter = p._plot_chloropleth_getter(time = time)
    plot = plotter(data = self.opt_df,
                                      intervention = intervention,
                                        time = time,
                                        optimum_interest=opt,
                                        map_df = map_df,
                                        merge_key=merge_key,
                                        aggfunc = 'sum',
                                        title = title,
                                        intervention_bubbles = intervention_bubbles,
                                        intervention_bubble_names = intervention_bubble_names,
                                        save = save)

plot_grouped_interventions(data_of_interest='benefits', title=None, intervention_subset=slice(None), save=None)

Shows Optimal level of benefits or costs in a grouped bar plots for every optimally chosen variable across regions.

Parameters:

Name Type Description Default
data_of_interest str

variable to show. Defaults to 'benefits'.

'benefits'
title str

title for resulting plot. Defaults to None.

None
intervention_subset Union[str, list]

subset of interventions to show on bar plot. Defaults to slice(None).

slice(None)
save str

path to save the figure. Defaults to None.

None
Source code in minimod_opt/base/basesolver.py
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
def plot_grouped_interventions(self, 
                                data_of_interest: str = 'benefits', 
                                title: str = None,
                                intervention_subset: Union[str,list] = slice(None),
                                save: str = None):
    """Shows Optimal level of benefits or costs in a grouped bar plots for every optimally chosen variable across regions.

    Args:
        data_of_interest (str, optional): variable to show. Defaults to 'benefits'.
        title (str, optional):title for resulting plot. Defaults to None.
        intervention_subset (Union[str,list], optional): subset of interventions to show on bar plot. Defaults to slice(None).
        save (str, optional): path to save the figure. Defaults to None.
    """


    p = Plotter(self)

    if data_of_interest == 'benefits':
        col_of_interest = 'opt_benefit'
    elif data_of_interest == 'costs':
        col_of_interest = 'opt_costs'

    p._plot_grouped_bar(intervention_col= self.intervention_col,
                        space_col = self.space_col,
                        col_of_interest= col_of_interest,
                        ylabel = "Optimal Level",
                        intervention_subset= intervention_subset,
                        save = save)

plot_map_benchmark(intervention=None, time=None, optimum_interest='b', bench_intervention=None, map_df=None, merge_key=None, save=None, intervention_in_title=True, intervention_bubbles=False, intervention_bubble_names=None, millions=True, bau_intervention_bubble_names=None)

Maps the optimal level on a map against a benchmark, optionally the BAU level chosen from minimum_benefit or total_funds.

Parameters:

Name Type Description Default
intervention list

interventions to map. Defaults to None.

None
time list

time periods to map. Defaults to None.

None
optimum_interest str

optimal value to use. Options include 'b' (benefits), 'c' (costs), 'v' (variables). Defaults to 'b'.

'b'
bench_intervention list

interventions to use for benchmark. Defaults to None.

None
map_df geopandas.GeoDataFrame

geo dataframe with geometry data. Defaults to None.

None
merge_key Union[str, list]

key to merge data from opt_df to geo dataframe. Defaults to None.

None
save str

path to save the map. Defaults to None.

None
intervention_in_title bool

True if intervention name will be included in the title of the figure. Defaults to True.

True
intervention_bubbles bool

True if intervention bubbles. Defaults to False.

False
intervention_bubble_names Union[str, list]

names of intervention bubbles. Defaults to None.

None
millions bool

True if values displayed in millions. Defaults to True.

True
bau_intervention_bubble_names Union[str, list]

name for bau intervention bubble. Defaults to None.

None
Source code in minimod_opt/base/basesolver.py
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
def plot_map_benchmark(self,
                       intervention: list = None,
                       time: list = None,
                       optimum_interest: str = 'b',
                       bench_intervention: list = None,
                       map_df: gpd.GeoDataFrame = None,
                       merge_key: Union[str,list] = None,
                       save: str = None,
                       intervention_in_title: bool = True,
                       intervention_bubbles: bool = False,
                       intervention_bubble_names: Union[str,list] = None,
                       millions: bool = True,
                       bau_intervention_bubble_names: Union[str,list] = None
                       ):
    """Maps the optimal level on a map against a benchmark, optionally the BAU level chosen from ``minimum_benefit`` or ``total_funds``.

    Args:
        intervention (list, optional): interventions to map. Defaults to None.
        time (list, optional): time periods to map. Defaults to None.
        optimum_interest (str, optional):  optimal value to use. Options include 'b' (benefits), 'c' (costs), 'v' (variables). Defaults to 'b'.
        bench_intervention (list, optional): interventions to use for benchmark. Defaults to None.
        map_df (geopandas.GeoDataFrame, optional):  geo dataframe with geometry data. Defaults to None.
        merge_key (Union[str,list], optional): key to merge data from opt_df to geo dataframe. Defaults to None.
        save (str, optional): path to save the map. Defaults to None.
        intervention_in_title (bool, optional): True if intervention name will be included in the title of the figure. Defaults to True.
        intervention_bubbles (bool, optional): True if intervention bubbles. Defaults to False.
        intervention_bubble_names (Union[str,list], optional): names of intervention bubbles. Defaults to None.
        millions (bool, optional): True if values displayed in millions. Defaults to True.
        bau_intervention_bubble_names (Union[str,list], optional): name for bau intervention bubble. Defaults to None.

    """

    if intervention is None:
        intervention = self.optimal_interventions   

    if figsize is not None:   
        fig = plt.figure(figsize=figsize)
    else:
        fig = plt.figure(figsize=(10,12))

    gs = gridspec.GridSpec(2,2, height_ratios = [6,1])
    optimal = fig.add_subplot(gs[0,0])
    bench = fig.add_subplot(gs[0,1])
    cbar = fig.add_subplot(gs[1,:])

    p = Plotter(self)

    if optimum_interest == 'b':
        opt = 'opt_benefit'
        bench_col = self.benefit_col
        title = self.benefit_title
    elif optimum_interest == 'c':
        opt = 'opt_costs'
        bench_col = self.cost_col
        title = "Costs"
    elif optimum_interest == 'v':
        opt = 'opt_vals'
        title = "Interventions"
    elif optimum_interest == 'cdb':
        opt =  'cumulative_discounted_benefits'
        bench_col = 'discounted_benefits'
        title = 'Cumulative Discounted ' + self.benefit_title
    elif optimum_interest == 'cdc':
        opt =  'cumulative_discounted_costs'
        title = 'Cumulative Discounted Costs'
        bench_col = 'discounted_costs'
    elif optimum_interest == 'cb':
        opt =  'cumulative_benefits'
        title = 'Cumulative ' + self.benefit_title   
        bench_col = self.benefit_col   
    elif optimum_interest == 'cc':
        opt =  'cumulative_costs'
        title = 'Cumulative Costs'
        bench_col = self.cost_col
    else:
        raise Exception("Not one of the allowed variables for map plotting. Try again.")

    if bench_intervention is None:
        bench_intervention = self.minimum_benefit

    if merge_key is None:
        merge_key = self.space_col

    if optimum_interest in ['cdb', 'cdc', 'cb', 'cc']:

        bench_df = self.bau_df.assign(bench_col = lambda df: (df
                                                        .groupby([self.intervention_col, 
                                                                self.space_col])
                                                        [bench_col]
                                                        .transform('cumsum')))

    else:
        bench_df = self.bau_df.assign(bench_col = lambda df: df[bench_col])

    y = 1.05

    if intervention_in_title:
        title = title + f"\nOptimal Interventions:\n{', '.join(intervention)}"
        y = y + .05

    fig.suptitle(title, y=y)
    plotter = p._plot_chloropleth_getter(time)

    # Get min and max values for color map
    opt_max = self.opt_df[opt].max()
    opt_min = self.opt_df[opt].min()

    bench_max = bench_df['bench_col'].max()
    bench_min = bench_df['bench_col'].min()

    vmax = max(opt_max, bench_max)
    vmin = min(opt_min, bench_min)

    if intervention_bubbles:
        bau_intervention_bubbles = 'bau'
    else:
        bau_intervention_bubbles = False


    plotter(data = self.opt_df,
                intervention = intervention,
                time = time,
                optimum_interest=opt,
                map_df = map_df,
                merge_key=merge_key,
                aggfunc = 'sum',
                ax = optimal,
                cax = cbar,
                title = "Optimal Scenario",
                intervention_bubbles = intervention_bubbles,
                intervention_bubble_names = intervention_bubble_names,
                vmin = vmin,
                vmax = vmax,
                legend_kwds = {'orientation' : 'horizontal'})

    plotter(data = bench_df,
                    intervention = bench_intervention,
                    time = time,
                    optimum_interest= 'bench_col',
                    map_df = map_df,
                    merge_key=merge_key,
                    aggfunc = 'sum',
                    ax = bench,
                    show_legend = False,
                    title = f"BAU* Scenario",
                     vmin = vmin,
                    vmax = vmax,
                    intervention_bubbles = bau_intervention_bubbles,
                    intervention_bubble_names = bau_intervention_bubble_names)

    plt.tight_layout()

    fig_text = 'Note: Colors describe ' + title

    if millions:
        fig_text = fig_text + ' (in millions)'

    # if intervention_bubble_names:
    #     fig_text = fig_text + '\nBAU* scenario made up of ' + ', '.join(intervention_bubble_names)

    fig.text(0.5,-.05, fig_text, ha='center')

    if save is not None:
        plt.savefig(save, dpi = p.dpi, bbox_inches="tight")

plot_opt_val_hist(fig=None, ax=None, save=None)

A histogram of the optimally chosen interventions

Parameters:

Name Type Description Default
fig matplotlib.figure

figure instance to use. Defaults to None.

None
ax matplotlib.axis

axis instance to use. Defaults to None.

None
save str

path to save the figure. Defaults to None.

None

Returns:

Type Description
mpl.figure

matplotlib.figure: histogram figure

Source code in minimod_opt/base/basesolver.py
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
def plot_opt_val_hist(self, 
                      fig: mpl.figure = None, 
                      ax: mpl.axis = None, 
                      save: str = None) -> mpl.figure:
    """A histogram of the optimally chosen interventions

    Args:
        fig (matplotlib.figure, optional): figure instance to use. Defaults to None.
        ax (matplotlib.axis, optional): axis instance to use. Defaults to None.
        save (str, optional): path to save the figure. Defaults to None.

    Returns:
        matplotlib.figure: histogram figure
    """      

    p = Plotter(self)

    return p._plot_hist(to_plot = 'opt_vals',
                        title = "Optimal Choices",
                        xlabel = "Time",
                        ylabel= "",
                        figure = fig,
                        axis = ax,
                        save = save)  

plot_time(fig=None, ax=None, save=None, cumulative=False, cumulative_discount=False)

Plots optimal benefits and costs across time after model optimization

Parameters:

Name Type Description Default
fig matplotlib.figure

matplotlib figure. Defaults to None.

None
ax matplotlib.axis

matplotlib axis to use. Defaults to None.

None
save str

path to save the figure. Defaults to None.

None
cumulative bool

whether to plot cumulative benefits or costs. Defaults to False.

False
cumulative_discount bool

whether to plot cumulative benefits or costs, discounted. Defaults to False.

False

Returns:

Type Description
mpl.figure

matplotlib.figure: figure with optimal benefits and cost across time

Source code in minimod_opt/base/basesolver.py
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
def plot_time(self, 
              fig: mpl.figure = None, 
              ax: mpl.axis= None,
              save: str = None,
              cumulative: bool = False,
              cumulative_discount: bool = False) -> mpl.figure:
    """Plots optimal benefits and costs across time after model optimization

    Args:
        fig (matplotlib.figure, optional): matplotlib figure. Defaults to None.
        ax (matplotlib.axis, optional): matplotlib axis to use. Defaults to None.
        save (str, optional): path to save the figure. Defaults to None.
        cumulative (bool, optional): whether to plot cumulative benefits or costs. Defaults to False.
        cumulative_discount (bool, optional): whether to plot cumulative benefits or costs, discounted. Defaults to False.

    Returns:
        matplotlib.figure: figure with optimal benefits and cost across time
    """

    p = Plotter(self)

    if cumulative:
        return p._plot_lines(to_plot = ['cumulative_benefits', 'cumulative_costs'],
                title= "Optima over Time",
                xlabel = 'Time',
                ylabel = self.benefit_title,
                twin =True,
                twin_ylabel= "Currency",
                save = save,
                legend = ['Cumm. ' + self.benefit_title,
                        'Cumm. Costs'],
                figure=fig,
                axis=ax)
    elif cumulative_discount:
        return p._plot_lines(to_plot = ['cumulative_discounted_benefits', 'cumulative_discounted_costs'],
                title= "Optima over Time",
                xlabel = 'Time',
                ylabel = self.benefit_title,
                twin =True,
                twin_ylabel= "Currency",
                save = save,
                legend = ['Cumm. Dis. '+ self.benefit_title,
                        'Cumm. Dis. Costs'],
                figure=fig,
                axis=ax)
    else:
        return p._plot_lines(to_plot = ['opt_benefit', 'opt_costs'],
                            title= "Optima over Time",
                            xlabel = 'Time',
                            ylabel = self.benefit_title,
                            twin =True,
                            twin_ylabel= "Currency",
                            save = save,
                            legend = ['Optimal ' + self.benefit_title,
                                    'Optimal Costs'],
                            figure=fig,
                            axis=ax)

process_results(sol_num=None)

Processes results of optimization to be used in visualization and reporting functions

Parameters:

Name Type Description Default
sol_num int

index of solution. Defaults to None.

None
Source code in minimod_opt/base/basesolver.py
316
317
318
319
320
321
322
323
324
325
326
327
def process_results(self, sol_num:int=None):
    """Processes results of optimization to be used in visualization and reporting functions

    Args:
        sol_num (int, optional): index of solution. Defaults to None.
    """

    self.opt_df = self.model.process_results(self.benefit_col, 
                                        self.cost_col, 
                                        self.intervention_col,
                                        self.space_col,
                                        sol_num=sol_num)

report(sol_num=None, quiet=False)

Prints out a report of optimal model parameters and useful statistics.

Parameters:

Name Type Description Default
sol_num int

index of solution to be displayed. Defaults to None.

None
quiet bool

whether we want the report printed out or not. Defaults to False.

False
Source code in minimod_opt/base/basesolver.py
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
def report(self, sol_num:int=None, quiet:bool=False) -> str:
    """Prints out a report of optimal model parameters and useful statistics.

    Args:
        sol_num (int, optional): index of solution to be displayed. Defaults to None.
        quiet (bool, optional): whether we want the report printed out or not. Defaults to False.
    """

    self.opt_df = self.model.process_results(self.benefit_col, 
                                        self.cost_col, 
                                        self.intervention_col,
                                        self.space_col,
                                        sol_num=sol_num)

    if quiet:
        return
    header = [
        ('MiniMod Solver Results', ""),
        ("Method:" , str(self.sense)),
        ("Solver:", str(self.solver_name)),
        ("Optimization Status:", str(self.status)),
        ("Number of Solutions Found:", str(self.num_solutions))

    ]

    features = [
        ("No. of Variables:", str(self.num_cols)),
        ("No. of Integer Variables:", str(self.num_int)),
        ("No. of Constraints", str(self.num_rows)),
        ("No. of Non-zeros in Constr.", str(self.num_nz))
    ]

    s = OptimizationSummary(self)

    s.print_generic(header, features)

    print("Interventions Chosen:")

write(filename='model.lp')

Save model to file

Parameters:

Name Type Description Default
filename str

name of the file. Defaults to "model.lp".

'model.lp'
Source code in minimod_opt/base/basesolver.py
307
308
309
310
311
312
313
314
def write(self, filename:str="model.lp"):
    """Save model to file

    Args:
        filename (str, optional):name of the file. Defaults to "model.lp".
    """

    self.model.write(filename)

BAUConstraintCreator

Source code in minimod_opt/base/bau_constraint.py
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class BAUConstraintCreator:

    def __init__(self):
        pass

    def bau_df(self, data:pandas.DataFrame, constraint:str, discounted_variable:str = None) -> pandas.DataFrame:
        """A dataframe of costs and benefits for the BAU (business as usual) intervention

        Args:
            data (pandas.DataFrame): input data
            constraint (str): name of dataframe BAU column
            discounted_variable (str, optional): outputs a series of the variable of interest. Defaults to None.

        Returns:
            pandas.DataFrame
        """

        if discounted_variable is None:
            discounted_variable = data.columns

        df = (data
         .loc[(constraint, 
               slice(None), 
               slice(None)),:][discounted_variable]
         )

        return df


    def create_bau_constraint(self, data:pandas.DataFrame, constraint:str, discounted_variable:str, over:str = None)->pandas.DataFrame:
        """This function sums the values of each column in the given dataframe. 
            If the option `over' is provided, the function sums across groups as well

        Args:
            data (pandas.DataFrame): input data
            constraint (str): name of dataframe's column with information BAU
            discounted_variable (str): column of interest.
            over (str, optional): name of dataframe's column  with attribute used to group data by (e.g., time, region). Defaults to None.

        Returns:
            pandas.DataFrame: dataframe with the sum of values for each column-group
        """


        if over is None:
            minimum_constraint = (
                self.bau_df(data, constraint, discounted_variable)
                .sum()
            )
        else:
            minimum_constraint = (
                self.bau_df(data, constraint, discounted_variable)
                .groupby(over)
                .sum()
            )

        return minimum_constraint

bau_df(data, constraint, discounted_variable=None)

A dataframe of costs and benefits for the BAU (business as usual) intervention

Parameters:

Name Type Description Default
data pandas.DataFrame

input data

required
constraint str

name of dataframe BAU column

required
discounted_variable str

outputs a series of the variable of interest. Defaults to None.

None

Returns:

Type Description
pandas.DataFrame

pandas.DataFrame

Source code in minimod_opt/base/bau_constraint.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def bau_df(self, data:pandas.DataFrame, constraint:str, discounted_variable:str = None) -> pandas.DataFrame:
    """A dataframe of costs and benefits for the BAU (business as usual) intervention

    Args:
        data (pandas.DataFrame): input data
        constraint (str): name of dataframe BAU column
        discounted_variable (str, optional): outputs a series of the variable of interest. Defaults to None.

    Returns:
        pandas.DataFrame
    """

    if discounted_variable is None:
        discounted_variable = data.columns

    df = (data
     .loc[(constraint, 
           slice(None), 
           slice(None)),:][discounted_variable]
     )

    return df

create_bau_constraint(data, constraint, discounted_variable, over=None)

This function sums the values of each column in the given dataframe. If the option `over' is provided, the function sums across groups as well

Parameters:

Name Type Description Default
data pandas.DataFrame

input data

required
constraint str

name of dataframe's column with information BAU

required
discounted_variable str

column of interest.

required
over str

name of dataframe's column with attribute used to group data by (e.g., time, region). Defaults to None.

None

Returns:

Type Description
pandas.DataFrame

pandas.DataFrame: dataframe with the sum of values for each column-group

Source code in minimod_opt/base/bau_constraint.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def create_bau_constraint(self, data:pandas.DataFrame, constraint:str, discounted_variable:str, over:str = None)->pandas.DataFrame:
    """This function sums the values of each column in the given dataframe. 
        If the option `over' is provided, the function sums across groups as well

    Args:
        data (pandas.DataFrame): input data
        constraint (str): name of dataframe's column with information BAU
        discounted_variable (str): column of interest.
        over (str, optional): name of dataframe's column  with attribute used to group data by (e.g., time, region). Defaults to None.

    Returns:
        pandas.DataFrame: dataframe with the sum of values for each column-group
    """


    if over is None:
        minimum_constraint = (
            self.bau_df(data, constraint, discounted_variable)
            .sum()
        )
    else:
        minimum_constraint = (
            self.bau_df(data, constraint, discounted_variable)
            .groupby(over)
            .sum()
        )

    return minimum_constraint

Last update: February 21, 2023