Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions ax/analysis/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,17 @@
# pyre-strict

from enum import Enum
from logging import Logger
from typing import Optional, Protocol

import pandas as pd
from ax.core.experiment import Experiment
from ax.modelbridge.generation_strategy import GenerationStrategy
from ax.utils.common.base import Base
from ax.utils.common.logger import get_logger
from ax.utils.common.result import Err, ExceptionE, Ok, Result

logger: Logger = get_logger(__name__)


class AnalysisCardLevel(Enum):
Expand Down Expand Up @@ -88,3 +93,33 @@ def compute(
# experiment.fetch_data() to avoid unintential data fetching within the report
# generation.
...

def compute_result(
self,
experiment: Optional[Experiment] = None,
generation_strategy: Optional[GenerationStrategy] = None,
) -> Result[AnalysisCard, ExceptionE]:
"""
Utility method to compute an AnalysisCard as a Result. This can be useful for
computing many Analyses at once and handling Exceptions later.
"""

try:
card = self.compute(
experiment=experiment, generation_strategy=generation_strategy
)
return Ok(value=card)
except Exception as e:
logger.error(f"Failed to compute {self}: {e}")

return Err(
value=ExceptionE(
message=f"Failed to compute {self}",
exception=e,
)
)

def __str__(self) -> str:
args = ", ".join([f"{key}={value}" for key, value in self.__dict__.items()])

return f"{self.__class__.__name__}({args})"
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def compute(
fig = _prepare_plot(df=df, metric_name=metric_name)

return PlotlyAnalysisCard(
name=self.__class__.__name__,
name=str(self),
title=f"Parallel Coordinates for {metric_name}",
subtitle="View arm parameterizations with their respective metric values",
level=AnalysisCardLevel.HIGH,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def test_compute(self) -> None:
analysis.compute()

card = analysis.compute(experiment=experiment)
self.assertEqual(card.name, "ParallelCoordinatesPlot")
self.assertEqual(card.name, "ParallelCoordinatesPlot(metric_name=branin)")
self.assertEqual(card.title, "Parallel Coordinates for branin")
self.assertEqual(
card.subtitle,
Expand Down
4 changes: 1 addition & 3 deletions ax/core/metric.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,7 @@

@dataclass(frozen=True)
class MetricFetchE:
# NOTE/TODO[mpolson64]: This could probably be generalized to a
# `PythonExceptionE` class in the future. Let's do our best to avoid
# reinventing the wheel in the next `Result` use case in Ax.
# TODO[mpolson64] Replace this with ExceptionE

message: str
exception: Optional[Exception]
Expand Down
35 changes: 35 additions & 0 deletions ax/utils/common/result.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@

from __future__ import annotations

import traceback

from abc import ABC, abstractmethod, abstractproperty
from functools import reduce

from typing import Any, Callable, cast, Generic, NoReturn, Optional, TypeVar, Union

Expand Down Expand Up @@ -258,3 +261,35 @@ class UnwrapError(Exception):
"""

pass


class ExceptionE:
"""
A class that holds an Exception and can be used as the E type in Result[T, E].
"""

message: str
exception: Exception

def __init__(self, message: str, exception: Exception) -> None:
self.message = message
self.exception = exception

def __repr__(self) -> str:
return (
f'ExceptionE(message="{self.message}", exception={self.exception})\n'
f"with Traceback:\n {self.tb_str()}"
)

def tb_str(self) -> Optional[str]:
if self.exception is None:
return None

return reduce(
lambda left, right: left + right,
traceback.format_exception(
None, self.exception, self.exception.__traceback__
),
)

pass