Skip to content
Merged
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
130 changes: 110 additions & 20 deletions autofit/aggregator/aggregator.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,11 @@
import logging
import os
import zipfile
import zlib
from collections import defaultdict
from pathlib import Path
from shutil import rmtree
from typing import List, Union, Iterator, Optional
from typing import List, Union, Iterator, Optional, Tuple

from autonerves.test_mode import is_test_mode

Expand All @@ -32,6 +33,35 @@

logger = logging.getLogger(__name__)

ON_ERROR_VALUES = ("skip", "raise")
"""
What ``Aggregator.from_directory`` does with an unreadable zip: ``"skip"`` it and
record it in ``Aggregator.errors``, or ``"raise"``.
"""


def _check_on_error(on_error: str):
if on_error not in ON_ERROR_VALUES:
raise ValueError(
f"on_error must be one of {ON_ERROR_VALUES}, not {on_error!r}."
)


ZIP_READ_ERRORS = (zipfile.BadZipFile, EOFError, zlib.error)
"""
What reading one damaged result zip raises: ``BadZipFile`` for a missing or bad
central directory or a CRC mismatch, ``EOFError`` and ``zlib.error`` for a member
truncated or corrupted part-way through.
"""


def _bad_zip_error(zip_path: Path, error: Exception) -> zipfile.BadZipFile:
return zipfile.BadZipFile(
f"File is not a readable zip file ({type(error).__name__}: {error}): \n "
f"{zip_path.parent} \n"
f"{zip_path.name}"
)


class AggregatorGroup:
def __init__(self, groups: ["AggregatorGroup"]):
Expand Down Expand Up @@ -85,20 +115,42 @@ def values(self, name: str, parser=lambda o: o) -> List[List]:
return [group.values(name, parser=parser) for group in self.groups]


def unzip_directory(directory: str):
def unzip_directory(
directory: str, on_error: str = "raise"
) -> List[Tuple[Path, Exception]]:
"""
Unzip all zip files in a directory recursively.

Parameters
----------
directory
The directory searched recursively for zips.
on_error
``"raise"`` (the default) raises on the first unreadable zip; ``"skip"``
logs it, carries on, and returns it among the ``(path, exception)`` pairs.

Returns
-------
The ``(path, exception)`` of every zip that could not be read.
"""
_check_on_error(on_error)

errors = []

for root, _, filenames in os.walk(directory):
for filename in filenames:
if filename.endswith(".zip"):
zip_path = Path(root) / filename
try:
with zipfile.ZipFile(Path(root) / filename, "r") as f:
with zipfile.ZipFile(zip_path, "r") as f:
f.extractall(Path(root) / filename[:-4])
except zipfile.BadZipFile:
raise zipfile.BadZipFile(
f"File is not a zip file: \n " f"{root} \n" f"{filename}"
)
except ZIP_READ_ERRORS as e:
if on_error == "raise":
raise _bad_zip_error(zip_path, e) from e
logger.warning(f"Skipping unreadable zip {zip_path}: {e}")
errors.append((zip_path, e))

return errors


