API Reference

parameters

Parameters

class paramtools.parameters.Parameters(initial_state: Optional[dict] = None, index_rates: Optional[dict] = None, sort_values: bool = True, **ops)[source]
adjust(params_or_path: Union[str, Mapping[str, List[ValueObject]]], ignore_warnings: bool = False, raise_errors: bool = True, extend_adj: bool = True, clobber: bool = True)[source]

Deserialize and validate parameter adjustments. params_or_path can be a file path or a dict that has not been fully deserialized. The adjusted values replace the current values stored in the corresponding parameter attributes.

If clobber is True and extend mode is on, then all future values for a given parameter be replaced by the values in the adjustment. If clobber is False and extend mode is on, then user-defined values will not be replaced by values in this adjustment. Only values that were added automatically via the extend method will be updated.

This simply calls a private method _adjust to do the upate. Creating this layer on top of _adjust makes it easy to subclass Parameters and implement custom adjust methods.

Parameters

  • params_or_path: Adjustment that is either a dict, file path, or JSON string.

  • ignore_warnings: Whether to raise an error on warnings or ignore them.

  • raise_errors: Either raise errors or simply store the error messages.

  • extend_adj: If in extend mode, this is a flag indicating whether to extend the adjustment values or not.

  • clobber: If in extend mode, this is a flag indicating whether to override all values, including user-defined values, or to only override automatically created values.

Returns

  • params: Parsed, validated parameters.

Raises

  • marshmallow.exceptions.ValidationError if data is not valid.

  • ParameterUpdateException if label values do not match at least one existing value item’s corresponding label values.

clear_state()[source]

Reset the state of the Parameters instance.

extend(label: Optional[str] = None, label_values: Optional[List[Any]] = None, params: Optional[List[str]] = None, raise_errors: bool = True, ignore_warnings: bool = False)[source]

Extend parameters along label.

Parameters

  • label: Label to extend values along. By default, label_to_extend is used.

  • label_values: values of label to extend. By default, this is a grid created from the valid values of label_to_extend.

  • params: Parameters to extend. By default, all parameters are extended.

  • raise_errors: Whether adjust should raise or store errors.

  • ignore_warnings: Whether adjust should raise or ignore warnings.

Raises

  • InconsistentLabelsException: Value objects do not have consistent labels.

extend_func(param: str, extend_vo: ValueObject, known_vo: ValueObject, extend_grid: List, label: str)[source]

Function for applying indexing rates to parameter values as they are extended. Projects may implement their own extend_func by overriding this one. Projects need to write their own indexing_rate method for returning the correct indexing rate for a given parameter and value of label.

Returns

  • extend_vo: New ValueObject.

from_array(param, array=None, **labels)[source]

Convert NumPy array to a Value object.

Parameters

  • param: Name of parameter to convert to a list of value objects.

  • array: Optionally, provide a NumPy array to convert into a list of value objects. If not specified, the value at self.param will be used.

  • labels: Optionally, override instance state.

Returns

  • List of ValueObjects

Raises

  • InconsistentLabelsException: Value objects do not have consistent labels.

parse_labels(**labels)[source]

Parse and validate labels.

Returns

  • Parsed and validated labels.

read_params(params_or_path: Union[str, pathlib.Path, IO, Dict[str, any]], storage_options: Optional[Dict[str, Any]] = None)[source]

Read JSON data of the form:

  • Python dict.

  • JSON string.

  • Local file path.

  • Any URL readable by fsspec. For example:
    • s3: s3://paramtools-test/defaults.json

    • gcs: gs://paramtools-dev/defaults.json

    • http: https://somedomain.com/defaults.json

    • github: github://PSLmodels:ParamTools@master/paramtools/tests/defaults.json

Returns - params: Python Dict created from JSON file.

set_state(**labels)[source]

Sets state for the Parameters instance. The _state, label_grid, and parameter attributes are all updated with the new state.

Use the view_state method to inspect the current state of the instance, and use the clear_state method to revert to the default state.

Raises

  • ValidationError if the labels kwargs contain labels that are not specified in schema.json or if the label values fail the validator set for the corresponding label in schema.json.

sort_values(data=None, has_meta_data=True)[source]

Sort value objects for all parameters in data according to the order specified in schema.

Parameters

  • data: Parameter data to be sorted. This should be a dict of parameter names and values. If data is None, the current values will be sorted.

  • has_meta_data: Whether parameter values should be accessed directly or through the “value” attribute.

