Skip to content

Result Sets

result_set

Result set management for creating and managing subsets of optimization data.

Result sets allow users to create named subsets of optimization results for focused analysis, comparison, and decision making.

Classes

SetOperation

Bases: BaseModel

Record of an operation that created or modified a set.

ResultSet

Bases: BaseModel

A named subset of optimization results.

Result sets reference indices in the parent OptimizationResult and can be created through filtering, manual selection, or algorithmic identification (e.g., Pareto front detection).

Functions
__len__
__len__() -> int

Return number of points in set.

Source code in optiscope/core/result_set.py
def __len__(self) -> int:
    """Return number of points in set."""
    return len(self.indices)
add_operation
add_operation(operation: str, parameters: dict[str, Any], description: str | None = None) -> None

Record an operation in the set's history.

Parameters:

Name Type Description Default
operation str

Type of operation

required
parameters dict[str, Any]

Operation parameters

required
description str | None

Optional description

None
Source code in optiscope/core/result_set.py
def add_operation(
    self, operation: str, parameters: dict[str, Any], description: str | None = None
) -> None:
    """
    Record an operation in the set's history.

    Args:
        operation: Type of operation
        parameters: Operation parameters
        description: Optional description
    """
    self.operations.append(
        SetOperation(operation=operation, parameters=parameters, description=description)
    )
union
union(other: ResultSet, name: str) -> ResultSet

Create a new set as the union of this set and another.

Parameters:

Name Type Description Default
other ResultSet

Another ResultSet

required
name str

Name for the new set

required

Returns:

Type Description
ResultSet

New ResultSet containing union of indices

Source code in optiscope/core/result_set.py
def union(self, other: ResultSet, name: str) -> ResultSet:
    """
    Create a new set as the union of this set and another.

    Args:
        other: Another ResultSet
        name: Name for the new set

    Returns:
        New ResultSet containing union of indices
    """
    union_indices = sorted(set(self.indices) | set(other.indices))
    new_set = ResultSet(
        name=name,
        indices=union_indices,
        created_by=f"{self.created_by}+{other.created_by}",
        description=f"Union of '{self.name}' and '{other.name}'",
        color=None,
        parent_set=None,
    )
    new_set.add_operation(
        "union",
        {"sets": [self.name, other.name]},
        f"Union of {len(self)} and {len(other)} points",
    )
    return new_set
intersection
intersection(other: ResultSet, name: str) -> ResultSet

Create a new set as the intersection of this set and another.

Parameters:

Name Type Description Default
other ResultSet

Another ResultSet

required
name str

Name for the new set

required

Returns:

Type Description
ResultSet

New ResultSet containing intersection of indices

Source code in optiscope/core/result_set.py
def intersection(self, other: ResultSet, name: str) -> ResultSet:
    """
    Create a new set as the intersection of this set and another.

    Args:
        other: Another ResultSet
        name: Name for the new set

    Returns:
        New ResultSet containing intersection of indices
    """
    intersect_indices = sorted(set(self.indices) & set(other.indices))
    new_set = ResultSet(
        name=name,
        indices=intersect_indices,
        created_by=f"{self.created_by}+{other.created_by}",
        description=f"Intersection of '{self.name}' and '{other.name}'",
        color=None,
        parent_set=None,
    )
    new_set.add_operation(
        "intersection",
        {"sets": [self.name, other.name]},
        f"Intersection of {len(self)} and {len(other)} points",
    )
    return new_set
difference
difference(other: ResultSet, name: str) -> ResultSet

Create a new set as the difference (this - other).

Parameters:

Name Type Description Default
other ResultSet

Another ResultSet

required
name str

Name for the new set

required

Returns:

Type Description
ResultSet

New ResultSet containing difference of indices

Source code in optiscope/core/result_set.py
def difference(self, other: ResultSet, name: str) -> ResultSet:
    """
    Create a new set as the difference (this - other).

    Args:
        other: Another ResultSet
        name: Name for the new set

    Returns:
        New ResultSet containing difference of indices
    """
    diff_indices = sorted(set(self.indices) - set(other.indices))
    new_set = ResultSet(
        name=name,
        indices=diff_indices,
        created_by=self.created_by,
        description=f"Difference '{self.name}' - '{other.name}'",
        color=None,
        parent_set=None,
    )
    new_set.add_operation(
        "difference",
        {"sets": [self.name, other.name]},
        f"Removed {len(other)} points from {len(self)} points",
    )
    return new_set
filter_by_mask
filter_by_mask(mask: ndarray, name: str, description: str | None = None) -> ResultSet

Create a new set by filtering current set with a boolean mask.

Parameters:

Name Type Description Default
mask ndarray

Boolean mask array (length must match this set)

required
name str

Name for new set

required
description str | None

Optional description

None

Returns:

Type Description
ResultSet

New filtered ResultSet

