How to use the pywr.parameters.load_parameter function in pywr

To help you get started, we’ve selected a few pywr examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pywr / pywr / tests / test_control_curves.py View on Github external
def test_single_cc_load(self, model):
        """ Test load from dict with 'control_curve' key

        This is different to the above test by using singular 'control_curve' key in the dict
        """
        m = model
        s = m.nodes['Storage']

        data = {
            "type": "controlcurve",
            "storage_node": "Storage",
            "control_curve": 0.8,
        }

        s.cost = p = load_parameter(model, data)
        assert isinstance(p, ControlCurveParameter)

        @assert_rec(m, p)
        def expected_func(timestep, scenario_index):
            v = s.initial_volume
            if v >= 80.0:
                expected = 0
            else:
                expected = 1
            return expected

        for initial_volume in (90, 70):
            s.initial_volume = initial_volume
            m.run()
github pywr / pywr / tests / test_parameters_cache.py View on Github external
def test_unknown_cache_type(model):
    data = {
        "cached": "fail",
        "type": "constant",
        "values": 42.0
    }
    with pytest.raises(ValueError):
        parameter = load_parameter(model, data)
github pywr / pywr / tests / test_parameters.py View on Github external
def test_storage_threshold_parameter(self, simple_storage_model):
        """ Test StorageThresholdParameter """
        m = simple_storage_model

        data = {
            "type": "storagethreshold",
            "storage_node": "Storage",
            "threshold": 10.0,
            "predicate": ">"
        }

        p1 = load_parameter(m, data)

        si = ScenarioIndex(0, np.array([0], dtype=np.int32))

        m.nodes['Storage'].initial_volume = 15.0
        m.setup()
        # Storage > 10
        assert p1.index(m.timestepper.current, si) == 1

        m.nodes['Storage'].initial_volume = 5.0
        m.setup()
        # Storage < 10
        assert p1.index(m.timestepper.current, si) == 0
github pywr / pywr / tests / test_parameters.py View on Github external
def test_load(self, model):

        data = {
            "type": "annualharmonicseries",
            "mean": 0.5,
            "amplitudes": [0.25],
            "phases": [np.pi/4]
        }

        p1 = load_parameter(model, data)

        si = ScenarioIndex(0, np.array([0], dtype=np.int32))
        for ts in model.timestepper:
            doy = (ts.datetime.dayofyear - 1) / 365
            np.testing.assert_allclose(p1.value(ts, si), 0.5 + 0.25 * np.cos(doy * 2 * np.pi + np.pi / 4))
github pywr / pywr / tests / test_parameters.py View on Github external
def test_too_close_doys_error(self, simple_linear_model):
        """Test that setting days of the year too close together for optimisation raises an error."""

        data = {
            'type': 'rbfprofile',
            "days_of_year": [1, 140, 200],   # Closest distance is 60 days
            "values": [0.5, 0.7, 0.5],
            "lower_bounds": 0.1,
            "upper_bounds": 0.8,
            "variable_days_of_year_range": 30,  # A range of 30 could cause overlap (140 + 30, 200 - 30)
            "is_variable": True
        }

        with pytest.raises(ValueError):
            load_parameter(simple_linear_model, data)
github pywr / pywr / tests / test_parameters.py View on Github external
def test_load_with_scaling(self, simple_linear_model):
        model = simple_linear_model
        x = 1.5
        data = {
            "type": "polynomial1d",
            "coefficients": [0.5, 2.5],
            "parameter": {
                "type": "constant",
                "value": x
            },
            "scale": 1.25,
            "offset": 0.75
        }
        xscaled = x*1.25 + 0.75
        p1 = load_parameter(model, data)

        @assert_rec(model, p1)
        def expected_func(timestep, scenario_index):
            return 0.5 + 2.5*xscaled
        model.run()
github pywr / pywr / tests / test_parameters.py View on Github external
m.timestepper.start = '2015-04-01'
        m.timestepper.end = '2017-04-01'

        expected_values = np.r_[
            np.linspace(1, 1/366, 366),  # This period covers Apr-2015 to Apr-2016 (i.e. 366 days)
            np.linspace(1, 1/365, 365),  # This period covers Apr-2016 to Apr-2017 (i.e. 365 days)
            np.linspace(1, 1/365, 365),  # This period covers Apr-2017 to Apr-2018 (i.e. 365 days)
        ]

        data = {
            'type': 'uniformdrawdownprofile',
            "reset_day": 1,
            "reset_month": 4
        }

        p = load_parameter(m, data)

        @assert_rec(m, p)
        def expected_func(timestep, scenario_index):
            return expected_values[timestep.index]

        m.run()
github pywr / pywr / tests / test_parameters.py View on Github external
profile = list(range(1, 367))

        data = {
            "type": "division",
            "numerator": {
                "name": "raw",
                "type": "dailyprofile",
                "values": profile,
            },
            "denominator": {
                "type": "constant",
                "value": 123.456
            }
        }

        model.nodes["Input"].max_flow = parameter = load_parameter(model, data)
        model.nodes["Output"].max_flow = 9999
        model.nodes["Output"].cost = -100

        daily_profile = model.parameters["raw"]

        @assert_rec(model, parameter)
        def expected(timestep, scenario_index):
            value = daily_profile.get_value(scenario_index)
            return value / 123.456
        model.run()
github pywr / pywr / tests / test_parameters.py View on Github external
model.timestepper.end = "1920-01-15"
        model.timestepper.delta = 1

        threshold = 5.0

        parameters = {}
        for predicate in (">", "<", "="):
            data = {
                "type": "nodethreshold",
                "node": "Output",
                "threshold": 5.0,
                "predicate": predicate,
                # we need to define values so AssertionRecorder can be used
                "values": [0.0, 1.0],
            }
            parameter = load_parameter(model, data)
            parameter.name = "nodethresold {}".format(predicate)
            parameters[predicate] = parameter

            if predicate == ">":
                expected_data = (np.arange(-1, 20) > threshold).astype(int)
            elif predicate == "<":
                expected_data = (np.arange(-1, 20) < threshold).astype(int)
            else:
                expected_data = (np.arange(-1, 20) == threshold).astype(int)
            expected_data[0] = 0 # previous flow in initial timestep is undefined
            expected_data = expected_data[:, np.newaxis]

            rec = AssertionRecorder(model, parameter, expected_data=expected_data, name="assertion recorder {}".format(predicate))

        model.run()
github pywr / pywr / pywr / schema / __init__.py View on Github external
# Load and assign parameters to an existing node instance.
        for field_name, field in self.fields.items():
            if not isinstance(field, ParameterReferenceField):
                continue

            try:
                field_data = data[field.name]
            except KeyError:
                if field.required:
                    raise marshmallow.ValidationError('Missing field.')
                else:
                    continue
            from pywr.parameters import load_parameter

            try:
                param = load_parameter(model, field_data)
            except Exception as err:
                logger.critical("Error loading parameter %s on %s.\n"
                                "Error Was: %s", field.name, obj.name, err)
                raise

            setattr(obj, field.name, param)
        return obj