Returns

  • Sorted data.

specification(use_state: bool = True, meta_data: bool = False, include_empty: bool = False, serializable: bool = False, sort_values: bool = False, **labels)[source]

Query value(s) of all parameters along labels specified in labels.

Parameters

  • use_state: Use the instance’s state for the select operation.

  • meta_data: Include information like the parameter description and title.

  • include_empty: Include parameters that do not meet the label query.

  • serializable: Return data that is compatible with json.dumps.

  • sort_values: Sort values by the label order.

Returns

  • dict of parameter names and data.

to_array(param, **labels)[source]

Convert a Value object to an n-labelal array. The list of Value objects must span the specified parameter space. The parameter space is defined by inspecting the label validators in schema.json and the state attribute of the Parameters instance.

Parameters
  • param: Name of parameter that will be used to create array.

  • labels: Optionally, override instance state.

Returns

  • arr: NumPy array created from list of value objects.

Raises

  • InconsistentLabelsException: Value objects do not have consistent labels.

  • SparseValueObjectsException: Value object does not span the entire space specified by the Order object.

  • ParamToolsError: Parameter is an array type and has labels. This is not supported by ParamTools when using array_first.

transaction(defer_validation=True, raise_errors=False, ignore_warnings=False)[source]

Rollback any changes to parameter state after the context block closes.

import paramtools

class Params(paramtools.Parameters):
    defaults = {
        "min_param": {
            "title": "Min param",
            "description": "Must be less than 'max_param'",
            "type": "int",
            "value": 2,
            "validators": {
                "range": {"max": "max_param"}
            }
        },
        "max_param": {
            "title": "Max param",
            "type": "int",
            "value": 3
        }
    }

params = Params()
with params.transaction():
    params.adjust({"min_param": 4})
    params.adjust({"max_param": 5})
Parameters:
  • defer_validation: Defer schema-level validation until the end of the block.

  • ignore_warnings: Whether to raise an error on warnings or ignore them.

  • raise_errors: Either raise errors or simply store the error messages.

validate(params, raise_errors=True, ignore_warnings=False)[source]

Validate parameter adjustment without modifying existing values.

For example, validate the current parameter values:

params.validate(
    params.specification(use_state=False)
)
Parameters:
  • params: Parameters to validate.

  • ignore_warnings: Whether to raise an error on warnings or ignore them.

  • raise_errors: Either raise errors or simply store the error messages.

view_state()[source]

Access the label state of the Parameters instance.

Values

class paramtools.values.Values(values: List[ValueObject], keyfuncs: Optional[Dict[str, Any]] = None, skls: Optional[Dict[str, paramtools.sorted_key_list.SortedKeyList]] = None, index: Optional[List[Any]] = None)[source]

The Values class is used to query and update parameter values.

For more information, checkout the Viewing Data docs.

__and__(queryresult: paramtools.values.QueryResult)[source]

Combine queries with logical ‘and’:

my_param = params.sel["my_param]
(my_param["my_label"] == 5) & (my_param["oth_label"] == "hello")
__or__(queryresult: paramtools.values.QueryResult)[source]

Combine queries with logical ‘or’:

my_param = params.sel["my_param]
(my_param["my_label"] == 5) | (my_param["oth_label"] == "hello")
eq(strict=True, **labels)[source]

Returns values that match the given label:

params.sel["my_param"].eq(my_label=5)
params.sel["my_param"]["my_label"] == 5
gt(strict=True, **labels)[source]

Returns values that have label values greater than the label value:

params.sel["my_param"].gt(my_label=5)
params.sel["my_param"]["my_label"] > 5
property isel

Select values by their index:

params.sel["my_param"].isel[0]
params.sel["my_param"].isel[:5]
isin(strict=True, **labels)[source]

Returns values that have label values less than or equal to the label value:

params.sel["my_param"].isin(my_label=[5, 6])
lt(strict=True, **labels)[source]

Returns values that have label values less than the label value:

params.sel["my_param"].lt(my_label=5)
params.sel["my_param"]["my_label"] < 5
lte(strict=True, **labels)[source]

Returns values that have label values less than or equal to the label value:

params.sel["my_param"].lte(my_label=5)
params.sel["my_param"]["my_label"] <= 5
ne(strict=True, **labels)[source]

Returns values that do match the given label:

params.sel["my_param"].ne(my_label=5)
params.sel["my_param"]["my_label"] != 5