Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add check to determine if graph uses all avaliable parameters #86

Closed
wants to merge 3 commits into from
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
44 changes: 39 additions & 5 deletions src/sciline/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,20 @@ def _is_compatible_type_tuple(
return True


def _qualname(obj: Any) -> Any:
return (
obj.__qualname__ if hasattr(obj, '__qualname__') else obj.__class__.__qualname__
)


def _kind_of_provider(p: Callable[..., Any]) -> str:
if _qualname(p) == f'{_qualname(Pipeline.__setitem__)}.<locals>.<lambda>':
return 'parameter'
if _qualname(p) == f'{_qualname(Pipeline.set_param_table)}.<locals>.<lambda>':
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will it be better to make a dummy Pipeline with a parameter and a table
and retrieve their names, and use them to check these instead?

Or if you add the passing case unit test I mentioned, it might be fine like this.

Copy link
Contributor Author

@jokasimr jokasimr Dec 15, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't quite understand what you mean. Do you mean to compute the expected _qualnames for each of the different kinds of providers, instead of hardcoding something like f'{_qualname(Pipeline.set_param_table)}.<locals>.<lambda>'?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No sth like..

_DUMMY_PIPELINE = sl.Pipeline(params={int: 0})
_PARAMETER_PROVIDER_NAME = _DUMMY_PIPELINE._get_provider(int)[0].__qualname__

return 'table'
return 'function'


def _bind_free_typevars(tp: TypeVar | Key, bound: Dict[TypeVar, Key]) -> Key:
if isinstance(tp, TypeVar):
if (result := bound.get(tp)) is None:
Expand Down Expand Up @@ -642,18 +656,18 @@ def _build_series(
return graph

@overload
def compute(self, tp: Type[T]) -> T:
def compute(self, tp: Type[T], check: bool = ...) -> T:
...

@overload
def compute(self, tp: Iterable[Type[T]]) -> Dict[Type[T], T]:
def compute(self, tp: Iterable[Type[T]], check: bool = ...) -> Dict[Type[T], T]:
...

@overload
def compute(self, tp: Item[T]) -> T:
def compute(self, tp: Item[T], check: bool = ...) -> T:
...

def compute(self, tp: type | Iterable[type] | Item[T]) -> Any:
def compute(self, tp: type | Iterable[type] | Item[T], check: bool = False) -> Any:
"""
Compute result for the given keys.

Expand All @@ -665,7 +679,7 @@ def compute(self, tp: type | Iterable[type] | Item[T]) -> Any:
Type to compute the result for.
Can be a single type or an iterable of types.
"""
return self.get(tp).compute()
return self.get(tp, check=check).compute()

def visualize(
self, tp: type | Iterable[type], **kwargs: Any
Expand All @@ -691,6 +705,7 @@ def get(
*,
scheduler: Optional[Scheduler] = None,
handler: Optional[ErrorHandler] = None,
check: bool = False,
) -> TaskGraph:
"""
Return a TaskGraph for the given keys.
Expand All @@ -710,6 +725,8 @@ def get(
During development and debugging it can be helpful to use a handler that
raises an exception only when the graph is computed. This can be achieved
by passing :py:class:`HandleAsComputeTimeException` as the handler.
check:
Checks if the constructed graph uses all available parameters.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In #43, detecting missing providers was also mentioned, so maybe we need a more specific name for unused parameters check here.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, we need a more meaningful name.

"""
handler = handler or HandleAsBuildTimeException()
if _is_multiple_keys(keys):
Expand All @@ -719,6 +736,23 @@ def get(
graph.update(self.build(t, handler=handler))
else:
graph = self.build(keys, handler=handler) # type: ignore[arg-type]

if check:
all_providers = chain(
(
(p[c], v)
for p in self._subproviders
for c, v in self._subproviders[p].items()
),
((p, v) for p, v in self._providers.items()),
)

for p, v in all_providers:
if p not in graph and _kind_of_provider(v) == 'parameter':
raise RuntimeError(
'Graph was expected to use all available parameters.'
)
Comment on lines +740 to +754
Copy link
Member

@SimonHeybrock SimonHeybrock Dec 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we take a step back, I am not sure this is sufficiently capturing the problem. In general, I think what we want to do is check whether a graph is connected, I suppose? Raising errors about individual disconnected pieces may not be meaningful?

Instead of the check flag and handling things via exceptions, would it be better to return some list (or other data structure) of disconnected pieces of the graph? This might be a separate method, instead of extending the compute and get methods with keyword args.


return TaskGraph(
graph=graph, keys=keys, scheduler=scheduler # type: ignore[arg-type]
)
Expand Down
10 changes: 10 additions & 0 deletions tests/pipeline_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -917,3 +917,13 @@ def func(x: int) -> float:
graph = pipeline.get(float, handler=sl.HandleAsComputeTimeException())
with pytest.raises(sl.UnsatisfiedRequirement):
graph.compute()


def test_pipeline_with_unused_parameter_raises_if_check() -> None:
Unused = NewType('Unused', str)
pipeline = sl.Pipeline([int_to_float, make_int])
assert pipeline.compute(float, check=True) == 1.5
pipeline[Unused] = 'Should raise'
with pytest.raises(RuntimeError):
assert pipeline.compute(float, check=True) == 1.5
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you also add a test that pass,
even if the compute passes with the check=True?

assert pipeline.compute(float) == 1.5
Loading