Source code in optiscope/core/result_set.py
def filter_by_mask(
    self, mask: np.ndarray, name: str, description: str | None = None
) -> ResultSet:
    """
    Create a new set by filtering current set with a boolean mask.

    Args:
        mask: Boolean mask array (length must match this set)
        name: Name for new set
        description: Optional description

    Returns:
        New filtered ResultSet
    """
    if len(mask) != len(self.indices):
        raise ValueError(f"Mask length {len(mask)} must match set size {len(self.indices)}")

    filtered_indices = [idx for idx, keep in zip(self.indices, mask) if keep]
    new_set = ResultSet(
        name=name,
        indices=filtered_indices,
        created_by=self.created_by,
        parent_set=self.name,
        description=description or f"Filtered from '{self.name}'",
        color=None,
    )
    new_set.add_operation(
        "filter",
        {"parent": self.name, "kept": len(filtered_indices), "total": len(self)},
        f"Filtered to {len(filtered_indices)} points",
    )
    return new_set
to_dict
to_dict() -> dict[str, Any]

Export set as dictionary.

Source code in optiscope/core/result_set.py
def to_dict(self) -> dict[str, Any]:
    """Export set as dictionary."""
    return {
        "name": self.name,
        "indices": self.indices,
        "created_by": self.created_by,
        "created_at": self.created_at.isoformat(),
        "description": self.description,
        "color": self.color,
        "is_locked": self.is_locked,
        "metadata": self.metadata,
        "operations": [op.model_dump(mode="json") for op in self.operations],
        "parent_set": self.parent_set,
        "size": len(self),
    }
from_dict classmethod
from_dict(data: dict[str, Any]) -> ResultSet

Create ResultSet from dictionary.

Source code in optiscope/core/result_set.py
@classmethod
def from_dict(cls, data: dict[str, Any]) -> ResultSet:
    """Create ResultSet from dictionary."""
    # Convert operations
    if "operations" in data:
        data["operations"] = [
            SetOperation(**op) if isinstance(op, dict) else op for op in data["operations"]
        ]

    # Remove computed fields
    data.pop("size", None)

    # Convert datetime strings
    if isinstance(data.get("created_at"), str):
        data["created_at"] = datetime.fromisoformat(data["created_at"])

    return cls(**data)

SetManager

SetManager()

Manager for handling multiple result sets.

Provides utilities for creating, managing, and performing operations on collections of result sets.

Source code in optiscope/core/result_set.py
def __init__(self) -> None:
    self.sets: dict[str, ResultSet] = {}
Functions
add_set
add_set(result_set: ResultSet) -> None

Add a result set to the manager.

Source code in optiscope/core/result_set.py
def add_set(self, result_set: ResultSet) -> None:
    """Add a result set to the manager."""
    if result_set.name in self.sets:
        raise ValueError(f"Set '{result_set.name}' already exists")
    self.sets[result_set.name] = result_set
get_set
get_set(name: str) -> ResultSet

Get a result set by name.

Source code in optiscope/core/result_set.py
def get_set(self, name: str) -> ResultSet:
    """Get a result set by name."""
    if name not in self.sets:
        raise KeyError(f"Set '{name}' not found")
    return self.sets[name]
remove_set
remove_set(name: str) -> None

Remove a result set.

Source code in optiscope/core/result_set.py
def remove_set(self, name: str) -> None:
    """Remove a result set."""
    if name not in self.sets:
        raise KeyError(f"Set '{name}' not found")

    result_set = self.sets[name]
    if result_set.is_locked:
        raise ValueError(f"Cannot remove locked set '{name}'")

    del self.sets[name]
list_sets
list_sets() -> list[str]

List all set names.

Source code in optiscope/core/result_set.py
def list_sets(self) -> list[str]:
    """List all set names."""
    return list(self.sets.keys())
get_all_sets
get_all_sets() -> list[ResultSet]

Get all sets.

Source code in optiscope/core/result_set.py
def get_all_sets(self) -> list[ResultSet]:
    """Get all sets."""
    return list(self.sets.values())
get_sets_by_creator
get_sets_by_creator(created_by: str) -> list[ResultSet]

Get all sets created by a specific module.

Source code in optiscope/core/result_set.py
def get_sets_by_creator(self, created_by: str) -> list[ResultSet]:
    """Get all sets created by a specific module."""
    return [s for s in self.sets.values() if s.created_by == created_by]
clear
clear() -> None

Remove all unlocked sets.

Source code in optiscope/core/result_set.py
def clear(self) -> None:
    """Remove all unlocked sets."""
    self.sets = {name: s for name, s in self.sets.items() if s.is_locked}
to_dict
to_dict() -> dict[str, Any]

Export all sets as dictionary.

Source code in optiscope/core/result_set.py
def to_dict(self) -> dict[str, Any]:
    """Export all sets as dictionary."""
    return {name: s.to_dict() for name, s in self.sets.items()}
from_dict
from_dict(data: dict[str, Any]) -> None

Load sets from dictionary.

Source code in optiscope/core/result_set.py
def from_dict(self, data: dict[str, Any]) -> None:
    """Load sets from dictionary."""
    self.sets = {name: ResultSet.from_dict(set_data) for name, set_data in data.items()}