Пример #1
0
def get_lake_model():
    """Returns a fully formulated model of the lake problem."""
    # instantiate the model
    lake_model = Model('lakeproblem', function=lake_problem)
    lake_model.time_horizon = 100

    # specify uncertainties
    lake_model.uncertainties = [
        RealParameter('b', 0.1, 0.45),
        RealParameter('q', 2.0, 4.5),
        RealParameter('mean', 0.01, 0.05),
        RealParameter('stdev', 0.001, 0.005),
        RealParameter('delta', 0.93, 0.99)
    ]

    # set levers, one for each time step
    lake_model.levers = [
        RealParameter(str(i), 0, 0.1) for i in range(lake_model.time_horizon)
    ]

    # specify outcomes
    lake_model.outcomes = [
        ScalarOutcome('max_P', ),
        ScalarOutcome('utility'),
        ScalarOutcome('inertia'),
        ScalarOutcome('reliability')
    ]

    # override some of the defaults of the model
    lake_model.constants = [Constant('alpha', 0.41), Constant('nsamples', 150)]
    return lake_model
Пример #2
0
def performExperiments():

    ema_logging.LOG_FORMAT = '[%(name)s/%(levelname)s/%(processName)s] %(message)s'
    ema_logging.log_to_stderr(ema_logging.INFO)

    model = Model('SimulateER', function=simulate_ER)  # instantiate the model
    # specify uncertainties
    model.uncertainties = [RealParameter("p", 0.1, 1.0)]
    model.uncertainties = [RealParameter("f", 0.1, 0.9)]

    model.levers = [IntegerParameter("n", 10, 100)]

    # specify outcomes
    model.outcomes = [ScalarOutcome('cc')]

    model.constants = [Constant('replications', 10)]

    n_scenarios = 10
    n_policies = 10

    res = perform_experiments(model, n_scenarios, n_policies)

    experiments, outcomes = res
    data = experiments[['n', 'p', 'f']]
    data.to_csv('out.csv', index=False)
    return data
