Skip to content

Parameters

albert.collections.parameters.ParameterCollection

ParameterCollection(*, session: AlbertSession)

Bases: BaseCollection

Manage Parameters in the Albert platform.

A Parameter (ID format PRM..., e.g. "PRM9999999") is the definition of a single condition or input variable used when running experiments, such as Temperature, Spin Speed, or Instrument. It is often called an "indirect variable": the Parameter itself only names the variable, and its actual value and unit are fixed to a setpoint later, inside a Workflow.

Parameters are the building blocks of Parameter Groups (ParameterGroup) and form the parameter side of Data Templates (DataTemplate).

This collection is accessed as client.parameters.

Example

from albert import Albert
client = Albert()
param = client.parameters.get_by_id(id="PRM9999999")
param.name
# 'Temperature'

Parameters:

Name Type Description Default
session AlbertSession

The authenticated Albert session used for API calls.

required

Attributes:

Name Type Description
base_path str

The base API route for parameter requests.

Methods:

Name Description
create

Create a new parameter.

get_or_create

Return the existing parameter matching by name, or create it.

get_by_id

Get a single parameter by its ID.

get_all

Search for parameters by name or ID.

update

Update an existing parameter.

delete

Delete a parameter by its ID.

Parameters:

Name Type Description Default
session AlbertSession

The authenticated Albert session used for API calls.

required
Source code in src/albert/collections/parameters.py
def __init__(self, *, session: AlbertSession):
    """Initialize a ParameterCollection.

    Parameters
    ----------
    session : AlbertSession
        The authenticated Albert session used for API calls.
    """
    super().__init__(session=session)
    self.base_path = f"/api/{ParameterCollection._api_version}/parameters"

base_path

base_path = (
    f"/api/{ParameterCollection._api_version}/parameters"
)

get_by_id

get_by_id(*, id: ParameterId) -> Parameter

Get a single parameter by its ID.

To find parameters without knowing their IDs, use get_all.

Example

param = client.parameters.get_by_id(id="PRM9999999")
param.name
# 'Temperature'

Parameters:

Name Type Description Default
id ParameterId

The Parameter ID (format PRM..., e.g. "PRM9999999").

required

Returns:

Type Description
Parameter

The fully populated parameter.

Source code in src/albert/collections/parameters.py
@validate_call
def get_by_id(self, *, id: ParameterId) -> Parameter:
    """Get a single parameter by its ID.

    To find parameters without knowing their IDs, use [`get_all`][albert.collections.parameters.ParameterCollection.get_all].

    !!! example
        ```python
        param = client.parameters.get_by_id(id="PRM9999999")
        param.name
        # 'Temperature'
        ```

    Parameters
    ----------
    id : ParameterId
        The Parameter ID (format ``PRM...``, e.g. ``"PRM9999999"``).

    Returns
    -------
    Parameter
        The fully populated parameter.
    """
    url = f"{self.base_path}/{id}"
    response = self.session.get(url)
    return Parameter(**response.json())

create

create(*, parameter: Parameter) -> Parameter

Create a new parameter.

This registers a new condition or input variable (e.g. Temperature or Spin Speed) that can then be used in Parameter Groups and Data Templates. To avoid creating duplicates when a parameter of the same name may already exist, use get_or_create instead.

Example

from albert.resources.parameters import Parameter
param = client.parameters.create(parameter=Parameter(name="Spin Speed"))
param.id
# 'PRM9999999'

Parameters:

Name Type Description Default
parameter Parameter

The parameter to create. Only name is required.

required

Returns:

Type Description
Parameter

The newly created parameter, populated with its assigned Parameter ID.

Source code in src/albert/collections/parameters.py
def create(self, *, parameter: Parameter) -> Parameter:
    """Create a new parameter.

    This registers a new condition or input variable (e.g. Temperature or Spin
    Speed) that can then be used in Parameter Groups and Data Templates. To
    avoid creating duplicates when a parameter of the same name may already
    exist, use [`get_or_create`][albert.collections.parameters.ParameterCollection.get_or_create] instead.

    !!! example
        ```python
        from albert.resources.parameters import Parameter
        param = client.parameters.create(parameter=Parameter(name="Spin Speed"))
        param.id
        # 'PRM9999999'
        ```

    Parameters
    ----------
    parameter : Parameter
        The parameter to create. Only ``name`` is required.

    Returns
    -------
    Parameter
        The newly created parameter, populated with its assigned Parameter ID.
    """
    response = self.session.post(
        self.base_path,
        json=parameter.model_dump(by_alias=True, exclude_none=True, mode="json"),
    )
    return Parameter(**response.json())

