diff --git a/config.yml b/config.yml index 7fabdff0c..fe7d71338 100644 --- a/config.yml +++ b/config.yml @@ -67,7 +67,7 @@ notebooks: - ipywidgets - tabulate==0.9.0 - mat3ra-utils - - mat3ra-api-client>=2026.11.4.post0 + - mat3ra-api-client[tools]>=2026.11.4.post0 - name: dataframe packages_pyodide: - jinja2 @@ -80,11 +80,11 @@ notebooks: - emfs:/drive/packages/pydantic-2.7.1-py3-none-any.whl - mat3ra-standata - mat3ra-ide - - mat3ra-api-client>=2026.11.4.post0 + - mat3ra-api-client[tools]>=2026.11.4.post0 - requests - mat3ra-ade - mat3ra-mode - - mat3ra-wode + - mat3ra-wode[tools] - mat3ra-prode - name: torch packages_pyodide: diff --git a/pyproject.toml b/pyproject.toml index e47864a68..825154a7e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,7 +24,7 @@ utils_standata = [ "mat3ra-standata", ] api = [ - "mat3ra-api-client>=2026.11.4.post0", + "mat3ra-api-client[tools]>=2026.11.4.post0", ] materials = [ # ase >=3.25.0 is required for supercell to be generated, @@ -43,7 +43,7 @@ workflows = [ "mat3ra-notebooks-utils[materials]", "mat3ra-esse", "mat3ra-mode", - "mat3ra-wode", + "mat3ra-wode[tools]", "mat3ra-ade", "mat3ra-prode", "mat3ra-ide", diff --git a/src/py/mat3ra/notebooks_utils/core/api/auth.py b/src/py/mat3ra/notebooks_utils/core/api/auth.py index 1b88b5e21..d7a0f69c3 100644 --- a/src/py/mat3ra/notebooks_utils/core/api/auth.py +++ b/src/py/mat3ra/notebooks_utils/core/api/auth.py @@ -1,11 +1,17 @@ import asyncio -import os import time import urllib.parse from typing import Any, Awaitable, Callable, Optional -import requests -from mat3ra.api_client import ACCESS_TOKEN_ENV_VAR, CLIENT_ID, SCOPE, APIEnv, build_oidc_base_url +from mat3ra.api_client import CLIENT_ID, SCOPE +from mat3ra.api_client.tools.auth import get_oidc_base_url, request_device_flow_state +from mat3ra.api_client.tools.auth.settings import FORM_HEADERS, REFRESH_TOKEN_ENV_VAR, TOKEN_REQUEST_TIMEOUT_SECONDS +from mat3ra.api_client.tools.auth.token import ( + get_token_data_from_response, + get_token_request_form_data, + request_token_data, + store_token_data_in_environment, +) from ...primitive.environment import is_pyodide_environment from ...pyodide.runtime import run_interruptible_loop_async @@ -15,64 +21,14 @@ except ImportError: pyfetch = None -REFRESH_TOKEN_ENV_VAR = "OIDC_REFRESH_TOKEN" -TOKEN_REQUEST_TIMEOUT_SECONDS = 10 -FORM_HEADERS = {"Content-Type": "application/x-www-form-urlencoded"} - -def get_oidc_base_url() -> str: - env = APIEnv.from_env() - return build_oidc_base_url(env.host, env.port, env.secure) - - -def request_device_flow_state(oidc_base_url: str, client_id: str, scope: str) -> dict: - """ - Request an OAuth/OIDC Device Authorization flow state. - - Args: - oidc_base_url: Base OIDC URL. - client_id: OAuth client identifier for the device flow. - scope: Space-separated scopes to request (e.g. "openid profile email"). - - Returns: - A dict with device_code, user_code, verification_uri_complete, - polling_interval_seconds, expires_in_seconds. - """ - device_response = requests.post( - f"{oidc_base_url}/device/auth", - data={"client_id": client_id, "scope": scope}, - headers={"Content-Type": "application/x-www-form-urlencoded"}, - timeout=10, - ) - device_response.raise_for_status() - device_data = device_response.json() - return { - "device_code": device_data["device_code"], - "user_code": device_data["user_code"], - "verification_uri_complete": device_data.get("verification_uri_complete", device_data["verification_uri"]), - "polling_interval_seconds": int(device_data.get("interval", 5)), - "expires_in_seconds": int(device_data.get("expires_in", 600)), - } - - -def store_token_data_in_environment(token_data: dict) -> None: - os.environ[ACCESS_TOKEN_ENV_VAR] = token_data["access_token"] - if "refresh_token" in token_data: - os.environ[REFRESH_TOKEN_ENV_VAR] = token_data["refresh_token"] - - -def _request_token_data(token_url: str, form_data: dict) -> tuple: - response = requests.post(token_url, data=form_data, headers=FORM_HEADERS, timeout=TOKEN_REQUEST_TIMEOUT_SECONDS) - return response.status_code, response.json() if response.status_code < 500 else {} - - -async def _request_token_data_with_fetch(token_url: str, form_data: dict, abort_signal: Any) -> tuple: +async def _request_token_data_with_fetch(token_url: str, form_data: dict, abort_signal: Any) -> dict: """ - `_request_token_data` through the browser's fetch, which leaves the event loop free while the request is in flight. + `request_token_data` through the browser's fetch, which leaves the event loop free while the request is in flight. """ body = urllib.parse.urlencode(form_data, doseq=True) response = await pyfetch(token_url, method="POST", body=body, headers=FORM_HEADERS, signal=abort_signal) - return response.status, await response.json() if response.status < 500 else {} + return get_token_data_from_response(response.status, await response.json() if response.status < 500 else {}) async def _poll_for_token_data( @@ -84,29 +40,19 @@ async def _poll_for_token_data( ) -> dict: """Polls for the token until the device login is confirmed; in pyodide, ESC stops it at once.""" token_url = f"{oidc_base_url}/token" - form_data = { - "grant_type": "urn:ietf:params:oauth:grant-type:device_code", - "device_code": device_code, - "client_id": client_id, - "redirect_uris": [], - "response_types": [], - "token_endpoint_auth_method": "none", - } + form_data = get_token_request_form_data(client_id, device_code) deadline_seconds = time.time() + expires_in_seconds token_data: dict = {} - def request_token_data(abort_signal: Any) -> Awaitable[tuple]: + def request_token_data_async(abort_signal: Any) -> Awaitable[dict]: if is_pyodide_environment(): return _request_token_data_with_fetch(token_url, form_data, abort_signal) - return asyncio.get_running_loop().run_in_executor(None, _request_token_data, token_url, form_data) + return asyncio.get_running_loop().run_in_executor(None, request_token_data, token_url, form_data) async def poll_step(abort_signal: Any) -> bool: if time.time() >= deadline_seconds: raise Exception("Timeout waiting for authorization.") - status, response_data = await asyncio.wait_for(request_token_data(abort_signal), TOKEN_REQUEST_TIMEOUT_SECONDS) - if status != 200 and status < 500 and response_data.get("error") not in ("authorization_pending", "slow_down"): - raise Exception(f"Device login failed ({status}): {response_data.get('error')}.") - token_data.update(response_data if status == 200 else {}) + token_data.update(await asyncio.wait_for(request_token_data_async(abort_signal), TOKEN_REQUEST_TIMEOUT_SECONDS)) return not token_data await run_interruptible_loop_async( @@ -135,3 +81,14 @@ async def authenticate_oidc( ) store_token_data_in_environment(token_data) return token_data + + +__all__ = [ + "FORM_HEADERS", + "REFRESH_TOKEN_ENV_VAR", + "TOKEN_REQUEST_TIMEOUT_SECONDS", + "authenticate_oidc", + "get_oidc_base_url", + "request_device_flow_state", + "store_token_data_in_environment", +] diff --git a/src/py/mat3ra/notebooks_utils/core/api/token_store.py b/src/py/mat3ra/notebooks_utils/core/api/token_store.py index 17b9f8725..2497bbf8e 100644 --- a/src/py/mat3ra/notebooks_utils/core/api/token_store.py +++ b/src/py/mat3ra/notebooks_utils/core/api/token_store.py @@ -1,20 +1,5 @@ """File-based OIDC token cache storage.""" -import json -import os +from mat3ra.api_client.tools.auth.token import read, write -_FILE_PATH = os.path.join(os.path.expanduser("~"), ".mat3ra", "oidc_token_cache.json") - - -async def read() -> dict: - try: - with open(_FILE_PATH) as f: - return json.load(f) - except (FileNotFoundError, json.JSONDecodeError): - return {} - - -async def write(cache: dict) -> None: - os.makedirs(os.path.dirname(_FILE_PATH), exist_ok=True) - with open(_FILE_PATH, "w") as f: - json.dump(cache, f) +__all__ = ["read", "write"] diff --git a/src/py/mat3ra/notebooks_utils/core/entity/compute/api.py b/src/py/mat3ra/notebooks_utils/core/entity/compute/api.py index 767ec32d8..ff7b78f83 100644 --- a/src/py/mat3ra/notebooks_utils/core/entity/compute/api.py +++ b/src/py/mat3ra/notebooks_utils/core/entity/compute/api.py @@ -1,7 +1,3 @@ -import json -import os +from mat3ra.ide.tools.cluster import get_cluster_name - -def get_cluster_name(name: str = "cluster-001") -> str: - clusters = json.loads(os.environ.get("CLUSTERS", "[]") or "[]") - return clusters[0] if clusters else name +__all__ = ["get_cluster_name"] diff --git a/src/py/mat3ra/notebooks_utils/core/entity/file/api.py b/src/py/mat3ra/notebooks_utils/core/entity/file/api.py index 4be66ac1b..da6e3679f 100644 --- a/src/py/mat3ra/notebooks_utils/core/entity/file/api.py +++ b/src/py/mat3ra/notebooks_utils/core/entity/file/api.py @@ -1,22 +1,8 @@ -def to_object_storage_input(cloud_file: dict) -> dict: - """ - Converts an upload record into an `object_storage` input item for a workflow IO unit. +from mat3ra.wode.tools.unit import to_object_storage_input as _to_object_storage_input - Args: - cloud_file (dict): A record returned by `client.files.upload` (mat3ra-api-client). - Returns: - dict: IO unit input item. The runner fetches it into the job's working directory under - `basename`, which is what makes the user script's relative paths resolve. +def to_object_storage_input(cloud_file: dict) -> dict: + """ + `to_object_storage_input` of mat3ra.wode.tools.unit, returning the IO unit input item as a dict. """ - return { - "type": "object_storage", - "basename": cloud_file["key"].split("/")[-1], - "pathname": "", - "objectData": { - "NAME": cloud_file["key"], - "PROVIDER": cloud_file["provider"], - "CONTAINER": cloud_file["bucket"], - "REGION": cloud_file["region"], - }, - } + return _to_object_storage_input(cloud_file).model_dump(exclude_none=True) diff --git a/src/py/mat3ra/notebooks_utils/core/entity/job/api.py b/src/py/mat3ra/notebooks_utils/core/entity/job/api.py index ca8b7440f..2e76d2b79 100644 --- a/src/py/mat3ra/notebooks_utils/core/entity/job/api.py +++ b/src/py/mat3ra/notebooks_utils/core/entity/job/api.py @@ -1,12 +1,22 @@ import asyncio import json -import re import urllib.parse -import urllib.request -from typing import Any, Awaitable, Dict, Iterable, List, Optional, Union +from typing import Any, Awaitable, List, Optional, Union import requests from mat3ra.api_client import APIClient, JobEndpoints +from mat3ra.api_client.tools.job import MATERIALS_SET_ENTITY_CLASS +from mat3ra.api_client.tools.job import create_job as _create_job +from mat3ra.api_client.tools.job import ( + find_job_for_material, + find_job_for_material_with_property, + save_files, + submit_jobs, +) +from mat3ra.ide.compute import Compute +from mat3ra.made.material import Material +from mat3ra.wode import Workflow +from mat3ra.wode.tools.espresso import get_kgrid_of_job, get_kgrid_query from ....auth import reauthenticate from ....primitive.environment import is_pyodide_environment @@ -16,28 +26,9 @@ except ImportError: pyfetch = None -MATERIALS_SET_ENTITY_CLASS = "Material" DEFAULT_STATUS_TIMEOUT_SECONDS = 30 -def save_files(job_id: str, job_endpoint: JobEndpoints, filename_on_cloud: str, filename_on_disk: str) -> None: - """ - Saves a file to disk, overwriting any files with the same name as filename_on_disk. - - Args: - job_id (str): ID of the job - job_endpoint (JobEndpoints): Job endpoint object from the Exabyte API Client - filename_on_cloud (str): Name of the file on the server - filename_on_disk (str): Name the file will be saved to - """ - files = job_endpoint.list_files(job_id) - file_metadata = next(f for f in files if filename_on_cloud in f["key"]) - signed_url = file_metadata["signedUrl"] - server_response = urllib.request.urlopen(signed_url) - with open(filename_on_disk, "wb") as outp: - outp.write(server_response.read()) - - async def _list_jobs_with_fetch(endpoint: JobEndpoints, query: dict, projection: dict, abort_signal: Any) -> List[dict]: """ `endpoint.list` through the browser's fetch, which leaves the event loop free while the request is in flight. @@ -90,192 +81,43 @@ def request_jobs() -> Awaitable[List[dict]]: return [job["status"] for job in jobs] -def _materials_set_reference(materials_set: Dict[str, Any]) -> Dict[str, str]: - """ - Builds the `_materialsSet` reference a job config expects. - - Mirrors what the job designer sends: the set's ID, the entity class it holds, - and a slug. The platform resolves members from the ID, so `slug` is only a - label — falling back to `name` keeps it readable when the response omits it. - - Args: - materials_set (dict): Materials set document. - - Returns: - dict: The `_materialsSet` reference. - - Raises: - KeyError: If the set document carries neither `slug` nor `name`. - """ - slug = materials_set.get("slug") or materials_set.get("name") - if not slug: - raise KeyError(f"Materials set {materials_set['_id']} has neither 'slug' nor 'name'.") - return { - "_id": materials_set["_id"], - "cls": MATERIALS_SET_ENTITY_CLASS, - "slug": slug, - } - - def create_job( api_client: APIClient, - materials: List[dict], - workflow: dict, + materials: List[Union[Material, dict]], + workflow: Union[Workflow, dict], project_id: str, owner_id: str, prefix: str, - compute: Optional[dict] = None, - materials_set: Optional[Dict[str, Any]] = None, + compute: dict, + materials_set: Optional[dict] = None, tags: Optional[List[str]] = None, -) -> Union[dict, List[dict]]: - """ - Creates jobs using pre-serialised material and workflow dicts. - - Args: - api_client (APIClient): API client instance carrying the authorization context. - materials (list[dict]): Serialised material dicts. - workflow (dict): Serialised workflow dict. - project_id (str): Project ID. - owner_id (str): Account ID. - prefix (str): Job name prefix. - compute (dict, optional): Compute configuration dict. - materials_set (dict, optional): Ordered/unordered materials set document - (same contract as the job designer `_materialsSet`). - tags (list[str], optional): Job tags, e.g. ["charge:-1"]. - - Returns: - dict | list[dict]: Created job(s). - """ - workflow.pop("_id", None) - is_multimaterial = workflow.get("isMultiMaterial", False) - - config: dict = { - "_project": {"_id": project_id}, - "workflow": workflow, - "owner": {"_id": owner_id}, - "name": prefix, - "_material": {"_id": materials[0]["_id"]}, - } - - if is_multimaterial: - config["_materials"] = [{"_id": m["_id"]} for m in materials] - - if materials_set is not None: - config["_materialsSet"] = _materials_set_reference(materials_set) - - if compute: - config["compute"] = compute - - if tags: - config["tags"] = list(tags) - - return api_client.jobs.create(config) - - -def find_job_for_material( - api_client: APIClient, - material_id: str, - workflow_name: str, - owner_id: str, - statuses: Iterable[str] = ("finished",), - kgrid: Optional[List[int]] = None, - unit_name: str = "pw_scf", -) -> Optional[dict]: - """ - Finds a job for a material and workflow name under the given owner, filtered by status and, - optionally, by the k-grid its `unit_name` unit ran on. - - Args: - api_client (APIClient): API client instance carrying the authorization context. - material_id (str): The job's `_material._id`. - workflow_name (str): Exact workflow name the job was created with. - owner_id (str): Account ID the job must belong to. - statuses (Iterable[str]): Job statuses that count as a match. - kgrid (List[int], optional): Exact k-grid dimensions the job's `unit_name` unit ran on; None for no condition. - unit_name (str): Name of the unit the k-grid was set on. - - Returns: - dict, optional: The matching job, or None if none exists. - """ - existing = api_client.jobs.list( - { - "_material._id": material_id, - "owner._id": owner_id, - "workflow.name": workflow_name, - "status": {"$in": list(statuses)}, - **get_kgrid_query(kgrid, unit_name), - }, - {"limit": 1}, - ) - return existing[0] if existing else None - - -def get_kgrid_query(kgrid: Optional[List[int]], unit_name: str = "pw_scf") -> Dict[str, Any]: - """ - `jobs.list` condition for jobs whose `unit_name` unit ran on `kgrid` (empty when `kgrid` is None), matched where - `apply_scf_kgrid` sets it: `workflow.subworkflows[].units[name].context[name="kgrid"].data.dimensions`. - A job created without an explicit k-grid has no such context and never matches. - """ - if kgrid is None: - return {} - kgrid_context = {"$elemMatch": {"name": "kgrid", "data.dimensions": list(kgrid)}} - return {"workflow.subworkflows.units": {"$elemMatch": {"name": unit_name, "context": kgrid_context}}} - - -def get_kgrid_of_job(job: Dict[str, Any], unit_name: str = "pw_scf") -> Optional[List[int]]: - """ - K-grid dimensions the job's `unit_name` unit ran on: its `kgrid` context, or, for a job created without one, the - grid the platform rendered into the unit's input, `workflow.subworkflows[].units[name].input[0].rendered`. - """ - units = [unit for subworkflow in job["workflow"]["subworkflows"] for unit in subworkflow["units"]] - unit = next(unit for unit in units if unit["name"] == unit_name) - kgrid_context = next((item for item in unit["context"] if item["name"] == "kgrid"), None) - if kgrid_context: - return kgrid_context["data"]["dimensions"] - match = re.search(r"K_POINTS automatic\s+(\d+)\s+(\d+)\s+(\d+)", unit["input"][0]["rendered"]) - return [int(dimension) for dimension in match.groups()] if match else None - - -def find_job_for_material_with_property( - api_client: APIClient, - material_id: str, - property_name: str, - owner_id: str, - tags: Optional[List[str]] = None, - kgrid: Optional[List[int]] = None, -) -> Optional[dict]: - """ - Finds a finished job on a material that reported the given property, optionally among the jobs - carrying every one of `tags` (e.g. ["charge:0"] for a reference computed in the neutral state) - and among those whose `pw_scf` unit ran on `kgrid`. - - Args: - api_client (APIClient): API client instance carrying the authorization context. - material_id (str): The job's `_material._id`. - property_name (str): Property the job must have reported, e.g. "total_energy". - owner_id (str): Account ID the job must belong to. - tags (List[str], optional): Tags the job must all carry. - kgrid (List[int], optional): Exact k-grid dimensions the job's `pw_scf` unit ran on; None for no condition. - - Returns: - dict, optional: The first matching job, or None if none exists. - """ - query: Dict[str, Any] = {"_material._id": material_id, "owner._id": owner_id, "status": "finished"} - if tags: - query["tags"] = {"$all": list(tags)} - jobs = api_client.jobs.list({**query, **get_kgrid_query(kgrid)}) - return next( - (job for job in jobs if api_client.properties.get_for_job(job["_id"], property_name=property_name)), None - ) - - -def submit_jobs(endpoint: JobEndpoints, job_ids: List[str]) -> None: - """ - Submits jobs by IDs. - - Args: - endpoint (JobEndpoints): Job endpoint object from the Exabyte API Client. - job_ids (list[str]): Job IDs to submit. - """ - for job_id in job_ids: - endpoint.submit(job_id) +) -> dict: + """ + `create_job` of mat3ra.api_client.tools for the materials, workflow and compute dict the notebooks hold, + returning the created job as the dict the notebooks read. + """ + return _create_job( + api_client, + [Material.create(material) for material in materials], + Workflow.create(workflow), + project_id, + owner_id, + prefix, + Compute.create(compute), + materials_set, + tags, + ).to_dict() + + +__all__ = [ + "DEFAULT_STATUS_TIMEOUT_SECONDS", + "MATERIALS_SET_ENTITY_CLASS", + "create_job", + "find_job_for_material", + "find_job_for_material_with_property", + "get_jobs_statuses_by_ids_async", + "get_kgrid_of_job", + "get_kgrid_query", + "save_files", + "submit_jobs", +] diff --git a/src/py/mat3ra/notebooks_utils/core/entity/material/api.py b/src/py/mat3ra/notebooks_utils/core/entity/material/api.py index 8af6d92b6..58dce557c 100644 --- a/src/py/mat3ra/notebooks_utils/core/entity/material/api.py +++ b/src/py/mat3ra/notebooks_utils/core/entity/material/api.py @@ -1,11 +1,20 @@ import os import re -from typing import Any, Dict, List, Optional +from typing import Dict, List from mat3ra.api_client import APIClient +from mat3ra.api_client.tools.material import ( + ORDERED_ENTITY_SET_TYPE, + UNORDERED_ENTITY_SET_TYPE, + find_material_set, + find_relaxed_material, + get_final_structure_for_job, + get_or_create_material, +) +from mat3ra.api_client.tools.material import get_or_create_materials_set as _get_or_create_materials_set +from mat3ra.api_client.tools.material import list_materials_by_set, list_materials_in_set from mat3ra.made.material import Material from mat3ra.made.tools.build_components import MaterialWithBuildMetadata -from mat3ra.prode import PropertyName from mat3ra.standata.materials import Materials from ..job.api import get_kgrid_query @@ -13,30 +22,16 @@ from .analysis import get_slab_bulk_crystal, resolve_bulk_query_from_crystal from .io import load_materials_from_folder -ORDERED_ENTITY_SET_TYPE = "ordered" -UNORDERED_ENTITY_SET_TYPE = "unordered" - -def get_or_create_material(api_client: APIClient, material, owner_id: str) -> dict: +def get_or_create_materials_set( + api_client: APIClient, owner_id: str, material_set_name: str, materials: List[dict], is_ordered: bool = False +) -> dict: """ - Returns an existing material from the collection if one with the same structural hash - exists under the given owner, otherwise creates a new one. - - Args: - api_client (APIClient): API client instance carrying the authorization context. - material: mat3ra-made Material object (must have a .hash property). - owner_id (str): Account ID under which to search and create. - - Returns: - dict: The material dict (existing or newly created). + `get_or_create_materials_set` of mat3ra.api_client.tools for the saved material dicts the notebooks hold. """ - existing = api_client.materials.list({"hash": material.hash, "owner._id": owner_id}) - if existing: - print(f"♻️ Reusing already existing Material: {existing[0]['_id']}") - return existing[0] - created = api_client.materials.create(material.to_dict(), owner_id=owner_id) - print(f"✅ Material created: {created['_id']}") - return created + return _get_or_create_materials_set( + api_client, owner_id, material_set_name, [Material.create(material) for material in materials], is_ordered + ) def select_material_by_name(materials: List[Material], name: str) -> Material: @@ -98,44 +93,6 @@ def load_material(api_client: APIClient, folder: str, name: str, owner_id: str) return select_material_by_name(candidates, name) -def get_final_structure_for_job(api_client: APIClient, job_id: str) -> Material: - """Fetch the relaxed structure a job reported as its `final_structure` property.""" - properties = get_properties_for_job(api_client, job_id, PropertyName.non_scalar.final_structure.value) - if not properties: - raise RuntimeError(f"Job {job_id} reported no 'final_structure'") - return Material.create(api_client.materials.get(properties[-1]["materialId"])) - - -def find_relaxed_material( - api_client: APIClient, material, owner_id: str, kgrid: Optional[List[int]] = None, unit_name: str = "pw_scf" -) -> Optional[Material]: - """ - Finds a relaxed version of a material: the final structure of a finished job on a material - with the same structural hash, where the geometry has changed, optionally among the jobs whose - `unit_name` unit ran on `kgrid`. - - Args: - api_client (APIClient): API client instance carrying the authorization context. - material: mat3ra-made Material object (must have a .hash property). - owner_id (str): Account ID under which to search. - kgrid (List[int], optional): Exact k-grid dimensions the relaxation ran on; None for no condition. - unit_name (str): Name of the relaxation unit, e.g. "pw_vc-relax". - - Returns: - Material, optional: The relaxed structure, or None if none exists. - """ - ids = [m["_id"] for m in api_client.materials.list({"hash": material.hash, "owner._id": owner_id})] - query = {"_material._id": {"$in": ids}, "owner._id": owner_id, "status": "finished"} - for job in api_client.jobs.list({**query, **get_kgrid_query(kgrid, unit_name)}): - properties = api_client.properties.get_for_job(job["_id"], PropertyName.non_scalar.final_structure.value) - if not properties: - continue - relaxed = api_client.materials.get(properties[-1]["materialId"]) - if relaxed["hash"] != material.hash: - return Material.create(relaxed) - return None - - def get_bulk_material(api_client: APIClient, slab_material: Material, owner_id: str) -> Material: """ Resolves the platform bulk material a slab was built from, owned by the given account. @@ -184,140 +141,20 @@ def _require_material_for_owner(api_client: APIClient, query: dict, owner_id: st return Material.create(material_response) -def _index_in_set(material: Dict[str, Any], material_set_id: str) -> float: - """ - Path-order sort key. A member with no recorded index sorts last, so a - partially indexed set degrades to "known order first" instead of reshuffling. - """ - for entry in material.get("inSet") or []: - if entry.get("_id") == material_set_id: - index = entry.get("index") - return float(index) if index is not None else float("inf") - return float("inf") - - -def find_material_set( - api_client: APIClient, - owner_id: str, - material_set_name: str, - require_ordered: bool = False, -) -> Dict[str, Any]: - """ - Find a materials entity set by name (case-insensitive substring match). - - Args: - api_client (APIClient): API client instance carrying the authorization context. - owner_id (str): Account ID that owns the set. - material_set_name (str): Substring matched against set names under the owner. - require_ordered (bool): Reject the match unless it carries path order. - - Returns: - dict: The first matching materials set document. - - Raises: - ValueError: If no set matches, or if `require_ordered` and the match is unordered. - """ - material_sets = api_client.materials.list( - { - "owner._id": owner_id, - "isEntitySet": True, - "name": {"$regex": re.escape(material_set_name), "$options": "i"}, - } - ) - if not material_sets: - raise ValueError(f"No material set matching '{material_set_name}'") - material_set = material_sets[0] - - # Only an ordered set gets inSet.index values, so sorting an unordered one leaves - # every member tied — an arbitrary path, submitted without an error. - entity_set_type = material_set.get("entitySetType") - if require_ordered and entity_set_type != ORDERED_ENTITY_SET_TYPE: - raise ValueError( - f"Materials set '{material_set.get('name')}' is '{entity_set_type}', not " - f"'{ORDERED_ENTITY_SET_TYPE}'. Its members carry no path order." - ) - return material_set - - -def list_materials_in_set(api_client: APIClient, owner_id: str, material_set: Dict[str, Any]) -> List[Dict[str, Any]]: - """ - Members of an already-resolved set, ascending by `inSet.index` - (first -> optional intermediates -> last). Takes a resolved set so callers - that already have one do not re-query for it. - """ - material_set_id = material_set["_id"] - matches = api_client.materials.list( - {"owner._id": owner_id, "inSet._id": material_set_id, "isEntitySet": {"$ne": True}} - ) - members = [material for material in matches if not material.get("isEntitySet")] - return sorted(members, key=lambda material: _index_in_set(material, material_set_id)) - - -def list_materials_by_set( - api_client: APIClient, - owner_id: str, - material_set_name: str, - require_ordered: bool = False, -) -> List[Dict[str, Any]]: - """Resolve a materials set by name and list its members in path order.""" - material_set = find_material_set(api_client, owner_id, material_set_name, require_ordered=require_ordered) - return list_materials_in_set(api_client, owner_id, material_set) - - -def get_or_create_materials_set( - api_client: APIClient, - owner_id: str, - material_set_name: str, - materials: List[Any], - is_ordered: bool = False, -) -> Dict[str, Any]: - """ - Reuse an existing materials set by name, or create one, then move members into it. - - Members are moved one at a time in list order: the platform assigns `inSet.index` - in the order it receives them, which is what makes an ordered set's path order - match the caller's list. - - Args: - api_client (APIClient): API client instance carrying the authorization context. - owner_id (str): Account ID under which to find or create the set. - material_set_name (str): Name of the set to reuse or create. - materials (list): Members to include (dict responses or Made objects with `.id`). - is_ordered (bool): Whether path order (`inSet.index`) matters for this set. - - Returns: - dict: The existing or newly created materials set document. - - Raises: - ValueError: If materials are empty, if an ordered set has fewer than two members, - or if an existing set of that name has the opposite `entitySetType`. - """ - if not materials: - raise ValueError("Materials set needs at least one material.") - if is_ordered and len(materials) < 2: - raise ValueError("Ordered materials set needs at least two materials.") - - entity_set_type = ORDERED_ENTITY_SET_TYPE if is_ordered else UNORDERED_ENTITY_SET_TYPE - try: - materials_set: Optional[Dict[str, Any]] = find_material_set(api_client, owner_id, material_set_name) - except ValueError: - materials_set = None - - if materials_set is None: - materials_set = api_client.materials.create_set( - {"name": material_set_name, "owner": {"_id": owner_id}, "entitySetType": entity_set_type} - ) - print(f"✅ Materials set '{materials_set['name']}' ({entity_set_type}, {materials_set['_id']})") - else: - existing_type = materials_set.get("entitySetType") - if existing_type != entity_set_type: - raise ValueError( - f"Materials set '{materials_set['name']}' already exists as '{existing_type}', but " - f"'{entity_set_type}' was requested. Reusing it would silently drop path order." - ) - print(f"♻️ Reusing materials set '{materials_set['name']}' ({existing_type}, {materials_set['_id']})") - - for material in materials: - identifier = material["_id"] if isinstance(material, dict) else material.id - api_client.materials.move_to_set(identifier, "", materials_set["_id"]) - return materials_set +__all__ = [ + "ORDERED_ENTITY_SET_TYPE", + "UNORDERED_ENTITY_SET_TYPE", + "find_material_set", + "find_relaxed_material", + "get_bulk_material", + "get_bulk_material_by_crystal", + "get_final_structure_for_job", + "get_kgrid_query", + "get_or_create_material", + "get_or_create_materials_set", + "get_properties_for_job", + "list_materials_by_set", + "list_materials_in_set", + "load_material", + "select_material_by_name", +] diff --git a/src/py/mat3ra/notebooks_utils/core/entity/property/api.py b/src/py/mat3ra/notebooks_utils/core/entity/property/api.py index 65e59feb7..78fb71f5a 100644 --- a/src/py/mat3ra/notebooks_utils/core/entity/property/api.py +++ b/src/py/mat3ra/notebooks_utils/core/entity/property/api.py @@ -1,15 +1,17 @@ from typing import List, Optional -from mat3ra.api_client import APIClient, PropertiesEndpoints -from mat3ra.prode import PropertyName +from mat3ra.api_client import APIClient +from mat3ra.api_client.tools.property import find_total_energy_for_material +from mat3ra.api_client.tools.property import get_properties_for_job as _get_properties_for_job +from mat3ra.api_client.tools.property import ( + get_property_by_subworkflow_and_unit_indicies, + get_property_holder_for_job, + update_property_holder_value, +) +from mat3ra.prode import FERMI_ENERGY_PROPERTIES, PropertyName, add_fermi_energy_to_properties from .job import get_fermi_energy_flowchart_id -FERMI_ENERGY_PROPERTIES = { - PropertyName.non_scalar.band_structure.value, - PropertyName.non_scalar.density_of_states.value, -} - def get_properties_for_job(client: APIClient, job_id: str, property_name: Optional[str] = None) -> List[dict]: """ @@ -17,125 +19,24 @@ def get_properties_for_job(client: APIClient, job_id: str, property_name: Option Use instead of client.properties.get_for_job when passing results to visualize_properties. """ job = client.jobs.get(job_id) - properties = client.properties.get_for_job(job_id, property_name) + properties = _get_properties_for_job(client, job_id, property_name) if property_name not in FERMI_ENERGY_PROPERTIES: return properties flowchart_id = get_fermi_energy_flowchart_id(job) - fermi_energy = None + fermi_energy_properties: List[dict] = [] if flowchart_id: - fe_props = client.properties.get_for_job(job_id, PropertyName.scalar.fermi_energy.value, flowchart_id) - if fe_props: - fermi_energy = fe_props[0].get("value") - return [{**prop, "fermiEnergy": fermi_energy} for prop in properties] - - -def get_property_holder_for_job( - client: APIClient, job_id: str, property_name: str, unit_id: Optional[str] = None -) -> dict: - """ - Fetch the first full property holder for a job/property pair. - - Args: - client (APIClient): API client instance. - job_id (str): Job ID. - property_name (str): Property name. - unit_id (str, optional): Unit flowchart ID. - - Returns: - dict: Full property holder document. - """ - query = { - "source.info.jobId": job_id, - "data.name": property_name, - } - if unit_id: - query["source.info.unitId"] = unit_id - holders = client.properties.list(query=query) - if not holders: - raise ValueError(f"Property '{property_name}' not found for job '{job_id}'") - return holders[0] - - -def update_property_holder_value(client: APIClient, property_holder_id: str, value: float) -> dict: - """ - Update a scalar property's data.value. - - Args: - client (APIClient): API client instance. - property_holder_id (str): Property holder ID. - value (float): New scalar value. - - Returns: - dict: Server response payload. - """ - return client.properties.update(property_holder_id, {"$set": {"data.value": value}}) - - -def find_total_energy_for_material( - client: APIClient, - material_id: str, - source: str = "my_account", - group: Optional[str] = None, - precision_value: Optional[float] = None, -) -> Optional[dict]: - """ - Find the best-precision total_energy property for a material. Mirrors the - platform's "Resolve Total Energies for Elemental Materials" subworkflow, - which queries properties directly by material and selects by precision -- - no job lookup involved. - - Properties are keyed by the material's `exabyteId`, not its platform `_id`, - so the material is fetched first to resolve that field. - - Args: - client (APIClient): API client instance. - material_id (str): Material _id to look up the total_energy property for. - source (str): Source of the total energy property: `my_account` (default), `curators` or - `public`. - group (str, optional): Model identifier the property must carry, e.g. `qe:dft:lda:pz`. - Without it a property computed with a different model is returned. - precision_value (float, optional): `precision.value` (KPPRA) the property must carry. - - Returns: - The best-precision total_energy property, or None if none exists. - """ - material = client.materials.get(material_id) - exabyte_id = material.get("exabyteId") - if not exabyte_id: - return None - query = {"exabyteId": exabyte_id, "slug": "total_energy"} - if group: - query["group"] = group - if precision_value is not None: - query["precision.value"] = precision_value - if source == "curators": - query["owner.slug"] = "curators" - elif source == "my_account": - query["owner._id"] = client.my_account.id - elif source != "public": - raise ValueError(f"Invalid source: {source!r}. Expected 'public', 'curators', or 'my_account'.") - properties = client.properties.list( - query=query, - projection={"sort": {"precision.value": -1}, "limit": 1}, - ) - return properties[0] if properties else None - - -def get_property_by_subworkflow_and_unit_indicies( - endpoint: PropertiesEndpoints, property_name: str, job: dict, subworkflow_index: int, unit_index: int -) -> dict: - """ - Returns the property extracted in the given unit of the job's subworkflow. - - Args: - endpoint (PropertiesEndpoints): an instance of PropertiesEndpoints class. - property_name (str): name of property to extract. - job (dict): job config to extract the property from. - subworkflow_index (int): index of subworkflow to extract the property from. - unit_index (int): index of unit to extract the property from. - - Returns: - dict: extracted property - """ - unit_flowchart_id = job["workflow"]["subworkflows"][subworkflow_index]["units"][unit_index]["flowchartId"] - return endpoint.get_property(job["_id"], unit_flowchart_id, property_name) + fermi_energy_properties = client.properties.get_for_job( + job_id, PropertyName.scalar.fermi_energy.value, flowchart_id + ) + return add_fermi_energy_to_properties(properties, fermi_energy_properties) + + +__all__ = [ + "FERMI_ENERGY_PROPERTIES", + "find_total_energy_for_material", + "get_fermi_energy_flowchart_id", + "get_properties_for_job", + "get_property_by_subworkflow_and_unit_indicies", + "get_property_holder_for_job", + "update_property_holder_value", +] diff --git a/src/py/mat3ra/notebooks_utils/core/entity/property/job.py b/src/py/mat3ra/notebooks_utils/core/entity/property/job.py index b9cea8fce..b3024376e 100644 --- a/src/py/mat3ra/notebooks_utils/core/entity/property/job.py +++ b/src/py/mat3ra/notebooks_utils/core/entity/property/job.py @@ -1,20 +1,3 @@ -from typing import Optional +from mat3ra.wode.tools.workflow import get_fermi_energy_flowchart_id -from mat3ra.prode import PropertyName - - -def get_fermi_energy_flowchart_id(job: dict) -> Optional[str]: - """ - Find the flowchart ID of the last unit that declares fermi_energy in its results. - Mirrors calculateFermiEnergy logic in the web app. - """ - for subworkflow in job.get("workflow", {}).get("subworkflows", []): - units_with_fermi_energy = [ - unit - for unit in subworkflow.get("units", []) - if any(r.get("name") == PropertyName.scalar.fermi_energy.value for r in unit.get("results", [])) - ] - if not units_with_fermi_energy: - continue - return units_with_fermi_energy[-1].get("flowchartId") - return None +__all__ = ["get_fermi_energy_flowchart_id"] diff --git a/src/py/mat3ra/notebooks_utils/core/entity/workflow/api.py b/src/py/mat3ra/notebooks_utils/core/entity/workflow/api.py index 91a590cfc..721161be4 100644 --- a/src/py/mat3ra/notebooks_utils/core/entity/workflow/api.py +++ b/src/py/mat3ra/notebooks_utils/core/entity/workflow/api.py @@ -1,42 +1,15 @@ -from mat3ra.api_client import APIClient, BankWorkflowEndpoints +from mat3ra.api_client import APIClient +from mat3ra.api_client.tools.workflow import copy_bank_workflow_by_system_name +from mat3ra.api_client.tools.workflow import get_or_create_workflow as _get_or_create_workflow from mat3ra.wode import Workflow +from mat3ra.wode.tools.unit import set_execution_unit_input def get_or_create_workflow(api_client: APIClient, workflow: Workflow, owner_id: str) -> dict: """ - Creates a workflow in the collection if none with the same hash exists under the given owner. - - Args: - api_client (APIClient): API client instance carrying the authorization context. - workflow: mat3ra-wode Workflow object. - owner_id (str): Account ID under which to search and create. - - Returns: - dict: The workflow dict (existing or newly created). + `get_or_create_workflow` of mat3ra.api_client.tools, returning the saved workflow as the dict the notebooks read. """ - existing = api_client.workflows.list({"hash": workflow.hash, "owner._id": owner_id}) - if existing: - print(f"♻️ Reusing already existing Workflow: {existing[0]['_id']}") - return existing[0] - created = api_client.workflows.create(workflow.to_dict_without_special_keys(), owner_id=owner_id) - print(f"✅ Workflow created: {created['_id']}") - return created - - -def copy_bank_workflow_by_system_name(endpoint: BankWorkflowEndpoints, system_name: str, account_id: str) -> dict: - """ - Copies a bank workflow with given system name into the account's workflows. - - Args: - endpoint (BankWorkflowEndpoints): an instance of BankWorkflowEndpoints class - system_name (str): workflow system name. - account_id (str): ID of account to copy the bank workflow into. - - Returns: - dict: new account's workflow - """ - bank_workflow_id = endpoint.list({"systemName": system_name})[0]["_id"] - return endpoint.copy(bank_workflow_id, account_id)["_id"] + return _get_or_create_workflow(api_client, workflow, owner_id).to_dict() CUSTOM_SCRIPT_RUNNER = '''import json @@ -60,28 +33,10 @@ def copy_bank_workflow_by_system_name(endpoint: BankWorkflowEndpoints, system_na """ -def set_execution_unit_input(unit: dict, template_name: str, content: str) -> None: - """ - Replaces one input file of an execution unit with fixed content. - - `isManuallyChanged` stops the platform re-rendering the file at job creation, which is what - lets the runner keep its `{{ ... }}` placeholders for the compute node to resolve, and keeps a - user's requirements verbatim. Inputs are matched by template name rather than position, so - adding a file to the flavor cannot silently write content into the wrong one. - - Args: - unit (dict): Execution unit config from a workflow. - template_name (str): Name of the input file to replace, e.g. "script.py". - content (str): Content to write. - - Raises: - KeyError: If the unit has no input with that template name. - """ - for unit_input in unit["input"]: - if unit_input["template"]["name"] == template_name: - unit_input["template"]["content"] = content - unit_input["rendered"] = content - unit_input["isManuallyChanged"] = True - return - available = [unit_input["template"]["name"] for unit_input in unit["input"]] - raise KeyError(f"No input named '{template_name}' in unit '{unit.get('name')}'. Available: {available}") +__all__ = [ + "CUSTOM_SCRIPT_RUNNER", + "CUSTOM_SCRIPT_RUNNER_SH", + "copy_bank_workflow_by_system_name", + "get_or_create_workflow", + "set_execution_unit_input", +] diff --git a/src/py/mat3ra/notebooks_utils/job.py b/src/py/mat3ra/notebooks_utils/job.py index f05771dc5..6bb1ebb0a 100644 --- a/src/py/mat3ra/notebooks_utils/job.py +++ b/src/py/mat3ra/notebooks_utils/job.py @@ -1,59 +1,8 @@ -from functools import wraps -from typing import Any, Callable, List +from mat3ra.api_client.tools.job import get_convergence_series -from mat3ra.api_client import APIClient -from mat3ra.made.material import Material -from mat3ra.wode import Workflow +from .core.entity.job.api import create_job -from .core.entity.job.api import create_job as _create_job - - -# TODO: place to mat3ra-made -def convert_material_args(fn: Callable) -> Callable: - """Converts any Material or List[Material] arg/kwarg to dict(s).""" - - @wraps(fn) - def wrapper(*args: Any, **kwargs: Any) -> Any: - def convert(v: Any) -> Any: - if Material is not None and isinstance(v, Material): - return v.to_dict() - if isinstance(v, list): - return [i.to_dict() if (Material is not None and isinstance(i, Material)) else i for i in v] - return v - - return fn(*[convert(a) for a in args], **{k: convert(v) for k, v in kwargs.items()}) - - return wrapper - - -# TODO: place to mat3ra-wode -def convert_workflow_args(fn: Callable) -> Callable: - """Converts any Workflow arg/kwarg to a dict.""" - - @wraps(fn) - def wrapper(*args: Any, **kwargs: Any) -> Any: - convert = lambda v: v.to_dict() if (Workflow is not None and isinstance(v, Workflow)) else v # noqa: E731 - return fn(*[convert(a) for a in args], **{k: convert(v) for k, v in kwargs.items()}) - - return wrapper - - -create_job = convert_workflow_args(convert_material_args(_create_job)) - - -def get_convergence_series(client: APIClient, job_id: str, subworkflow_index: int = 0) -> List[dict]: - """ - Returns the convergence series from a finished convergence job. - - Args: - client: API client instance. - job_id: ID of the finished convergence job. - subworkflow_index: Index of the convergence subworkflow (default 0). - - Returns: - List of dicts with keys "x", "parameter", "y". - """ - finished_job = client.jobs.get(job_id) - job_workflow = Workflow.create(finished_job["workflow"]) - subworkflow = job_workflow.subworkflows[subworkflow_index] - return subworkflow.convergence_series(finished_job.get("scopeTrack")) +__all__ = [ + "create_job", + "get_convergence_series", +] diff --git a/src/py/mat3ra/notebooks_utils/token_store.py b/src/py/mat3ra/notebooks_utils/token_store.py index 79a135d5c..9a7aeee47 100644 --- a/src/py/mat3ra/notebooks_utils/token_store.py +++ b/src/py/mat3ra/notebooks_utils/token_store.py @@ -3,9 +3,10 @@ Switches storage between file (Python) and IndexedDB (Pyodide). """ -import time from typing import Optional +from mat3ra.api_client.tools.auth.token import add_token_to_cache, get_token_from_cache + from .primitive.environment import is_pyodide_environment if is_pyodide_environment(): @@ -15,22 +16,15 @@ from .core.api.token_store import read as _read from .core.api.token_store import write as _write -_EXPIRY_BUFFER = 60 * 5 # to avoid using soon-to-expire tokens - async def save_token(oidc_url: str, token_data: dict) -> None: - entry = dict(token_data) - entry["expires_at"] = time.time() + entry.get("expires_in", 3600) cache = await _read() - cache[oidc_url] = entry + add_token_to_cache(cache, oidc_url, token_data) await _write(cache) async def load_token(oidc_url: str) -> Optional[dict]: - entry = (await _read()).get(oidc_url) - if not entry or entry.get("expires_at", 0) <= time.time() + _EXPIRY_BUFFER: - return None - return entry + return get_token_from_cache(await _read(), oidc_url) async def delete_token(oidc_url: str) -> None: diff --git a/src/py/mat3ra/notebooks_utils/workflow.py b/src/py/mat3ra/notebooks_utils/workflow.py index ffa70f3fe..fd506b12f 100644 --- a/src/py/mat3ra/notebooks_utils/workflow.py +++ b/src/py/mat3ra/notebooks_utils/workflow.py @@ -1,150 +1,24 @@ -import math -import re -from typing import Dict, List, Optional +from typing import List -from mat3ra.wode import Workflow -from mat3ra.wode.context.providers import PlanewaveCutoffsContextProvider, PointsGridDataProvider +from mat3ra.made.material import Material +from mat3ra.wode.context.providers import PointsGridDataProvider +from mat3ra.wode.tools.espresso import apply_planewave_cutoffs, apply_scf_kgrid, patch_workflow_qe_input +from mat3ra.wode.tools.espresso.helpers import FORTRAN_NUMBER_PATTERN +from mat3ra.wode.tools.workflow import set_assignment_value -FORTRAN_NUMBER_PATTERN = re.compile(r"^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[de][+-]?\d+)?$", re.IGNORECASE) - -def _format_fortran_value(value: object) -> str: - if isinstance(value, bool): - return f".{str(value).lower()}." - if isinstance(value, str) and not FORTRAN_NUMBER_PATTERN.match(value): - return repr(value) - return str(value) - - -def patch_workflow_qe_input( - workflow: Workflow, - parameters: Dict[str, Dict[str, object]], - unit_names: List[str], - input_name: Optional[str] = None, -) -> Workflow: +def kgrid_from_density(material: Material, density: float, periodic_dims: tuple = (0, 1, 2)) -> List[int]: """ - Patch QE inputs across workflow subworkflows for named units. - - Args: - workflow: Workflow with subworkflows. - parameters: Multi-section parameters {section: {key: val}}. - unit_names: List of unit names to patch. - input_name: Optional input file name filter. - - Example: - patch_workflow_qe_input(workflow, {"system": {"vdw_corr": "d3_grimme"}}, ["pw_relax"]) - """ - for subworkflow in workflow.subworkflows: - for unit_name in unit_names: - if not (unit := subworkflow.get_unit_by_name(name=unit_name)): - continue - for input_item in getattr(unit, "input", []): - template = input_item.template - template_name = template.name - content = template.content - - if input_name not in (None, template_name): - continue - - for section, updates in parameters.items(): - name = section.lstrip("&") - match = re.search(rf"(?ims)(^&{re.escape(name)}\s*\n)(.*?)(^/\s*$)", content) - if not match: - raise ValueError(f"Namelist '&{name.upper()}' not found.") - header, body, footer = match.groups() - for key, value in updates.items(): - line = f" {key} = {_format_fortran_value(value)}" - pattern = rf"(?im)^\s*{re.escape(key)}\s*=.*$" - body = re.sub(pattern, line, body) if re.search(pattern, body) else f"{body.rstrip()}\n{line}\n" - content = content[: match.start()] + header + body + footer + content[match.end() :] - - template.set_content(content) - subworkflow.set_unit(unit) - return workflow - - -def kgrid_from_density(material, density: float, periodic_dims: tuple = (0, 1, 2)) -> List[int]: - """ - Returns a k-point grid sized to a reciprocal-space density (points per Å⁻¹) per periodic - dimension, 1 elsewhere. - - Args: - material: Material the grid applies to; reciprocal vector norms come from its lattice. - density (float): Points per Å⁻¹ of reciprocal length (GPAW's k-point density convention). - periodic_dims (tuple[int]): Lattice dimensions (0, 1, 2) that are periodic. - - Returns: - list[int]: Grid dimensions, e.g. [4, 4, 1]. - """ - norms = material.lattice.reciprocal_vector_norms - grid = [1, 1, 1] - for dim in periodic_dims: - grid[dim] = max(1, math.ceil(density * 2 * math.pi * norms[dim])) - return grid - - -def apply_scf_kgrid( - workflow: Workflow, scf_kgrid=None, *, material=None, unit_name: str = "pw_scf", first_only: bool = False -) -> Workflow: - """ - Attaches an edited SCF k-grid context to units named `unit_name`. - - Args: - workflow: Workflow with subworkflows. - scf_kgrid: K-grid dimensions, e.g. [4, 4, 1]. If None, the workflow is returned unchanged. - material: Material the grid applies to. KPPRA is per reciprocal atom and the reciprocal - vector ratios come from the lattice, so both are derived from it. - unit_name: Name of the unit to attach the k-grid context to. - first_only: If True, only patch the first matching subworkflow. - """ - if scf_kgrid is None: - return workflow - context = PointsGridDataProvider(material=material, dimensions=scf_kgrid, isEdited=True).get_context_item_data() - for subworkflow in workflow.subworkflows: - if unit_name not in [unit.name for unit in subworkflow.units]: - continue - unit = subworkflow.get_unit_by_name(name=unit_name) - unit.add_context(context) - subworkflow.set_unit(unit) - if first_only: - break - return workflow - - -# TODO: move to Wode -def set_assignment_value(workflow: Workflow, unit_name: str, value: str) -> Workflow: - """ - Sets the value of the assignment units named `unit_name` in every subworkflow that has one. - - Args: - workflow: Workflow with subworkflows. - unit_name: Name of the assignment unit, e.g. "assign-charge". - value: The unit's new value, as the Python expression the workflow evaluates, e.g. "-1". - - Raises: - ValueError: If no subworkflow has a unit of that name. + `calculate_dimensions_from_density` of the mat3ra.wode PointsGridDataProvider holding the material. """ - subworkflows = [ - subworkflow for subworkflow in workflow.subworkflows if subworkflow.get_unit_by_name(name=unit_name) - ] - if not subworkflows: - raise ValueError(f"The workflow has no '{unit_name}' unit.") - for subworkflow in subworkflows: - unit = subworkflow.get_unit_by_name(name=unit_name) - unit.value = value - subworkflow.set_unit(unit) - return workflow + return PointsGridDataProvider(material=material).calculate_dimensions_from_density(density, periodic_dims) -def apply_planewave_cutoffs(workflow: Workflow, wavefunction, density, *, unit_name: str = "pw_relax") -> Workflow: - """Attaches an edited planewave cutoffs context to units named `unit_name`.""" - context = PlanewaveCutoffsContextProvider( - wavefunction=wavefunction, density=density, isEdited=True - ).get_context_item_data() - for subworkflow in workflow.subworkflows: - if unit_name not in [unit.name for unit in subworkflow.units]: - continue - unit = subworkflow.get_unit_by_name(name=unit_name) - unit.add_context(context) - subworkflow.set_unit(unit) - return workflow +__all__ = [ + "FORTRAN_NUMBER_PATTERN", + "apply_planewave_cutoffs", + "apply_scf_kgrid", + "kgrid_from_density", + "patch_workflow_qe_input", + "set_assignment_value", +] diff --git a/tests/py/unit/core/entity/test_file_api.py b/tests/py/unit/core/entity/test_file_api.py deleted file mode 100644 index 43abf163e..000000000 --- a/tests/py/unit/core/entity/test_file_api.py +++ /dev/null @@ -1,33 +0,0 @@ -from typing import Any, Dict - -from mat3ra.notebooks_utils.core.entity.file.api import to_object_storage_input - -CLOUD_FILE: Dict[str, Any] = { - "key": "my-account/user_script.py", - "size": 14, - "bucket": "test-bucket", - "region": "us-west-2", - "provider": "aws", - "name": "user_script.py", -} - - -def test_object_storage_input_carries_every_field_the_runner_needs(): - """rupy requires all of NAME/PROVIDER/CONTAINER/REGION plus a basename, with no defaults.""" - assert to_object_storage_input(CLOUD_FILE) == { - "type": "object_storage", - "basename": "user_script.py", - "pathname": "", - "objectData": { - "NAME": "my-account/user_script.py", - "PROVIDER": "aws", - "CONTAINER": "test-bucket", - "REGION": "us-west-2", - }, - } - - -def test_object_storage_basename_is_the_name_the_script_opens(): - nested = {**CLOUD_FILE, "key": "my-account/assets/radii.json"} - - assert to_object_storage_input(nested)["basename"] == "radii.json" diff --git a/tests/py/unit/core/entity/test_job_api.py b/tests/py/unit/core/entity/test_job_api.py index fc3c575e9..7078ab464 100644 --- a/tests/py/unit/core/entity/test_job_api.py +++ b/tests/py/unit/core/entity/test_job_api.py @@ -1,260 +1,22 @@ import asyncio -from typing import Any, Dict, List +from typing import Any, Dict from unittest.mock import MagicMock import pytest from mat3ra.api_client import AuthContext, JobEndpoints -from mat3ra.notebooks_utils.core.entity.job.api import ( - create_job, - find_job_for_material, - find_job_for_material_with_property, - get_jobs_statuses_by_ids_async, - get_kgrid_of_job, - get_kgrid_query, -) +from mat3ra.ide.compute import Compute, QueueName +from mat3ra.made.material import Material +from mat3ra.notebooks_utils.core.entity.job.api import create_job, get_jobs_statuses_by_ids_async +from mat3ra.standata.materials import Materials +from mat3ra.standata.workflows import WorkflowStandata +from mat3ra.wode import Workflow OWNER_ID = "account-1" -PROJECT_ID = "project-1" JOB_PREFIX = "NEB H2+H" -MATERIAL_SET_ID = "set-1" -MATERIAL_SET_NAME = "H2+H" - -MATERIAL_INITIAL: Dict[str, Any] = {"_id": "m-initial", "name": "initial"} -MATERIAL_FINAL: Dict[str, Any] = {"_id": "m-final", "name": "final"} -MATERIALS: List[Dict[str, Any]] = [MATERIAL_INITIAL, MATERIAL_FINAL] - -MULTI_MATERIAL_WORKFLOW: Dict[str, Any] = { - "_id": "workflow-1", - "name": "NEB", - "isMultiMaterial": True, -} -SINGLE_MATERIAL_WORKFLOW: Dict[str, Any] = { - "_id": "workflow-2", - "name": "Total Energy", - "isMultiMaterial": False, -} -MATERIALS_SET: Dict[str, Any] = { - "_id": MATERIAL_SET_ID, - "name": MATERIAL_SET_NAME, - "slug": MATERIAL_SET_NAME, - "isEntitySet": True, -} CREATED_JOB: Dict[str, Any] = {"_id": "job-1", "name": JOB_PREFIX} -EXISTING_JOB: Dict[str, Any] = {"_id": "job-0", "name": "Fixed-cell Relaxation V_B pbe-us", "status": "finished"} -RELAX_WORKFLOW_NAME = "Fixed-cell Relaxation V_B pbe-us" -CHARGE_TAGS = ["charge:-1"] - - -@pytest.mark.parametrize( - ("workflow", "materials_set", "expected_materials_set"), - [ - (MULTI_MATERIAL_WORKFLOW, MATERIALS_SET, True), - (MULTI_MATERIAL_WORKFLOW, None, False), - (SINGLE_MATERIAL_WORKFLOW, MATERIALS_SET, True), - ], -) -def test_create_job_sets_materials_set_when_provided(workflow, materials_set, expected_materials_set): - client = MagicMock() - client.jobs.create.return_value = CREATED_JOB - workflow_payload = dict(workflow) - - job = create_job( - api_client=client, - materials=MATERIALS, - workflow=workflow_payload, - project_id=PROJECT_ID, - owner_id=OWNER_ID, - prefix=JOB_PREFIX, - materials_set=materials_set, - ) - - assert job["_id"] == "job-1" - config = client.jobs.create.call_args.args[0] - assert "_id" not in workflow_payload - assert ("_materialsSet" in config) is expected_materials_set - if expected_materials_set: - assert config["_materialsSet"] == { - "_id": MATERIAL_SET_ID, - "cls": "Material", - "slug": MATERIAL_SET_NAME, - } - if workflow.get("isMultiMaterial"): - assert config["_materials"] == [{"_id": "m-initial"}, {"_id": "m-final"}] - else: - assert "_materials" not in config - - -@pytest.mark.parametrize( - ("tags", "expected_tags"), - [(None, None), (CHARGE_TAGS, CHARGE_TAGS)], -) -def test_create_job_sets_tags_when_provided(tags, expected_tags): - client = MagicMock() - client.jobs.create.return_value = CREATED_JOB - - create_job( - api_client=client, - materials=MATERIALS, - workflow=dict(SINGLE_MATERIAL_WORKFLOW), - project_id=PROJECT_ID, - owner_id=OWNER_ID, - prefix=JOB_PREFIX, - tags=tags, - ) - - assert client.jobs.create.call_args.args[0].get("tags") == expected_tags - - -@pytest.mark.parametrize( - "statuses", - [("finished",), ("submitted", "queued", "active")], -) -def test_find_job_for_material_returns_the_job_when_found(statuses): - client = MagicMock() - client.jobs.list.return_value = [EXISTING_JOB] - - job = find_job_for_material(client, MATERIAL_INITIAL["_id"], RELAX_WORKFLOW_NAME, OWNER_ID, statuses=statuses) - - assert job == EXISTING_JOB - client.jobs.list.assert_called_once_with( - { - "_material._id": MATERIAL_INITIAL["_id"], - "owner._id": OWNER_ID, - "workflow.name": RELAX_WORKFLOW_NAME, - "status": {"$in": list(statuses)}, - }, - {"limit": 1}, - ) - - -def test_find_job_for_material_returns_none_when_not_found(): - client = MagicMock() - client.jobs.list.return_value = [] - - job = find_job_for_material(client, MATERIAL_INITIAL["_id"], RELAX_WORKFLOW_NAME, OWNER_ID) - - assert job is None - - -def test_find_job_for_material_defaults_to_finished_only(): - client = MagicMock() - client.jobs.list.return_value = [] - - find_job_for_material(client, MATERIAL_INITIAL["_id"], RELAX_WORKFLOW_NAME, OWNER_ID) - - assert client.jobs.list.call_args.args[0]["status"] == {"$in": ["finished"]} - - -PROPERTY_NAME = "total_energy" -JOB_WITHOUT_PROPERTY: Dict[str, Any] = {"_id": "job-2", "name": "Band Gap", "status": "finished"} - - -def test_find_job_for_material_with_property_returns_the_first_job_that_reported_it(): - client = MagicMock() - client.jobs.list.return_value = [JOB_WITHOUT_PROPERTY, EXISTING_JOB] - client.properties.get_for_job.side_effect = lambda job_id, property_name: ( - [{"name": property_name}] if job_id == EXISTING_JOB["_id"] else [] - ) - - job = find_job_for_material_with_property( - client, MATERIAL_INITIAL["_id"], PROPERTY_NAME, OWNER_ID, tags=CHARGE_TAGS - ) - - assert job == EXISTING_JOB - client.jobs.list.assert_called_once_with( - { - "_material._id": MATERIAL_INITIAL["_id"], - "owner._id": OWNER_ID, - "status": "finished", - "tags": {"$all": CHARGE_TAGS}, - } - ) - - -def test_find_job_for_material_with_property_returns_none_when_no_job_reported_it(): - client = MagicMock() - client.jobs.list.return_value = [JOB_WITHOUT_PROPERTY] - client.properties.get_for_job.return_value = [] - - job = find_job_for_material_with_property(client, MATERIAL_INITIAL["_id"], PROPERTY_NAME, OWNER_ID) - - assert job is None - assert "tags" not in client.jobs.list.call_args.args[0] - - -SCF_KGRID_QUERY: Dict[str, Any] = { - "workflow.subworkflows.units": { - "$elemMatch": {"name": "pw_scf", "context": {"$elemMatch": {"name": "kgrid", "data.dimensions": [4, 4, 4]}}} - } -} -RELAX_KGRID_QUERY: Dict[str, Any] = { - "workflow.subworkflows.units": { - "$elemMatch": {"name": "pw_relax", "context": {"$elemMatch": {"name": "kgrid", "data.dimensions": [4, 4, 4]}}} - } -} - - -@pytest.mark.parametrize( - ("kgrid", "unit_name", "expected_query"), - [(None, "pw_relax", {}), ([4, 4, 4], "pw_scf", SCF_KGRID_QUERY), ([4, 4, 4], "pw_relax", RELAX_KGRID_QUERY)], -) -def test_get_kgrid_query(kgrid, unit_name, expected_query): - assert get_kgrid_query(kgrid, unit_name) == expected_query - - -def test_find_job_for_material_with_property_matches_the_pw_scf_kgrid(): - client = MagicMock() - client.jobs.list.return_value = [EXISTING_JOB] - client.properties.get_for_job.return_value = [{"name": PROPERTY_NAME}] - - job = find_job_for_material_with_property(client, MATERIAL_INITIAL["_id"], PROPERTY_NAME, OWNER_ID, kgrid=[4, 4, 4]) - - assert job == EXISTING_JOB - assert SCF_KGRID_QUERY.items() <= client.jobs.list.call_args.args[0].items() - - -def test_find_job_for_material_matches_the_kgrid_of_the_unit(): - client = MagicMock() - client.jobs.list.return_value = [EXISTING_JOB] - - job = find_job_for_material( - client, MATERIAL_INITIAL["_id"], RELAX_WORKFLOW_NAME, OWNER_ID, kgrid=[4, 4, 4], unit_name="pw_relax" - ) - - assert job == EXISTING_JOB - assert RELAX_KGRID_QUERY.items() <= client.jobs.list.call_args.args[0].items() - - -# The pw_scf unit with a kgrid context, input not rendered yet, and as production job BLmZo5WZfFXKKTb2H stores a job -# created without a grid: no context, the platform's grid rendered into the input. -KGRID_CONTEXT: Dict[str, Any] = { - "name": "kgrid", - "isEdited": True, - "data": {"dimensions": [4, 4, 4], "shifts": [0, 0, 0], "gridMetricType": "KPPRA", "gridMetricValue": 768}, - "extraData": {"materialHash": "041d30e32f91e2eeb14c74298dffd08b"}, -} -RENDERED_INPUT = ( - "CELL_PARAMETERS angstrom\n 0.000000000 0.000000000 5.326038000\nK_POINTS automatic\n1 1 1 0 0 0 \n" -) -UNIT_WITH_KGRID_CONTEXT: Dict[str, Any] = { - "name": "pw_scf", - "context": [KGRID_CONTEXT], - "input": [{"template": {"name": "pw_scf.in"}, "rendered": "", "isManuallyChanged": False}], -} -UNIT_WITH_RENDERED_INPUT: Dict[str, Any] = { - "name": "pw_scf", - "context": [], - "input": [{"template": {"name": "pw_scf.in"}, "rendered": RENDERED_INPUT, "isManuallyChanged": False}], -} - - -@pytest.mark.parametrize( - ("unit", "expected_kgrid"), - [(UNIT_WITH_KGRID_CONTEXT, [4, 4, 4]), (UNIT_WITH_RENDERED_INPUT, [1, 1, 1])], -) -def test_get_kgrid_of_job(unit, expected_kgrid): - assert get_kgrid_of_job({"workflow": {"subworkflows": [{"units": [unit]}]}}) == expected_kgrid - +SAVED_MATERIAL: Dict[str, Any] = {**Materials.get_by_name_first_match("Silicon"), "_id": "m-1"} +WORKFLOW: Dict[str, Any] = WorkflowStandata.get_by_name_first_match("total_energy") +COMPUTE: Dict[str, Any] = Compute(cluster={"fqdn": "cluster-001.mat3ra.com"}, queue=QueueName.D, ppn=2).to_dict() REQUEST_TIMEOUT_SECONDS = 0.05 BLOCKED_REQUEST_SECONDS = 1.0 @@ -278,3 +40,25 @@ async def test_get_jobs_statuses_by_ids_async(monkeypatch): with pytest.raises(asyncio.TimeoutError): await get_jobs_statuses_by_ids_async(endpoint, [CREATED_JOB["_id"]], REQUEST_TIMEOUT_SECONDS, ABORT_SIGNAL) pyfetch.assert_called_once_with(JOBS_FETCH_URL, headers=BEARER_HEADERS, signal=ABORT_SIGNAL) + + +@pytest.mark.parametrize( + ("material", "workflow"), + [(SAVED_MATERIAL, WORKFLOW), (Material.create(SAVED_MATERIAL), Workflow.create(WORKFLOW))], +) +def test_create_job_takes_the_notebooks_materials_and_workflow_and_returns_the_job_dict(material, workflow): + client = MagicMock() + client.jobs.create.side_effect = lambda config: {**config, **CREATED_JOB} + + job = create_job( + api_client=client, + materials=[material], + workflow=workflow, + project_id="project-1", + owner_id=OWNER_ID, + prefix=JOB_PREFIX, + compute=COMPUTE, + ) + + assert job["_id"] == CREATED_JOB["_id"] + assert client.jobs.create.call_args.args[0]["_material"] == {"_id": SAVED_MATERIAL["_id"]} diff --git a/tests/py/unit/core/entity/test_material_api.py b/tests/py/unit/core/entity/test_material_api.py index aed8f711f..6177a611c 100644 --- a/tests/py/unit/core/entity/test_material_api.py +++ b/tests/py/unit/core/entity/test_material_api.py @@ -1,61 +1,18 @@ import json import re -from types import SimpleNamespace -from typing import Any, Dict, List +from typing import Any, Dict from unittest.mock import MagicMock import pytest from mat3ra.made.material import Material -from mat3ra.notebooks_utils.core.entity.job.api import get_kgrid_query from mat3ra.notebooks_utils.core.entity.material.api import ( - find_material_set, - find_relaxed_material, - get_final_structure_for_job, get_or_create_materials_set, - list_materials_by_set, - list_materials_in_set, load_material, select_material_by_name, ) from mat3ra.standata.materials import Materials OWNER_ID = "account-1" -MATERIAL_SET_NAME = "H2+H" -MATERIAL_SET_ID = "set-1" - -MATERIAL_INITIAL: Dict[str, Any] = { - "_id": "m-initial", - "name": "path-start", - "isEntitySet": False, - "inSet": [{"_id": MATERIAL_SET_ID, "index": 0}], -} -MATERIAL_IMAGE: Dict[str, Any] = { - "_id": "m-image", - "name": "path-mid", - "isEntitySet": False, - "inSet": [{"_id": MATERIAL_SET_ID, "index": 1}], -} -MATERIAL_FINAL: Dict[str, Any] = { - "_id": "m-final", - "name": "path-end", - "isEntitySet": False, - "inSet": [{"_id": MATERIAL_SET_ID, "index": 2}], -} -ENTITY_SET: Dict[str, Any] = { - "_id": MATERIAL_SET_ID, - "name": "H2+H", - "isEntitySet": True, - "entitySetType": "ordered", -} - -SET_MEMBER_MATERIALS_OUT_OF_ORDER: List[Dict[str, Any]] = [ - MATERIAL_FINAL, - MATERIAL_INITIAL, - MATERIAL_IMAGE, - ENTITY_SET, -] -EXPECTED_ORDERED_IDS = ["m-initial", "m-image", "m-final"] -EXPECTED_SINGLE_MEMBER_IDS = ["m-initial"] SILICON = "Silicon" SILICON_RELAXED = "Silicon relaxed" @@ -67,314 +24,6 @@ def _silicon_named(name: str) -> Dict[str, Any]: return {**Materials.get_by_name_first_match("Silicon"), "name": name} -def _client_with_list_responses(responses: List[List[Dict[str, Any]]]) -> MagicMock: - client = MagicMock() - client.materials.list.side_effect = responses - return client - - -def test_find_material_set_returns_first_match(): - client = _client_with_list_responses([[ENTITY_SET]]) - - material_set = find_material_set(client, OWNER_ID, MATERIAL_SET_NAME) - - assert material_set["_id"] == MATERIAL_SET_ID - client.materials.list.assert_called_once_with( - { - "owner._id": OWNER_ID, - "isEntitySet": True, - "name": {"$regex": re.escape(MATERIAL_SET_NAME), "$options": "i"}, - } - ) - assert "+" in MATERIAL_SET_NAME - assert re.escape(MATERIAL_SET_NAME) != MATERIAL_SET_NAME - - -def test_find_material_set_raises_when_missing(): - client = _client_with_list_responses([[]]) - - with pytest.raises(ValueError, match="No material set matching"): - find_material_set(client, OWNER_ID, MATERIAL_SET_NAME) - - -def test_find_material_set_rejects_unordered_when_order_required(): - client = _client_with_list_responses([[{**ENTITY_SET, "entitySetType": "unordered"}]]) - - with pytest.raises(ValueError, match="is 'unordered', not 'ordered'"): - find_material_set(client, OWNER_ID, MATERIAL_SET_NAME, require_ordered=True) - - -def test_list_materials_by_set_rejects_unordered_when_order_required(): - client = _client_with_list_responses([[{**ENTITY_SET, "entitySetType": "unordered"}]]) - - with pytest.raises(ValueError, match="is 'unordered', not 'ordered'"): - list_materials_by_set(client, OWNER_ID, MATERIAL_SET_NAME, require_ordered=True) - assert client.materials.list.call_count == 1 - - -def test_list_materials_in_set_does_not_re_resolve_the_set(): - client = _client_with_list_responses([SET_MEMBER_MATERIALS_OUT_OF_ORDER]) - - materials = list_materials_in_set(client, OWNER_ID, ENTITY_SET) - - assert [material["_id"] for material in materials] == EXPECTED_ORDERED_IDS - client.materials.list.assert_called_once_with( - {"owner._id": OWNER_ID, "inSet._id": MATERIAL_SET_ID, "isEntitySet": {"$ne": True}} - ) - - -@pytest.mark.parametrize( - ("members", "expected_ids"), - [ - (SET_MEMBER_MATERIALS_OUT_OF_ORDER, EXPECTED_ORDERED_IDS), - ([MATERIAL_INITIAL], EXPECTED_SINGLE_MEMBER_IDS), - ], -) -def test_list_materials_by_set_orders_by_inset_index(members, expected_ids): - client = _client_with_list_responses([[ENTITY_SET], members]) - - materials = list_materials_by_set(client, OWNER_ID, MATERIAL_SET_NAME) - - assert [material["_id"] for material in materials] == expected_ids - assert client.materials.list.call_args_list[1].args[0] == { - "owner._id": OWNER_ID, - "inSet._id": MATERIAL_SET_ID, - "isEntitySet": {"$ne": True}, - } - - -@pytest.mark.parametrize( - ("is_ordered", "expected_entity_set_type", "materials"), - [ - (True, "ordered", [MATERIAL_INITIAL, MATERIAL_FINAL]), - (False, "unordered", [MATERIAL_INITIAL]), - ], -) -def test_get_or_create_materials_set_creates_when_missing(is_ordered, expected_entity_set_type, materials): - client = _client_with_list_responses([[]]) - client.materials.create_set.return_value = { - **ENTITY_SET, - "entitySetType": expected_entity_set_type, - } - - materials_set = get_or_create_materials_set( - client, - OWNER_ID, - MATERIAL_SET_NAME, - materials, - is_ordered=is_ordered, - ) - - assert materials_set["_id"] == MATERIAL_SET_ID - client.materials.create_set.assert_called_once_with( - { - "name": MATERIAL_SET_NAME, - "owner": {"_id": OWNER_ID}, - "entitySetType": expected_entity_set_type, - } - ) - assert client.materials.move_to_set.call_args_list[0].args == ( - materials[0]["_id"], - "", - MATERIAL_SET_ID, - ) - - -def test_get_or_create_materials_set_reuses_when_found(): - client = _client_with_list_responses([[ENTITY_SET]]) - materials = [MATERIAL_INITIAL, MATERIAL_FINAL] - - materials_set = get_or_create_materials_set( - client, - OWNER_ID, - MATERIAL_SET_NAME, - materials, - is_ordered=True, - ) - - assert materials_set["_id"] == MATERIAL_SET_ID - client.materials.create_set.assert_not_called() - assert client.materials.move_to_set.call_args_list[0].args == ( - materials[0]["_id"], - "", - MATERIAL_SET_ID, - ) - - -def test_get_or_create_materials_set_rejects_reuse_with_mismatched_type(): - unordered_set = {**ENTITY_SET, "entitySetType": "unordered"} - client = _client_with_list_responses([[unordered_set]]) - - with pytest.raises(ValueError, match="already exists as 'unordered'"): - get_or_create_materials_set( - client, - OWNER_ID, - MATERIAL_SET_NAME, - [MATERIAL_INITIAL, MATERIAL_FINAL], - is_ordered=True, - ) - client.materials.move_to_set.assert_not_called() - - -def test_get_or_create_materials_set_ordered_requires_two_materials(): - client = MagicMock() - - with pytest.raises(ValueError, match="at least two materials"): - get_or_create_materials_set( - client, - OWNER_ID, - MATERIAL_SET_NAME, - [MATERIAL_INITIAL], - is_ordered=True, - ) - client.materials.list.assert_not_called() - - -def test_get_or_create_materials_set_requires_one_material(): - client = MagicMock() - - with pytest.raises(ValueError, match="at least one material"): - get_or_create_materials_set( - client, - OWNER_ID, - MATERIAL_SET_NAME, - [], - is_ordered=False, - ) - client.materials.list.assert_not_called() - - -DEFECTIVE_HASH = "hash-defective" -RELAXED_HASH = "hash-relaxed" -DEFECTIVE_MATERIAL = SimpleNamespace(hash=DEFECTIVE_HASH) -SAVED_DEFECTIVE: Dict[str, Any] = {"_id": "m-defective", "name": "B-vacancy h-BN", "hash": DEFECTIVE_HASH} -FINISHED_JOB: Dict[str, Any] = {"_id": "job-1", "name": "Fixed-cell Relaxation", "status": "finished"} -RELAXED_MATERIAL_DOC: Dict[str, Any] = { - **Materials.get_by_name_first_match("Silicon"), - "name": "B-vacancy h-BN relaxed", - "hash": RELAXED_HASH, -} -# Same hash as the input material: an SCF's own output, not a relaxation. -SCF_MATERIAL_DOC: Dict[str, Any] = { - **Materials.get_by_name_first_match("Silicon"), - "name": "B-vacancy h-BN", - "hash": DEFECTIVE_HASH, -} - - -def test_find_relaxed_material_returns_final_structure_from_the_job(): - client = MagicMock() - client.materials.list.return_value = [SAVED_DEFECTIVE] - client.jobs.list.return_value = [FINISHED_JOB] - client.properties.get_for_job.return_value = [{"materialId": "m-relaxed"}] - client.materials.get.return_value = RELAXED_MATERIAL_DOC - - relaxed = find_relaxed_material(client, DEFECTIVE_MATERIAL, OWNER_ID) - - assert relaxed is not None - assert relaxed.name == "B-vacancy h-BN relaxed" - client.materials.list.assert_called_once_with({"hash": DEFECTIVE_HASH, "owner._id": OWNER_ID}) - client.jobs.list.assert_called_once_with( - {"_material._id": {"$in": [SAVED_DEFECTIVE["_id"]]}, "owner._id": OWNER_ID, "status": "finished"} - ) - client.properties.get_for_job.assert_called_once_with(FINISHED_JOB["_id"], "final_structure") - client.materials.get.assert_called_once_with("m-relaxed") - - -def test_find_relaxed_material_uses_the_last_final_structure_entry(): - # A relaxation job's final_structure property can carry more than one entry: the initial - # structure (same hash as the input) first, the relaxed one last -- PLAN #27. - client = MagicMock() - client.materials.list.return_value = [SAVED_DEFECTIVE] - client.jobs.list.return_value = [FINISHED_JOB] - client.properties.get_for_job.return_value = [{"materialId": "m-initial"}, {"materialId": "m-relaxed"}] - client.materials.get.side_effect = lambda material_id: { - "m-initial": SCF_MATERIAL_DOC, - "m-relaxed": RELAXED_MATERIAL_DOC, - }[material_id] - - relaxed = find_relaxed_material(client, DEFECTIVE_MATERIAL, OWNER_ID) - - assert relaxed is not None - assert relaxed.name == "B-vacancy h-BN relaxed" - client.materials.get.assert_called_once_with("m-relaxed") - - -def test_find_relaxed_material_returns_none_when_material_is_not_on_the_platform(): - client = MagicMock() - client.materials.list.return_value = [] - client.jobs.list.return_value = [] - - assert find_relaxed_material(client, DEFECTIVE_MATERIAL, OWNER_ID) is None - assert client.jobs.list.call_args.args[0]["_material._id"] == {"$in": []} - - -def test_find_relaxed_material_returns_none_when_no_job_exists(): - client = MagicMock() - client.materials.list.return_value = [SAVED_DEFECTIVE] - client.jobs.list.return_value = [] - - assert find_relaxed_material(client, DEFECTIVE_MATERIAL, OWNER_ID) is None - client.properties.get_for_job.assert_not_called() - - -def test_find_relaxed_material_returns_none_when_job_has_no_final_structure(): - client = MagicMock() - client.materials.list.return_value = [SAVED_DEFECTIVE] - client.jobs.list.return_value = [FINISHED_JOB] - client.properties.get_for_job.return_value = [] - - assert find_relaxed_material(client, DEFECTIVE_MATERIAL, OWNER_ID) is None - client.materials.get.assert_not_called() - - -def test_find_relaxed_material_checks_every_same_hash_material(): - other_material: Dict[str, Any] = {"_id": "m-other", "name": "B-vacancy h-BN", "hash": DEFECTIVE_HASH} - client = MagicMock() - client.materials.list.return_value = [other_material, SAVED_DEFECTIVE] - client.jobs.list.return_value = [FINISHED_JOB] - client.properties.get_for_job.return_value = [{"materialId": "m-relaxed"}] - client.materials.get.return_value = RELAXED_MATERIAL_DOC - - relaxed = find_relaxed_material(client, DEFECTIVE_MATERIAL, OWNER_ID) - - assert relaxed is not None - assert relaxed.name == "B-vacancy h-BN relaxed" - client.jobs.list.assert_called_once_with( - {"_material._id": {"$in": ["m-other", "m-defective"]}, "owner._id": OWNER_ID, "status": "finished"} - ) - - -def test_find_relaxed_material_skips_a_final_structure_with_the_same_hash(): - scf_job: Dict[str, Any] = {"_id": "job-scf", "name": "Total Energy", "status": "finished"} - relax_job: Dict[str, Any] = {"_id": "job-relax", "name": "Fixed-cell Relaxation", "status": "finished"} - client = MagicMock() - client.materials.list.return_value = [SAVED_DEFECTIVE] - client.jobs.list.return_value = [scf_job, relax_job] - client.properties.get_for_job.side_effect = [[{"materialId": "m-scf"}], [{"materialId": "m-relaxed"}]] - client.materials.get.side_effect = [SCF_MATERIAL_DOC, RELAXED_MATERIAL_DOC] - - relaxed = find_relaxed_material(client, DEFECTIVE_MATERIAL, OWNER_ID) - - assert relaxed is not None - assert relaxed.name == "B-vacancy h-BN relaxed" - assert client.properties.get_for_job.call_count == 2 - - -def test_find_relaxed_material_matches_the_relaxation_kgrid(): - client = MagicMock() - client.materials.list.return_value = [SAVED_DEFECTIVE] - client.jobs.list.return_value = [FINISHED_JOB] - client.properties.get_for_job.return_value = [{"materialId": "m-relaxed"}] - client.materials.get.return_value = RELAXED_MATERIAL_DOC - - relaxed = find_relaxed_material(client, DEFECTIVE_MATERIAL, OWNER_ID, kgrid=[4, 4, 4], unit_name="pw_vc-relax") - - assert relaxed is not None - assert relaxed.name == "B-vacancy h-BN relaxed" - assert get_kgrid_query([4, 4, 4], "pw_vc-relax").items() <= client.jobs.list.call_args.args[0].items() - - @pytest.mark.parametrize( ("folder_names", "account_names", "name", "expected_name"), [ @@ -419,31 +68,6 @@ def test_load_material_raises_when_the_name_is_missing_or_ambiguous(tmp_path, fo load_material(client, str(tmp_path), name, OWNER_ID) -JOB_ID = "job-1" -FINAL_STRUCTURE_MATERIAL_ID = "m-final-structure" - - -@pytest.mark.parametrize( - ("properties", "error"), - [ - ([{"materialId": FINAL_STRUCTURE_MATERIAL_ID}], None), - ([], "reported no 'final_structure'"), - ], -) -def test_get_final_structure_for_job(properties, error): - client = MagicMock() - client.properties.get_for_job.return_value = properties - client.materials.get.return_value = Materials.get_by_name_first_match("Silicon") - if error: - with pytest.raises(RuntimeError, match=error): - get_final_structure_for_job(client, JOB_ID) - return - material = get_final_structure_for_job(client, JOB_ID) - assert material.basis.elements.values == ["Si", "Si"] - client.properties.get_for_job.assert_called_once_with(JOB_ID, "final_structure") - client.materials.get.assert_called_once_with(FINAL_STRUCTURE_MATERIAL_ID) - - @pytest.mark.parametrize( ("names", "name", "expected_name"), [ @@ -468,3 +92,12 @@ def test_select_material_by_name_takes_the_exact_name_or_a_unique_partial_one(na def test_select_material_by_name_raises_when_the_name_is_missing_or_ambiguous(names, name, error): with pytest.raises(ValueError, match=error): select_material_by_name([Material.create(_silicon_named(candidate)) for candidate in names], name) + + +def test_get_or_create_materials_set_takes_saved_material_dicts(): + client = MagicMock() + client.materials.list.return_value = [{"_id": "set-1", "name": SILICON, "entitySetType": "unordered"}] + + get_or_create_materials_set(client, OWNER_ID, SILICON, [{**_silicon_named(SILICON), "_id": "m-1"}]) + + client.materials.move_to_set.assert_called_once_with("m-1", "", "set-1") diff --git a/tests/py/unit/core/entity/test_property_api.py b/tests/py/unit/core/entity/test_property_api.py deleted file mode 100644 index f1693bc32..000000000 --- a/tests/py/unit/core/entity/test_property_api.py +++ /dev/null @@ -1,129 +0,0 @@ -"""Unit tests for core.entity.property.api.""" - -from unittest.mock import MagicMock - -import pytest -from mat3ra.notebooks_utils.core.entity.property.api import find_total_energy_for_material - -MATERIAL_ID = "material-a" -EXABYTE_ID = "exabyte-a" -MATERIAL = {"_id": MATERIAL_ID, "exabyteId": EXABYTE_ID} -OWNER_ACCOUNT_ID = "account-a" -GROUP = "qe:dft:lda:pz" -PRECISION_VALUE = 1116 -TOTAL_ENERGY_PROPERTY = {"data": {"value": -12.34}, "precision": {"value": 0.001}} - - -def _client(): - client = MagicMock() - client.materials.get.return_value = MATERIAL - client.properties.list.return_value = [TOTAL_ENERGY_PROPERTY] - client.my_account.id = OWNER_ACCOUNT_ID - # entity_cache is often None right after auth -- this must not be relied on. - client.my_account.entity_cache = None - return client - - -def test_find_total_energy_for_material_defaults_to_my_account_scope(): - client = _client() - - result = find_total_energy_for_material(client, MATERIAL_ID) - - client.materials.get.assert_called_once_with(MATERIAL_ID) - client.properties.list.assert_called_once_with( - query={ - "exabyteId": EXABYTE_ID, - "slug": "total_energy", - "owner._id": OWNER_ACCOUNT_ID, - }, - projection={"sort": {"precision.value": -1}, "limit": 1}, - ) - client.jobs.list.assert_not_called() - assert result == TOTAL_ENERGY_PROPERTY - - -def test_find_total_energy_for_material_my_account_scope(): - client = _client() - - find_total_energy_for_material(client, MATERIAL_ID, source="my_account") - - client.properties.list.assert_called_once_with( - query={ - "exabyteId": EXABYTE_ID, - "slug": "total_energy", - "owner._id": OWNER_ACCOUNT_ID, - }, - projection={"sort": {"precision.value": -1}, "limit": 1}, - ) - - -def test_find_total_energy_for_material_curators_scope(): - client = _client() - - find_total_energy_for_material(client, MATERIAL_ID, source="curators") - - client.properties.list.assert_called_once_with( - query={ - "exabyteId": EXABYTE_ID, - "slug": "total_energy", - "owner.slug": "curators", - }, - projection={"sort": {"precision.value": -1}, "limit": 1}, - ) - - -def test_find_total_energy_for_material_public_scope_has_no_owner_filter(): - client = _client() - - find_total_energy_for_material(client, MATERIAL_ID, source="public") - - client.properties.list.assert_called_once_with( - query={ - "exabyteId": EXABYTE_ID, - "slug": "total_energy", - }, - projection={"sort": {"precision.value": -1}, "limit": 1}, - ) - - -def test_find_total_energy_for_material_constrains_group_and_precision(): - client = _client() - - find_total_energy_for_material(client, MATERIAL_ID, group=GROUP, precision_value=PRECISION_VALUE) - - client.properties.list.assert_called_once_with( - query={ - "exabyteId": EXABYTE_ID, - "slug": "total_energy", - "group": GROUP, - "precision.value": PRECISION_VALUE, - "owner._id": OWNER_ACCOUNT_ID, - }, - projection={"sort": {"precision.value": -1}, "limit": 1}, - ) - - -def test_find_total_energy_for_material_rejects_invalid_source(): - client = _client() - - with pytest.raises(ValueError, match="Invalid source"): - find_total_energy_for_material(client, MATERIAL_ID, source="everyone") - - -def test_find_total_energy_for_material_returns_none_when_no_property_found(): - client = _client() - client.properties.list.return_value = [] - - result = find_total_energy_for_material(client, MATERIAL_ID) - - assert result is None - - -def test_find_total_energy_for_material_returns_none_when_material_has_no_exabyte_id(): - client = _client() - client.materials.get.return_value = {"_id": MATERIAL_ID} - - result = find_total_energy_for_material(client, MATERIAL_ID) - - client.properties.list.assert_not_called() - assert result is None diff --git a/tests/py/unit/core/entity/test_workflow_api.py b/tests/py/unit/core/entity/test_workflow_api.py index 337db1851..4cce44cbc 100644 --- a/tests/py/unit/core/entity/test_workflow_api.py +++ b/tests/py/unit/core/entity/test_workflow_api.py @@ -1,40 +1,16 @@ -import pytest -from mat3ra.notebooks_utils.core.entity.workflow.api import set_execution_unit_input +from unittest.mock import MagicMock +from mat3ra.notebooks_utils.core.entity.workflow.api import get_or_create_workflow +from mat3ra.standata.workflows import WorkflowStandata +from mat3ra.wode import Workflow -def _unit(): - return { - "name": "custom_script", - "input": [ - {"template": {"name": "script.py", "content": "original"}}, - {"template": {"name": "requirements.txt", "content": ""}}, - ], - } +SAVED_WORKFLOW = {**WorkflowStandata.get_by_name_first_match("total_energy"), "_id": "workflow-1"} -def test_replaces_the_named_input_and_marks_it_manually_changed(): - """isManuallyChanged is what stops the platform re-rendering the runner's placeholders.""" - unit = _unit() - set_execution_unit_input(unit, "requirements.txt", "numpy<2\n") +def test_get_or_create_workflow_returns_the_saved_workflow_dict(): + client = MagicMock() + client.workflows.list.return_value = [SAVED_WORKFLOW] - changed = unit["input"][1] - assert changed["template"]["content"] == "numpy<2\n" - assert changed["rendered"] == "numpy<2\n" - assert changed["isManuallyChanged"] is True - assert unit["input"][0]["template"]["content"] == "original", "other inputs are untouched" + workflow = get_or_create_workflow(client, Workflow.create(SAVED_WORKFLOW), "account-1") - -def test_matches_by_name_not_position(): - """A flavor may list its inputs in any order; position would write into the wrong file.""" - unit = _unit() - unit["input"].reverse() - set_execution_unit_input(unit, "script.py", "print(1)") - - by_name = {item["template"]["name"]: item for item in unit["input"]} - assert by_name["script.py"]["rendered"] == "print(1)" - assert "rendered" not in by_name["requirements.txt"] - - -def test_unknown_input_name_is_an_error_naming_what_is_available(): - with pytest.raises(KeyError, match="requirements.txt"): - set_execution_unit_input(_unit(), "nope.txt", "x") + assert workflow["_id"] == SAVED_WORKFLOW["_id"] diff --git a/tests/py/unit/test_auth_retry.py b/tests/py/unit/test_auth_retry.py index cd45fcf0d..c94f3312d 100644 --- a/tests/py/unit/test_auth_retry.py +++ b/tests/py/unit/test_auth_retry.py @@ -6,9 +6,9 @@ import pytest import requests from mat3ra.api_client import ACCESS_TOKEN_ENV_VAR, AuthContext +from mat3ra.api_client.tools.auth import token as file_token_store from mat3ra.notebooks_utils import auth, token_store from mat3ra.notebooks_utils.api.job import wait_for_jobs_to_finish_async -from mat3ra.notebooks_utils.core.api import token_store as file_token_store POLL_INTERVAL_SECONDS = 0.01 CACHED_TOKEN_DATA = {"access_token": "cached-token", "expires_in": 3600} @@ -36,7 +36,7 @@ async def completed_device_login(show_popup): ], ) async def test_wait_for_jobs_to_finish_async(monkeypatch, tmp_path, status_results, expectation, expected_access_token): - monkeypatch.setattr(file_token_store, "_FILE_PATH", str(tmp_path / "oidc_token_cache.json")) + monkeypatch.setattr(file_token_store, "OIDC_TOKEN_CACHE_FILENAME", str(tmp_path / "oidc_token_cache.json")) monkeypatch.setattr(auth, "authenticate_oidc", completed_device_login) monkeypatch.setenv(ACCESS_TOKEN_ENV_VAR, CACHED_TOKEN_DATA["access_token"]) auth_context = AuthContext(access_token=CACHED_TOKEN_DATA["access_token"]) @@ -57,7 +57,7 @@ async def test_wait_for_jobs_to_finish_async(monkeypatch, tmp_path, status_resul ], ) async def test_authenticate(monkeypatch, tmp_path, environment_token, token_check_error, checked_token, expected_token): - monkeypatch.setattr(file_token_store, "_FILE_PATH", str(tmp_path / "oidc_token_cache.json")) + monkeypatch.setattr(file_token_store, "OIDC_TOKEN_CACHE_FILENAME", str(tmp_path / "oidc_token_cache.json")) monkeypatch.setattr(auth, "authenticate_oidc", completed_device_login) api_client = MagicMock() api_client.authenticate.return_value.list_accounts.side_effect = token_check_error diff --git a/tests/py/unit/test_workflow_utils.py b/tests/py/unit/test_workflow_utils.py deleted file mode 100644 index 3f8dd32e0..000000000 --- a/tests/py/unit/test_workflow_utils.py +++ /dev/null @@ -1,156 +0,0 @@ -import pytest -from mat3ra.made.material import Material -from mat3ra.notebooks_utils.workflow import ( - apply_planewave_cutoffs, - apply_scf_kgrid, - kgrid_from_density, - patch_workflow_qe_input, - set_assignment_value, -) -from mat3ra.standata.workflows import WorkflowStandata -from mat3ra.wode.workflows import Workflow - -FIXED_CELL_RELAXATION = "fixed_cell_relaxation.json" -RELAX_UNIT_NAMES = ["pw_relax"] -SURFACE_ENERGY_WORKFLOW = "surface_energy.json" -SCF_KGRID = [4, 4, 1] - - -def _relax_workflow(): - config = WorkflowStandata.filter_by_application("espresso").get_by_name_first_match(FIXED_CELL_RELAXATION) - return Workflow.create(config) - - -def _pw_relax_content(workflow): - return workflow.subworkflows[0].get_unit_by_name(name="pw_relax").input[0].template.content - - -@pytest.mark.parametrize( - "parameters,present,absent,error", - [ - ( - {"system": {"vdw_corr": "d3_grimme"}, "electrons": {"mixing_beta": 0.5, "diago_full_acc": True}}, - ["vdw_corr = 'd3_grimme'", "{{ input.IBRAV }}", "mixing_beta = 0.5", "diago_full_acc = .true."], - ["mixing_beta = 0.3"], - None, - ), - ({"FAKESECTION": {"x": 1}}, [], [], "Namelist '&FAKESECTION' not found."), - ], -) -def test_patch_workflow_qe_input(parameters, present, absent, error): - workflow = _relax_workflow() - if error: - with pytest.raises(ValueError, match=error): - patch_workflow_qe_input(workflow, parameters, unit_names=RELAX_UNIT_NAMES) - return - patch_workflow_qe_input(workflow, parameters, unit_names=RELAX_UNIT_NAMES) - content = _pw_relax_content(workflow) - for text in present: - assert text in content - for text in absent: - assert text not in content - - -def _surface_workflow(): - config = WorkflowStandata.filter_by_application("espresso").get_by_name_first_match(SURFACE_ENERGY_WORKFLOW) - return Workflow.create(config) - - -def _material_stub(number_of_atoms=2, reciprocal_vector_ratios=[1.0, 1.0, 0.5]): - """A real `Material` whose orthorhombic lattice yields the requested ratios.""" - a, b, c = (2.0 / ratio for ratio in reciprocal_vector_ratios) - return Material.create( - { - "name": "test", - "lattice": { - "a": a, - "b": b, - "c": c, - "alpha": 90, - "beta": 90, - "gamma": 90, - "type": "ORC", - "units": {"length": "angstrom", "angle": "degree"}, - }, - "basis": { - "elements": [{"id": i, "value": "Si"} for i in range(number_of_atoms)], - "coordinates": [{"id": i, "value": [i * 0.1] * 3} for i in range(number_of_atoms)], - "units": "crystal", - }, - } - ) - - -def test_apply_scf_kgrid_updates_pw_scf_context(): - workflow = _surface_workflow() - apply_scf_kgrid(workflow, scf_kgrid=SCF_KGRID, first_only=True, material=_material_stub()) - unit = next( - subworkflow.get_unit_by_name(name="pw_scf") - for subworkflow in workflow.subworkflows - if subworkflow.get_unit_by_name(name="pw_scf") - ) - kgrid_item = next(item for item in unit.context if item.get("name") == "kgrid") - assert kgrid_item["data"]["dimensions"] == SCF_KGRID - # KPPRA is per reciprocal atom, and the ratios come from the lattice -- both via `material`. - assert kgrid_item["data"]["gridMetricValue"] == 4 * 4 * 1 * 2 - assert kgrid_item["data"]["reciprocalVectorRatios"] == [1.0, 1.0, 0.5] - - -def _lattice_material(a, b, c): - return Material.create( - { - "name": "test", - "lattice": { - "a": a, - "b": b, - "c": c, - "alpha": 90, - "beta": 90, - "gamma": 90, - "type": "ORC", - "units": {"length": "angstrom", "angle": "degree"}, - }, - "basis": { - "elements": [{"id": 0, "value": "Si"}], - "coordinates": [{"id": 0, "value": [0, 0, 0]}], - "units": "crystal", - }, - } - ) - - -def test_kgrid_from_density_monolayer(): - material = _lattice_material(a=15.05, b=8.69, c=20.0) - assert kgrid_from_density(material, 6, periodic_dims=(0, 1)) == [3, 5, 1] - - -def test_kgrid_from_density_cubic(): - material = _lattice_material(a=5.0, b=5.0, c=5.0) - assert kgrid_from_density(material, 6) == [8, 8, 8] - - -@pytest.mark.parametrize("wavefunction,density", [(40, 200), (60, 480)]) -def test_apply_planewave_cutoffs_updates_pw_relax_context(wavefunction, density): - workflow = _relax_workflow() - apply_planewave_cutoffs(workflow, wavefunction, density, unit_name="pw_relax") - unit = workflow.subworkflows[0].get_unit_by_name(name="pw_relax") - cutoffs_item = next(item for item in unit.context if item.get("name") == "cutoffs") - assert cutoffs_item["data"]["wavefunction"] == float(wavefunction) - assert cutoffs_item["data"]["density"] == float(density) - - -def test_set_assignment_value_sets_every_unit_of_that_name(): - config = WorkflowStandata.filter_by_application("espresso").get_by_name_first_match(SURFACE_ENERGY_WORKFLOW) - workflow = set_assignment_value(Workflow.create(config), "assign-bulk-id", "'bulk-1'") - units = [ - subworkflow.get_unit_by_name(name="assign-bulk-id") - for subworkflow in workflow.subworkflows - if subworkflow.get_unit_by_name(name="assign-bulk-id") - ] - assert units - assert all(unit.value == "'bulk-1'" for unit in units) - - -def test_set_assignment_value_raises_for_an_unknown_unit(): - with pytest.raises(ValueError, match="no 'assign-nothing' unit"): - set_assignment_value(_relax_workflow(), "assign-nothing", "1")