Пример #3
0
        RealParameter("r1", 0, 2),
        RealParameter("r2", 0, 2),
        RealParameter("w1", 0, 1)
    ]

    # specify outcomes
    lake_model.outcomes = [
        ScalarOutcome('max_P'),
        ScalarOutcome('utility'),
        ScalarOutcome('inertia'),
        ScalarOutcome('reliability')
    ]

    # override some of the defaults of the model
    lake_model.constants = [
        Constant('alpha', 0.41),
        Constant('nsamples', 100),
        Constant('myears', 100)
    ]

    # setup and execute the robust optimization
    def signal_to_noise(data):
        mean = np.mean(data)
        std = np.std(data)
        sn = mean / std
        return sn

    MAXIMIZE = ScalarOutcome.MAXIMIZE  # @UndefinedVariable
    MINIMIZE = ScalarOutcome.MINIMIZE  # @UndefinedVariable
    robustnes_functions = [
        ScalarOutcome('mean p',
Пример #4
0
    # set levers
    lake_model.levers = [RealParameter("c1", -2, 2),
                         RealParameter("c2", -2, 2),
                         RealParameter("r1", 0, 2),
                         RealParameter("r2", 0, 2),
                         RealParameter("w1", 0, 1)
                         ]

    # specify outcomes
    lake_model.outcomes = [ScalarOutcome('max_P'),
                           ScalarOutcome('utility'),
                           ScalarOutcome('inertia'),
                           ScalarOutcome('reliability')]

    # override some of the defaults of the model
    lake_model.constants = [Constant('alpha', 0.41),
                            Constant('nsamples', 100),
                            Constant('myears', 100)]

    # setup and execute the robust optimization
    def signal_to_noise(data):
        mean = np.mean(data)
        std = np.std(data)
        sn = mean/std
        return sn

    MAXIMIZE = ScalarOutcome.MAXIMIZE  # @UndefinedVariable
    MINIMIZE = ScalarOutcome.MINIMIZE  # @UndefinedVariable
    robustnes_functions = [ScalarOutcome('mean p', kind=MINIMIZE,
                                         variable_name='max_P', function=np.mean),
                           ScalarOutcome('std p', kind=MINIMIZE,
                  kind=ScalarOutcome.MINIMIZE,
                  function=np.max),
    ScalarOutcome('Infectious population',
                  kind=ScalarOutcome.MINIMIZE,
                  function=np.mean),
    ScalarOutcome('Stock Total Effort',
                  kind=ScalarOutcome.MINIMIZE,
                  function=np.max),
    ScalarOutcome('Stock Societal Stress',
                  kind=ScalarOutcome.MINIMIZE,
                  function=np.max)
]

# Ensure the proper constant values based on information above
constants = [
    Constant('Initial deceased population', 0),
    Constant('Initial exposed population', 0),
    Constant('Initial infectious population', 1),
    Constant('Initial recovered population', 0),
    Constant('Initial susceptible population', 100000)
]

levers = [
    RealParameter("Lever Social Distance I", 0.00001, 1),
    RealParameter("Lever Social Distance II", 0.00001, 1),
    RealParameter("Lever Social Distance III", 0.00001, 1),
    RealParameter("Lever Public Info", 0.00001, 1),
    RealParameter("Lever Public Edu", 0.00001, 1),
    RealParameter("Lever Facemasks", 0.00001, 1),
    RealParameter("Lever Tracing", 0.00001, 1),
    RealParameter("Lever Case Isolation", 0.00001, 1),
Пример #6
0
def get_model_for_problem_formulation(problem_formulation_idea):
    disease_model = VensimModel("multidisease",
                                wd=r'.\models',
                                model_file='disease_model.vpm')

    disease_model.uncertainties = [
        # Sanitation Unknowns
        IntegerParameter('desire for improved sanitation', 10, 100),
        # Water Supply Unknowns
        IntegerParameter('Cost of well repair', 660, 1800),
        # Water Quality Unknowns
        IntegerParameter('use HWT', 10, 100),
        # Hygiene Unknowns
        IntegerParameter('Intensity of hygiene campaign', 10, 100),
        # Vaccination Unknowns
        IntegerParameter('Reliability of vaccine supply', 10, 100),
        # Treatment Unknowns
        IntegerParameter('seeking treatment', 10, 100),
        # Other Unknowns
        IntegerParameter('percent willing to accept MDA', 10, 100),
        # RealParameter('Childbearing years', 9, 14), #N.B. huge impact
    ]

    disease_model.constants = [
        Constant('Length latrine program', 10),
        Constant('Length GW supply program', 10),
        Constant('Length of water quality program', 10),
        Constant("Duration of hygiene campaign", 10),
        Constant("Length of ORT subsidy", 10),
        Constant("Years of MDA campaign", 10)
    ]

    disease_model.levers = [
        # Sanitation Levers
        IntegerParameter("Number of new latrines to build", 0, 9000),
        IntegerParameter("Number of latrines to maintain", 0, 4000),
        # Water Supply Levers
        IntegerParameter("Number of new wells to drill", 0, 2000),
        IntegerParameter("Number of wells to repair", 0, 2000),
        # Water Quality Levers
        IntegerParameter("Availability HWT", 0, 100),
        # Hygiene Promotion Levers
        IntegerParameter("HW stations to build", 0, 8000),
        # Vaccination Levers
        IntegerParameter("percentage of infants to vaccinate", 0, 100),
        # Treatment Levers
        IntegerParameter("Access to tmt", 0, 100),
        # MDA levers
        IntegerParameter("percent adults given MDA", 0, 100),
        IntegerParameter("percent youth given Albendazole", 0, 100),
    ]

    # add policies
    disease_model.policies = [
        Policy(
            'LatrineProgram', **{
                "Number of new latrines to build": 5000,
                "Number of latrines to maintain": 4000,
                "Length latrine program": 10,
                "Number of new wells to drill": 0,
                "Number of wells to repair": 0,
                "Length GW supply program": 0,
                "Availability HWT": 0,
                "Length of water quality program": 0,
                "HW stations to build": 0,
                "Duration of hygiene campaign": 0,
                "percentage of infants to vaccinate": 0,
                "Access to tmt": 0,
                "Length of ORT subsidy": 0,
                "percent adults given Albendazole": 0,
                "percent youth given Albendazole": 0,
                "Years of MDA campaign": 0,
            }),
        Policy(
            'GWsupply', **{
                "Number of new latrines to build": 0,
                "Number of latrines to maintain": 0,
                "Length latrine program": 0,
                "Number of new wells to drill": 1000,
                "Number of wells to repair": 100,
                "Length GW supply program": 10,
                "Availability HWT": 0,
                "Length of water quality program": 0,
                "HW stations to build": 0,
                "Duration of hygiene campaign": 0,
                "percentage of infants to vaccinate": 0,
                "Access to tmt": 0,
                "Length of ORT subsidy": 0,
                "percent adults given Albendazole": 0,
                "percent youth given Albendazole": 0,
                "Years of MDA campaign": 0,
            }),
        Policy(
            'ORT', **{
                "Number of new latrines to build": 0,
                "Number of latrines to maintain": 0,
                "Length latrine program": 0,
                "Number of new wells to drill": 0,
                "Number of wells to repair": 0,
                "Length GW supply program": 0,
                "Availability HWT": 0,
                "Length of water quality program": 0,
                "HW stations to build": 0,
                "Duration of hygiene campaign": 0,
                "percentage of infants to vaccinate": 0,
                "Access to tmt": 100,
                "Length of ORT subsidy": 10,
                "percent adults given Albendazole": 0,
                "percent youth given Albendazole": 0,
                "Years of MDA campaign": 0,
            }),
        Policy(
            'Hygiene', **{
                "Number of new latrines to build": 0,
                "Number of latrines to maintain": 0,
                "Length latrine program": 0,
                "Number of new wells to drill": 0,
                "Number of wells to repair": 0,
                "Length GW supply program": 0,
                "Availability HWT": 0,
                "Length of water quality program": 0,
                "HW stations to build": 1000,
                "Duration of hygiene campaign": 10,
                "percentage of infants to vaccinate": 0,
                "Access to tmt": 0,
                "Length of ORT subsidy": 0,
                "percent adults given Albendazole": 0,
                "percent youth given Albendazole": 0,
                "Years of MDA campaign": 0,
            }),
        Policy(
            'Vaccin', **{
                "Number of new latrines to build": 0,
                "Number of latrines to maintain": 0,
                "Length latrine program": 0,
                "Number of new wells to drill": 0,
                "Number of wells to repair": 0,
                "Length GW supply program": 0,
                "Availability HWT": 0,
                "Length of water quality program": 0,
                "HW stations to build": 0,
                "Duration of hygiene campaign": 0,
                "percentage of infants to vaccinate": 100,
                "Access to tmt": 0,
                "Length of ORT subsidy": 0,
                "percent adults given Albendazole": 0,
                "percent youth given Albendazole": 0,
                "Years of MDA campaign": 0,
            }),
        Policy(
            'DrinkingWater', **{
                "Number of new latrines to build": 0,
                "Number of latrines to maintain": 0,
                "Length latrine program": 0,
                "Number of new wells to drill": 0,
                "Number of wells to repair": 0,
                "Length GW supply program": 0,
                "Availability HWT": 100,
                "Length of water quality program": 10,
                "HW stations to build": 0,
                "Duration of hygiene campaign": 0,
                "percentage of infants to vaccinate": 0,
                "Access to tmt": 0,
                "Length of ORT subsidy": 0,
                "percent adults given Albendazole": 0,
                "percent youth given Albendazole": 0,
                "Years of MDA campaign": 0,
            }),
        Policy(
            'MDA', **{
                "Number of new latrines to build": 0,
                "Number of latrines to maintain": 0,
                "Length latrine program": 0,
                "Number of new wells to drill": 0,
                "Number of wells to repair": 0,
                "Length GW supply program": 0,
                "Availability HWT": 0,
                "Length of water quality program": 0,
                "HW stations to build": 0,
                "Duration of hygiene campaign": 0,
                "percentage of infants to vaccinate": 0,
                "Access to tmt": 0,
                "Length of ORT subsidy": 0,
                "percent adults given Albendazole": 100,
                "percent youth given Albendazole": 100,
                "Years of MDA campaign": 10,
            }),
        Policy(
            'DoNothing', **{
                "Number of new latrines to build": 0,
                "Number of latrines to maintain": 0,
                "Length latrine program": 0,
                "Number of new wells to drill": 0,
                "Number of wells to repair": 0,
                "Length GW supply program": 0,
                "Availability HWT": 0,
                "Length of water quality program": 0,
                "HW stations to build": 0,
                "Duration of hygiene campaign": 0,
                "percentage of infants to vaccinate": 0,
                "Access to tmt": 0,
                "Length of ORT subsidy": 0,
                "percent adults given Albendazole": 0,
                "percent youth given Albendazole": 0,
                "Years of MDA campaign": 0,
            }),
    ]
    # Problem formulations:
    direction = ScalarOutcome.MINIMIZE
    if problem_formulation_idea == 1:  ##PF1: Minimum child (<5 yo) deaths due to Rotavirus
        disease_model.name = 'Minimize Child <5 Rotavirus infections by 2030'
        disease_model.outcomes.clear()
        disease_model.outcomes = [
            ScalarOutcome(
                'Mortality',  #Deaths due to Rotavirus
                variable_name=[
                    'children under 5 deaths[Rota]', 'ts until 2020',
                    'ts at 2030'
                ],
                function=avg_over_period,
                kind=direction,
                expected_range=(10000, 250000)),
            ScalarOutcome(
                'Morbidity',  #Rota DALYs children
                variable_name=[
                    "Years Lost to Disability in Children[Rota]",
                    'ts until 2020', 'ts at 2030'
                ],
                function=avg_over_period,
                kind=direction,
                expected_range=(6000, 9000)),
            ScalarOutcome(
                'Timeliness',  #Delta child infections 2030
                variable_name=[
                    "Number of Children Infected[Rota]", 'ts until 2020',
                    'ts at 2030'
                ],
                function=change_over_period,
                kind=direction,
                expected_range=(-0.9, 0.1)),
            ScalarOutcome(
                'CapEx',
                variable_name=['Upfront Cost', 'ts until 2020', 'ts at 2040'],
                function=total_over_period,
                kind=direction,
                expected_range=(0, 3000000000000)),
            ScalarOutcome(
                'OpEx',  #Recurring Cost
                variable_name=[
                    'Recurring Cost', 'ts until 2020', 'ts at 2040'
                ],
                function=total_over_period,
                kind=direction,
                expected_range=(0, 2000000000000)),
        ]

    elif problem_formulation_idea == 2:  ##PF2: Minimum prevalence of ascariasis in Youth (Infants, PreSACs, and SACs) in 5 years
        disease_model.name = 'Minimize Ascariasis in Youth by 2025'
        disease_model.outcomes.clear()
        disease_model.outcomes = [
            ScalarOutcome('Mortality',
                          variable_name=[
                              'Youth Mortality[Ascar]', 'ts until 2020',
                              'ts at 2025'
                          ],
                          function=avg_over_period,
                          kind=direction,
                          expected_range=(1000, 20000)),
            ScalarOutcome('Morbidity',
                          variable_name=[
                              'Years Lost to Disability in Youth[Ascar]',
                              'ts until 2020', 'ts at 2025'
                          ],
                          function=avg_over_period,
                          kind=direction,
                          expected_range=(20000, 160000)),
            ScalarOutcome(
                'Timeliness',  #Change in prevalence of ascariasis in youth by 2025
                variable_name=[
                    'Number of Youth Infected[Ascar]', 'ts until 2020',
                    'ts at 2025'
                ],
                function=change_over_period,
                kind=direction,
                expected_range=(-1, 0)),
            ScalarOutcome(
                'CapEx',  #Upfront Cost
                variable_name=['Upfront Cost', 'ts until 2020', 'ts at 2040'],
                function=total_over_period,
                kind=direction,
                expected_range=(0, 3000000000000)),
            ScalarOutcome(
                'OpEx',  #Recurring Cost
                variable_name=[
                    'Recurring Cost', 'ts until 2020', 'ts at 2040'
                ],
                function=total_over_period,
                kind=direction,
                expected_range=(0, 2000000000000)),
        ]
    elif problem_formulation_idea == 3:  #PF3: Minimum Child (<5 yo) mortality, all diseases, w/in one year
        disease_model.name = 'Immediately minimize Child <5 burden from all causes'
        disease_model.outcomes.clear()
        disease_model.outcomes = [
            ScalarOutcome('Mortality',
                          variable_name=[
                              'Total children under 5 deaths', 'ts until 2020',
                              'ts at 2021'
                          ],
                          function=avg_over_period,
                          kind=direction,
                          expected_range=(50000, 400000)),
            ScalarOutcome('Morbidity',
                          variable_name=[
                              'morbidity in children', 'ts until 2020',
                              'ts at 2021'
                          ],
                          function=avg_over_period,
                          kind=direction,
                          expected_range=(40000, 100000)),
            ScalarOutcome(
                'Timeliness',  #Delta child infections 2021
                variable_name=[
                    'Total children w gastroenteric infection',
                    'ts until 2020', 'ts at 2021'
                ],
                function=change_over_period,
                kind=direction,
                expected_range=(-0.5, 0)),
            ScalarOutcome(
                'CapEx',  #Upfront Cost
                variable_name=['Upfront Cost', 'ts until 2020', 'ts at 2040'],
                function=total_over_period,
                kind=direction,
                expected_range=(5000000, 3000000000000)),
            ScalarOutcome(
                'OpEx',  #Recurring Cost
                variable_name=[
                    'Recurring Cost', 'ts until 2020', 'ts at 2040'
                ],  #bc no rec cost will show up in 1 yr
                function=total_over_period,
                kind=direction,
                expected_range=(50000000000, 2000000000000)),
        ]
    elif problem_formulation_idea == 4:  #PF4: Minimum number infected, all diseases, sustainably
        disease_model.name = 'Minimize number infected all diseases by 2040'
        disease_model.outcomes.clear()
        disease_model.outcomes = [
            ScalarOutcome('Mortality',
                          variable_name=[
                              'Total lives lost', 'ts until 2020', 'ts at 2040'
                          ],
                          function=avg_over_period,
                          kind=direction,
                          expected_range=(50000, 250000)),
            ScalarOutcome('Morbidity',
                          variable_name=[
                              'disability burden', 'ts until 2020',
                              'ts at 2040'
                          ],
                          function=avg_over_period,
                          kind=direction,
                          expected_range=(100000, 900000)),
            ScalarOutcome(
                'Timeliness',  #delta infections 2040
                variable_name=[
                    'Total number of gastroenteric infection', 'ts until 2020',
                    'ts at 2040'
                ],
                function=change_over_period,
                kind=direction,
                expected_range=(-1, -.45)),
            ScalarOutcome(
                'CapEx',  #Upfront Cost
                variable_name=['Upfront Cost', 'ts until 2020', 'ts at 2040'],
                function=total_over_period,
                kind=direction,
                expected_range=(20000000000, 3000000000000)),
            ScalarOutcome(
                'OpEx',  #Recurring Cost
                variable_name=[
                    'Recurring Cost', 'ts until 2020', 'ts at 2040'
                ],
                function=total_over_period,
                kind=direction,
                expected_range=(20000000000, 2000000000000)),
            ##recurring costs divided by 20 years
        ]

    else:
        raise TypeError('unknown problem identifier')
    return disease_model
    df_unc['Min'] = df_unc['Reference'] * 0.5
    df_unc['Max'] = df_unc['Reference'] * 1.5

    vensimModel.uncertainties = [
        RealParameter(row['Uncertainties'], row['Min'], row['Max'])
        for index, row in df_unc.iterrows()
    ]

    #vensimModel.outcomes = [TimeSeriesOutcome(out) for out in df_out['Outcomes']]
    vensimModel.outcomes = [
        TimeSeriesOutcome('Total Agricultural and Land Use Emissions')
    ]

    sc = 0
    n = 2500
    vensimModel.constants = [Constant('SA Diet Composition Switch', sc)]
    with MultiprocessingEvaluator(vensimModel, n_processes=7) as evaluator:
        for sc in [0, 2, 3, 4]:
            start = time.time()
            results_sa = evaluator.perform_experiments(
                n, uncertainty_sampling=SOBOL, reporting_interval=5000)
            end = time.time()
            print("Experiments took {} seconds, {} hours.".format(
                end - start, (end - start) / 3600))

            fn = './Diet_Sobol_n{}_sc{}_v4_2050.tar.gz'.format(
                n, sc
            )  #v2 is with narrow ranges for efficacy and removing some of the unimportant parameters
            #v3 is with the new multiplicative formulation, and new social norm parameters
            save_results(results_sa, fn)
Пример #8
0
from ema_workbench import (RealParameter, ScalarOutcome, Constant, Constraint)

from modelData.builder import *

modelParams = type('obj', (object,), {
    'timeHorizon': 100,
    'uncertainties': [RealParameter('b', 0.1, 0.45),
                      RealParameter('q', 2.0, 4.5),
                      RealParameter('mean', 0.01, 0.05),
                      RealParameter('stdev', 0.001, 0.005),
                      RealParameter('delta', 0.93, 0.99)],
    'outcomes':  [ScalarOutcome('max_P', kind=ScalarOutcome.MINIMIZE),
                  ScalarOutcome('utility', kind=ScalarOutcome.MAXIMIZE),
                  ScalarOutcome('inertia', kind=ScalarOutcome.MAXIMIZE),
                  ScalarOutcome('reliability', kind=ScalarOutcome.MAXIMIZE)],
    'constants': [Constant('alpha', 0.41),
                  Constant('reps', 150)],
    'constraints': [Constraint('pollution level', outcome_names="max_P",
                               function=lambda x:max(0, x-2.5))],

})
baseModelParams = {'b': .42, 'delta': .98,
                   'mean': 0.02, 'q': 2, 'stdev': 0.0017}

baseModel = base_model(modelParams)
baseModel.name = 'base'

models = {
    'dps': dps_model(modelParams),
    'plannedadaptive': planned_adaptive_model(modelParams),
    'intertemporal': intertemporal_model(modelParams)
Пример #9
0
    RealParameter("r1", 0, 2),
    RealParameter("r2", 0, 2),
    RealParameter("w1", 0, 1)
]

#specify outcomes
model.outcomes = [
    ScalarOutcome('max_P'),
    ScalarOutcome('utility'),
    ScalarOutcome('inertia'),
    ScalarOutcome('reliability')
]

# override some of the defaults of the model
model.constants = [
    Constant('alpha', 0.41),
    Constant('nsamples', 150),
    Constant('steps', 100)
]

from ema_workbench import (SequentialEvaluator, ema_logging,
                           perform_experiments)
ema_logging.log_to_stderr(ema_logging.INFO)

from SALib.analyze import sobol
from ema_workbench.em_framework.salib_samplers import get_SALib_problem

with SequentialEvaluator(model) as evaluator:
    sa_results = evaluator.perform_experiments(scenarios=1,
                                               uncertainty_sampling='sobol')
Пример #10
0
model.uncertainties = [
    RealParameter('prey_birth_rate', 0.015, 0.35),
    RealParameter('predation_rate', 0.0005, 0.003),
    RealParameter('predator_efficiency', 0.001, 0.004),
    RealParameter('predator_loss_rate', 0.04, 0.08),
]

# specify outcomes
model.outcomes = [
    TimeSeriesOutcome('prey'),  # amount of prey
    TimeSeriesOutcome('predators'),  # amount of predators
]

# model constants
model.constants = [
    Constant('dt', 0.25),
    Constant('final_time', 365),
    Constant('reps', 1)
]

###
# Perform experiments
from ema_workbench import (SequentialEvaluator)

with SequentialEvaluator(model) as evaluator:
    results = perform_experiments(model,
                                  100,
                                  reporting_interval=1,
                                  evaluator=evaluator)

experiments, outcomes = results
Пример #11
0
    ]

    # specify outcomes
    model.outcomes = [
        ScalarOutcome('y'),
        ScalarOutcome('y1'),
        ArrayOutcome('y3'),
        ScalarOutcome('y4'),
        ScalarOutcome('y5'),
        ScalarOutcome('y6'),
        ScalarOutcome('y7')
    ]

    # override some of the defaults of the model
    model.constants = [
        Constant("X4rSnow", 0.7),
        Constant("xCostDay", 6),
        Constant("xRevenueDay", 10)
    ]

    #results = perform_experiments(model, 1500, 5)
    results = perform_experiments(model, 200, 20)

    #with MultiprocessingEvaluator(model, n_processes=4) as evaluator:
    #    results = evaluator.perform_experiments(scenarios=4, policies=5)

print('end!')
training_time = time.time() - start_time

print("--- %s seconds ---" % (training_time))
print('training time : {} mins and {} seconds'.format(
Пример #12
0
def generate_params(prefix: str,
                    dataset: Dict,
                    override: Optional[Dict] = None):
    """Generate EMA Workbench compatible parameter definitions.

    Parameters
    ----------
    prefix : str
    dataset : dict, of parameters for given component
    override : Dict[str, object], values to override nominals with keys
               based on prefix + name
    
    Returns
    ----------
    * Dict matching structure of dataset
    """
    prefix += '__'
    if override is None:
        override = {}

    for n, vals in dataset.items():
        var_id = prefix + n

        if isinstance(vals, dict):
            dataset[n] = generate_params(prefix, vals, override)
            continue

        # Replace nominal value with override value if specified
        if var_id in override:
            vals = override.pop(var_id)
            dataset[n] = Constant(var_id, vals)
            continue

        param = None
        try:
            val_type, *param_vals = vals

            if len(set(param_vals)) == 1:
                dataset[n] = Constant(var_id, param_vals[0])
                continue

            ptype = getattr(ema_mod, val_type)
            param = ptype(var_id, *param_vals[1:], default=param_vals[0])
            dataset[n] = param
            continue

        except (ValueError, TypeError) as e:
            dataset[n] = Constant(var_id, vals)
            continue
        except AttributeError:
            warnings.warn(
                "Old data parsing method used - this wil be deprecated in the future."
            )
            # Unknown param type, revert to old behaviour
            # To be removed
            nom, lb, ub = vals

            same_value = False
            if not isinstance(nom, str):
                try:
                    param = RealParameter(name=var_id,
                                          default=nom,
                                          lower_bound=lb,
                                          upper_bound=ub)
                except ValueError:
                    same_value = True
            else:
                if (nom == lb) and (ub == lb):
                    same_value = True
                else:
                    if len(set(vals)) > 1:
                        param = CategoricalParameter(name=var_id,
                                                     default=nom,
                                                     categories=vals)
                    else:
                        same_value = True
                # End if
            # End if

            if same_value:
                param = Constant(var_id, nom)

            if param is None:
                raise ValueError("Could not determine parameter type!")

            dataset[n] = param
        # End try
    # End for

    return dataset
Пример #13
0
                    TimeSeriesOutcome('terminal_capacity_project', function=mean_over_replications),              
                    TimeSeriesOutcome('terminal_capacity_unused_project', function=mean_over_replications),       
                    TimeSeriesOutcome('terminal_TP_project', function=mean_over_replications),                    
                    TimeSeriesOutcome('terminal_occupancy_project', function=mean_over_replications),             
                    TimeSeriesOutcome('terminal_capacity_expanded_project', function=mean_over_replications),     
                    TimeSeriesOutcome('terminal_capacity_initial_project', function=mean_over_replications),      
                    TimeSeriesOutcome('terminal_denied_infra_cap_project', function=mean_over_replications),      
                    TimeSeriesOutcome('terminal_surface_project', function=mean_over_replications),               
                    TimeSeriesOutcome('TP_without_terminal_project', function=mean_over_replications),            
                    TimeSeriesOutcome('total_TP_rdam_project', function=mean_over_replications),                  
                    TimeSeriesOutcome('total_surface_terminals_project', function=mean_over_replications),  
                    TimeSeriesOutcome('business_case_terminal_project', function=mean_over_replications),
                    TimeSeriesOutcome('business_value_pora_project', function=mean_over_replications),               
                    TimeSeriesOutcome('coal_throughput_Rdam_project', function=mean_over_replications),
                    TimeSeriesOutcome('market_share_Rdam_project', function=mean_over_replications),
                    TimeSeriesOutcome('coal_throughput_Rdam_current', function=mean_over_replications),
                    TimeSeriesOutcome('market_share_Rdam_current', function=mean_over_replications),
                    ScalarOutcome('NPV', function=mean_over_replications)]



    model.constants = [Constant('run_times', 40),
                      Constant('project_to_assess','Current values'),
                      Constant('energy_demand_init', 30000000),
                      Constant('other_grey_share_init', 0.3),
                      Constant('green_share_init', 0.13),
                      Constant('market_share_init',0.15)]
                     

       
Пример #14
0
# set levers
model.levers = [RealParameter("solarVSwind", 0, 1)]

# specify outcomes
model.outcomes = [ScalarOutcome(metric) for metric in metrics]
# model.outcomes = [ScalarOutcome("hv_net_capacity_delta_present_future")]

# initiate ETM connection
ref_scenario = 769771
ETM = init_ETM(ref_scenario, metrics)

# override some of the defaults of the model
model.constants = [
    # standard = 1920 hours / year
    Constant("ETM_instance", ETM),
    Constant("flh_of_energy_power_wind_turbine_inland", 3000),
    Constant("flh_of_solar_pv_solar_radiation", 1000),  # standard = 867 / year
    Constant("costs_co2", 100),  # standard = 8 €/tonne
    Constant("total_supply", 55e6),  # MWh 35e6 minimum, RES 1.0 55e6
]

results = perform_experiments(model, policies=25)

experiments, outcomes = results

policies = experiments["policy"]
for i, policy in enumerate(np.unique(policies)):
    experiments.loc[policies == policy, "policy"] = str(i)

data = pd.DataFrame(outcomes)
Пример #15
0
                             RealParameter('mean', 0.01, 0.05),
                             RealParameter('stdev', 0.001, 0.005),
                             RealParameter('delta', 0.93, 0.99)]
 
 # set levers, one for each time step
 lake_model.levers = [RealParameter(str(i), 0, 0.1) for i in 
                      range(lake_model.time_horizon)]
 
 #specify outcomes 
 lake_model.outcomes = [ScalarOutcome('max_P',),
                        ScalarOutcome('utility'),
                        ScalarOutcome('inertia'),
                        ScalarOutcome('reliability')]
 
 # override some of the defaults of the model
 lake_model.constants = [Constant('alpha', 0.41),
                         Constant('nsamples', 150)]
     
 
 # generate sa single default no release policy
 policy = Policy('no release', **{str(i):0.1 for i in range(100)})
 
 n_scenarios = 1000
  
 with MultiprocessingEvaluator(lake_model) as evaluator:
     results = evaluator.perform_experiments(n_scenarios, policy, 
                                             uncertainty_sampling=SOBOL)
     
 sobol_stats, s2, s2_conf = analyze(results, 'max_P')
 print(sobol_stats)
 print(s2)
Пример #16
0

if __name__ == '__main__':
    ema_logging.LOG_FORMAT = '[%(name)s/%(levelname)s/%(processName)s] %(message)s'
    ema_logging.log_to_stderr(ema_logging.INFO)

    model = Model('SimulateER', function=simulate_ER)  # instantiate the model
    # specify uncertainties
    model.uncertainties = [RealParameter("p", 0.1, 1.0)]

    model.levers = [IntegerParameter("n", 10, 100)]

    # specify outcomes
    model.outcomes = [ScalarOutcome('density')]

    model.constants = [Constant('replications', 10)]

    n_scenarios = 10
    n_policies = 10

    res = perform_experiments(model, n_scenarios, n_policies)
    """ 
        with MultiprocessingEvaluator(model) as evaluator:
            res = evaluator.perform_experiments(n_scenarios, n_policies,
                                             levers_sampling=MC)
    """
    experiments, outcomes = res
    data = experiments[['n', 'p']]
    data.to_csv('outExperiment.csv', index=False)
    y = pd.DataFrame(outcomes['density'], columns=['density'])
    print(y)
Пример #17
0
# input domain name from command line
domain = sys.argv[1]

ema_logging.LOG_FORMAT = '[%(name)s/%(levelname)s/%(processName)s] %(message)s'
ema_logging.log_to_stderr(ema_logging.INFO)
    
model = Model('grsystem', function=gr_system)

# set levers
model.uncertainties = [IntegerParameter("phi", 0,100),
                RealParameter("delta", 0, 5),
                RealParameter("lamb", 1, 5),
                RealParameter("threshold", 0.6, 1.0)]

# model.levers = [CategoricalParameter("domain", ["sokoban", "blocks-world"])]
model.constants = [Constant("domain", domain)]

#specify outcomes
model.outcomes = [ScalarOutcome('p_10'),
                  ScalarOutcome('r_10'),
                  ScalarOutcome('a_10'),
                  ScalarOutcome('p_30'),
                  ScalarOutcome('r_30'),
                  ScalarOutcome('a_30'),
                  ScalarOutcome('p_50'),
                  ScalarOutcome('r_50'),
                  ScalarOutcome('a_50'),
                  ScalarOutcome('p_70'),
                  ScalarOutcome('r_70'),
                  ScalarOutcome('a_70'),
                  ScalarOutcome('p_100'),
# specify outcomes
model.outcomes = [
    ScalarOutcome('max_P'),
    ScalarOutcome('utility'),
    ScalarOutcome('inertia'),
    ScalarOutcome('reliability')
]

# set levers
#model.levers = [RealParameter('decisions', 0, 0.1)]
model.levers = [
    RealParameter(f"l{i}", 0, 0.1) for i in range(model.time_horizon)
]

# model constants
model.constants = [Constant('alpha', 0.4), Constant('nsamples', 100)]

#####################################################################################################
from ema_workbench import Policy
# performing experiments
# generate experiments
n_scenarios = 1000
n_policies = 4
policy = Policy("no release", **{l.name: 0 for l in model.levers})

from ema_workbench import (MultiprocessingEvaluator, ema_logging,
                           perform_experiments)

ema_logging.log_to_stderr(ema_logging.INFO)

if __name__ == '__main__':
    #                          RealParameter("w1", 0, 1)
    #                          ]

    lake_model.levers = [
        RealParameter(str(i), 0, 0.1) for i in range(lake_model.time_horizon)
    ]

    lake_model.outcomes = [
        ScalarOutcome('max_P', kind=ScalarOutcome.MINIMIZE),
        ScalarOutcome('utility', kind=ScalarOutcome.MAXIMIZE),
        ScalarOutcome('inertia', kind=ScalarOutcome.MINIMIZE),
        ScalarOutcome('reliability', kind=ScalarOutcome.MAXIMIZE)
    ]

    lake_model.constants = [
        Constant('alpha', 0.41),
        Constant('nsamples', 100),
        Constant('timehorizon', lake_model.time_horizon)
    ]

    scenarios = ['Ref', 77, 96, 130, 181]
    random_scenarios = [81, 289, 391, 257]
    policies = []

    for s in random_scenarios:
        #         if s == 'Ref':
        #             solutions = pd.DataFrame.from_csv(r'../results/Results_EpsNsgaII_nfe10000_scRef_v3.csv')
        #         else:
        #             solutions = pd.DataFrame.from_csv(r'../results/Results_EpsNsgaII_nfe10000_sc{}_v5.csv'.format(s))

        #checked if there are duplicates: No.