get_or_create

get_or_create(*, parameter: Parameter) -> Parameter

Return the existing parameter matching by name, or create it.

Matches an existing parameter by exact name. If a match is found, it is returned unchanged; otherwise a new parameter is created via create. Use this to avoid creating duplicate parameters.

Example

from albert.resources.parameters import Parameter
param = client.parameters.get_or_create(parameter=Parameter(name="Temperature"))
param.id
# 'PRM9999999'

Parameters:

Name Type Description Default
parameter Parameter

The parameter to get or create. Matched on name.

required

Returns:

Type Description
Parameter

The existing or newly created parameter.

Source code in src/albert/collections/parameters.py
def get_or_create(self, *, parameter: Parameter) -> Parameter:
    """Return the existing parameter matching by name, or create it.

    Matches an existing parameter by exact ``name``. If a match is found, it is
    returned unchanged; otherwise a new parameter is created via [`create`][albert.collections.parameters.ParameterCollection.create].
    Use this to avoid creating duplicate parameters.

    !!! example
        ```python
        from albert.resources.parameters import Parameter
        param = client.parameters.get_or_create(parameter=Parameter(name="Temperature"))
        param.id
        # 'PRM9999999'
        ```

    Parameters
    ----------
    parameter : Parameter
        The parameter to get or create. Matched on ``name``.

    Returns
    -------
    Parameter
        The existing or newly created parameter.
    """
    for match in self.get_all(names=parameter.name, exact_match=False):
        if match.name == parameter.name:
            logging.warning(
                f"Parameter with name {parameter.name} already exists. Returning existing parameter."
            )
            return match
    return self.create(parameter=parameter)

delete

delete(*, id: ParameterId) -> None

Delete a parameter by its ID.

This permanently removes the parameter.

Example

client.parameters.delete(id="PRM9999999")

Parameters:

Name Type Description Default
id ParameterId

The Parameter ID to delete (format PRM...).

required

Returns:

Type Description
None
Source code in src/albert/collections/parameters.py
@validate_call
def delete(self, *, id: ParameterId) -> None:
    """Delete a parameter by its ID.

    This permanently removes the parameter.

    !!! example
        ```python
        client.parameters.delete(id="PRM9999999")
        ```

    Parameters
    ----------
    id : ParameterId
        The Parameter ID to delete (format ``PRM...``).

    Returns
    -------
    None
    """
    url = f"{self.base_path}/{id}"
    self.session.delete(url)

get_all

get_all(
    *,
    ids: list[ParameterId] | None = None,
    names: str | list[str] = None,
    exact_match: bool = False,
    order_by: OrderBy = DESCENDING,
    start_key: str | None = None,
    max_items: int | None = None,
) -> Iterator[Parameter]

Search for parameters, optionally filtered by name or ID.

Results are returned as a lazily paginated iterator, so iterating fetches additional pages on demand. With no filters, iterates over all parameters.

Example

for param in client.parameters.get_all(names="Temperature", max_items=10):
    print(param.id, param.name)

Parameters:

Name Type Description Default
ids list[ParameterId]

Restrict results to these Parameter IDs (format PRM...).

None
names str or list[str]

One or more parameter names to filter by.

None
exact_match bool

When True, only parameters whose name matches names exactly are returned. When False (default), name matching is partial.

False
order_by OrderBy

Sort direction. Default OrderBy.DESCENDING.

DESCENDING
start_key str

Pagination key to resume from. Usually left unset.

None
max_items int

Maximum number of items to return in total. If None, iterates over all matches.

None

Returns:

Type Description
Iterator[Parameter]

A lazily paginated iterator of parameters matching the given criteria.