def _is_search_output(root, dirs, filenames) -> bool:
Expand Down Expand Up @@ -131,6 +183,7 @@ def __init__(
search_outputs: List[SearchOutput],
grid_search_outputs: List[GridSearchOutput],
temporary_directory: Optional[TemporaryExtraction] = None,
errors: Optional[List[Tuple[Path, Exception]]] = None,
):
"""
Class to aggregate phase results for all subdirectories in a given directory.
Expand All @@ -144,9 +197,12 @@ def __init__(
``from_directory`` was called with ``unzip_temporary=True``. Held so
``close`` can remove it eagerly; the search outputs keep it alive
regardless.
errors
The ``(path, exception)`` of every output ``from_directory`` could not
read and skipped (``on_error="skip"``), exposed as ``errors``.
"""
if len(search_outputs) > 20:
print(
logger.info(
"When aggregating many searches it can be more efficient to use the database.\n"
"Checkout the database cookbook at this URL: "
"https://pyautofit.readthedocs.io/en/latest/cookbooks/database.html"
Expand All @@ -156,6 +212,7 @@ def __init__(
# Set here rather than lazily: ``__getattr__`` returns an
# ``AttributePredicate`` for any name it does not find.
self._temporary_directory = temporary_directory
self.errors = list(errors or [])

def grid_searches(self):
"""
Expand All @@ -180,6 +237,7 @@ def from_directory(
completed_only=False,
reference: Optional[dict] = None,
unzip_temporary: bool = False,
on_error: str = "skip",
) -> "Aggregator":
"""
Aggregate phase results for all subdirectories in a given directory.
Expand Down Expand Up @@ -210,14 +268,21 @@ def from_directory(
beside it and carries a ``.completed`` file still uses that directory and is not extracted
again; one whose sibling directory has no ``.completed`` file is extracted, because such a
directory is written after the search was archived and does not stand for the search.
on_error
What to do with a zip that cannot be read (``ZIP_READ_ERRORS``): ``"skip"`` (the default) logs
a warning, leaves it out and records ``(path, exception)`` in the returned aggregator's
``errors``, so one corrupt archive does not hide every other result; ``"raise"`` raises.

Returns
-------
An aggregator whose search outputs are ordered by path, so that the same results tree gives
the same order on every machine regardless of the filesystem's directory-entry order.
"""
print("Aggregator loading search_outputs... could take some time.")
_check_on_error(on_error)

logger.info("Aggregator loading search_outputs... could take some time.")

errors = []
temporary_directory = None
temporary_roots = []
incomplete_count = 0
Expand Down Expand Up @@ -274,15 +339,21 @@ def scan(scan_directory, extract_temporary=False, owner=None):
)
if extract_temporary:
extracted = temporary_path(zip_path, scan_directory)
existed = extracted.exists()
try:
with zipfile.ZipFile(zip_path, "r") as f:
f.extractall(extracted)
except zipfile.BadZipFile:
raise zipfile.BadZipFile(
f"File is not a zip file: \n "
f"{root} \n"
f"{filename}"
except ZIP_READ_ERRORS as e:
if on_error == "raise":
raise _bad_zip_error(zip_path, e) from e
logger.warning(
f"Aggregator: skipping unreadable zip {zip_path}: {e}"
)
errors.append((zip_path, e))
if not existed:
# A partial extraction is not a search output.
rmtree(extracted, ignore_errors=True)
continue
if extract_temporary:
# Outside the tree being walked, so it is scanned separately.
temporary_roots.append(extracted)
Expand Down Expand Up @@ -371,31 +442,44 @@ def scan_all(scan_directory):
search_outputs, grid_search_outputs = scan_all(test_mode_directory)

if len(search_outputs) == 0:
print(f"\nNo search_outputs found in {directory}\n")
# Loud: an empty aggregator otherwise flows on into empty tables and
# plots that look like a result.
logger.warning(
f"Aggregator found no search outputs in {directory} "
f"(completed_only={completed_only}, unzip_temporary={unzip_temporary}, "
f"excluded as incomplete={incomplete_count}, unreadable={len(errors)})."
)
else:
print(
f"\n A total of {str(len(search_outputs))} search_outputs and results were found."
logger.info(
f"A total of {str(len(search_outputs))} search_outputs and results were found."
)

# A search dropped for having no ``.completed`` file is invisible in the
# count above, so a run that aggregates a fraction of its searches looks
# like a complete one. Say how many were left out.
if completed_only and incomplete_count > 0:
print(
f" {incomplete_count} further search_outputs were excluded because "
logger.warning(
f"{incomplete_count} further search_outputs were excluded because "
f"they have no .completed file."
)

if errors:
logger.warning(
f"{len(errors)} unreadable output(s) were skipped; see Aggregator.errors."
)

return cls(
search_outputs,
grid_search_outputs,
temporary_directory=temporary_directory,
errors=errors,
)

def add_directory(
self,
directory: Union[str, Path],
unzip_temporary: bool = False,
on_error: str = "skip",
):
"""
Add a directory to the aggregator.
Expand All @@ -408,13 +492,17 @@ def add_directory(
If `True` zips are extracted into a temporary directory that is cleaned
up automatically, as in ``from_directory``. The added search outputs
keep that directory alive; ``close`` does not remove it.
on_error
As in ``from_directory``; skipped outputs are added to ``errors``.
"""
aggregator = Aggregator.from_directory(
directory,
unzip_temporary=unzip_temporary,
on_error=on_error,
)
self.search_outputs.extend(aggregator.search_outputs)
self.grid_search_outputs.extend(aggregator.grid_search_outputs)
self.errors.extend(aggregator.errors)

def close(self):
"""
Expand Down Expand Up @@ -467,6 +555,7 @@ def __getitem__(self, item: Union[slice, int]) -> Union["Aggregator", SearchOutp
return Aggregator(
self.search_outputs[item],
self.grid_search_outputs,
errors=self.errors,
)
return self.search_outputs[item]

Expand Down Expand Up @@ -500,10 +589,11 @@ def query(self, *predicates) -> "Aggregator":
for predicate in predicates:
search_outputs = predicate.filter(search_outputs)
search_outputs = list(search_outputs)
print(f"Filter found a total of {str(len(search_outputs))} results")
logger.info(f"Filter found a total of {str(len(search_outputs))} results")
return Aggregator(
search_outputs=list(search_outputs),
grid_search_outputs=self.grid_search_outputs,
errors=self.errors,
)

def values(self, name: str, parser=lambda o: o) -> Iterator:
Expand Down
Loading
Loading