Skip to content

Commit

Permalink
Added singlepoint files + added route to main
Browse files Browse the repository at this point in the history
  • Loading branch information
Cbameron12 committed Jan 22, 2025
1 parent eeb9ca5 commit 0642f42
Show file tree
Hide file tree
Showing 3 changed files with 135 additions and 1 deletion.
63 changes: 63 additions & 0 deletions api/endpoints/singlepoint_route.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
"""Contains routes for performing singlepoint calculations."""

from __future__ import annotations

import logging
from pathlib import Path
from typing import Annotated, Any

from fastapi import APIRouter, HTTPException, Query

from api.utils.singlepoint_helper import singlepoint

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/singlepoint", tags=["calculations"])


@router.get("/")
def get_singlepoint(
struct: Annotated[str, Query()],
arch: Annotated[str | None, Query("mace_mp")],
properties: Annotated[list[str] | None, Query(None)],
range_selector: Annotated[str | None, Query(":")],
) -> dict[str, Any]:
"""
Endpoint to perform single point calculations and return results.
Parameters
----------
struct : str
The filename of the dataset to perform calculations on.
arch : str
The name of the model to perform the calculations with.
properties : List[str]
The properties to calculate.
range_selector : str
The range of indicies to read from the data structure.
Returns
-------
Dict[str, Any]
Results of the single point calculations.
Raises
------
HTTPException
If there is an error during the call.
"""
base_dir = Path("data")
struct_path = base_dir / struct
try:
results = singlepoint(
struct=struct_path,
arch=arch,
properties=properties,
range_selector=range_selector,
)
if "error" in results:
raise HTTPException(status_code=500, detail=results["error"])
return results
except Exception as e:
logger.error(e)
raise HTTPException(status_code=500, detail="Internal Server Error") from e
70 changes: 70 additions & 0 deletions api/utils/singlepoint_helper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
"""Helper functions for performing singeploint calculations."""

from __future__ import annotations

from pathlib import Path
from typing import Any

from janus_core.calculations.single_point import SinglePoint
import numpy as np


def singlepoint(
struct: Path,
arch: str | None = "mace_mp",
properties: list[str] | None = None,
range_selector: str | None = ":",
) -> dict[str, Any]:
"""
Perform single point calculations and return results.
Parameters
----------
struct : str
Filename of structure to simulate.
arch : str
MLIP architecture to use for single point calculations. Default is "mace_mp".
properties : List[str]
Physical properties to calculate. Default is ("energy", "forces", "stress").
range_selector : str
Range of indices to include from the structure. Default is all.
Returns
-------
Dict[str, Any]
Results of the single point calculations.
"""
read_kwargs = {"index": range_selector}
if properties == "all properties":
properties = None

singlepoint_kwargs = {
"struct_path": struct,
"properties": properties,
"arch": arch,
"device": "cpu",
"read_kwargs": read_kwargs,
}
print(singlepoint_kwargs)

s_point = SinglePoint(**singlepoint_kwargs)

s_point.run()

results = s_point.results

# Convert numpy arrays to lists
for key, value in results.items():
if isinstance(value, np.ndarray):
results[key] = value.tolist()

return results


if __name__ == "__main__":
results = singlepoint(
struct=Path("janus-web/data/input.data.2055.xyz"),
range_selector="0:1",
properties=["stress"],
)
print(results)
3 changes: 2 additions & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@

from fastapi import FastAPI

from api.endpoints import upload_route
from api.endpoints import singlepoint_route, upload_route
import logging_config

app = FastAPI()

app.include_router(upload_route.router)
app.include_router(singlepoint_route.router)

if __name__ == "__main__":
import uvicorn
Expand Down

0 comments on commit 0642f42

Please sign in to comment.