Source code in src/albert/collections/parameters.py
@validate_call
def get_all(
    self,
    *,
    ids: list[ParameterId] | None = None,
    names: str | list[str] = None,
    exact_match: bool = False,
    order_by: OrderBy = OrderBy.DESCENDING,
    start_key: str | None = None,
    max_items: int | None = None,
) -> Iterator[Parameter]:
    """Search for parameters, optionally filtered by name or ID.

    Results are returned as a lazily paginated iterator, so iterating fetches
    additional pages on demand. With no filters, iterates over all parameters.

    !!! example
        ```python
        for param in client.parameters.get_all(names="Temperature", max_items=10):
            print(param.id, param.name)
        ```

    Parameters
    ----------
    ids : list[ParameterId], optional
        Restrict results to these Parameter IDs (format ``PRM...``).
    names : str or list[str], optional
        One or more parameter names to filter by.
    exact_match : bool, optional
        When True, only parameters whose name matches ``names`` exactly are
        returned. When False (default), name matching is partial.
    order_by : OrderBy, optional
        Sort direction. Default ``OrderBy.DESCENDING``.
    start_key : str, optional
        Pagination key to resume from. Usually left unset.
    max_items : int, optional
        Maximum number of items to return in total. If None, iterates over all
        matches.

    Returns
    -------
    Iterator[Parameter]
        A lazily paginated iterator of parameters matching the given criteria.
    """

    def deserialize(items: list[dict]) -> Iterator[Parameter]:
        yield from (Parameter(**item) for item in items)

    params = {
        "orderBy": order_by,
        "parameters": ids,
        "startKey": start_key,
    }
    params["name"] = ensure_list(names)
    params["exactMatch"] = exact_match

    return AlbertPaginator(
        mode=PaginationMode.KEY,
        path=self.base_path,
        session=self.session,
        params=params,
        max_items=max_items,
        deserialize=deserialize,
    )

update

update(*, parameter: Parameter) -> Parameter

Update an existing parameter.

Fetch the parameter (e.g. with get_by_id), modify the updatable fields on the returned object, then pass it here. Only the fields listed in Notes are applied; changes to other fields are ignored.

Example

param = client.parameters.get_by_id(id="PRM9999999")
param.name = "Bath Temperature"
updated = client.parameters.update(parameter=param)
updated.name
# 'Bath Temperature'

Parameters:

Name Type Description Default
parameter Parameter

The parameter to update. Must have a valid id.

required

Returns:

Type Description
Parameter

The updated parameter.

Notes

The following fields can be updated: metadata, name.

Source code in src/albert/collections/parameters.py
def update(self, *, parameter: Parameter) -> Parameter:
    """Update an existing parameter.

    Fetch the parameter (e.g. with [`get_by_id`][albert.collections.parameters.ParameterCollection.get_by_id]), modify the updatable
    fields on the returned object, then pass it here. Only the fields listed in
    Notes are applied; changes to other fields are ignored.

    !!! example
        ```python
        param = client.parameters.get_by_id(id="PRM9999999")
        param.name = "Bath Temperature"
        updated = client.parameters.update(parameter=param)
        updated.name
        # 'Bath Temperature'
        ```

    Parameters
    ----------
    parameter : Parameter
        The parameter to update. Must have a valid ``id``.

    Returns
    -------
    Parameter
        The updated parameter.

    Notes
    -----
    The following fields can be updated: ``metadata``, ``name``.
    """
    existing = self.get_by_id(id=parameter.id)
    payload = self._generate_patch_payload(
        existing=existing,
        updated=parameter,
    )
    payload_dump = payload.model_dump(mode="json", by_alias=True)
    for i, change in enumerate(payload_dump["data"]):
        if not self._is_metadata_item_list(
            existing_object=existing,
            updated_object=parameter,
            metadata_field=change["attribute"],
        ):
            change["operation"] = "update"
            if "newValue" in change and change["newValue"] is None:
                del change["newValue"]
            if "oldValue" in change and change["oldValue"] is None:
                del change["oldValue"]
            payload_dump["data"][i] = change
    if len(payload_dump["data"]) == 0:
        return parameter
    for e in payload_dump["data"]:
        self.session.patch(
            f"{self.base_path}/{parameter.id}",
            json={"data": [e]},
        )
    return self.get_by_id(id=parameter.id)